llvm.org GIT mirror llvm / 2447312
SwitchInst refactoring. The purpose of refactoring is to hide operand roles from SwitchInst user (programmer). If you want to play with operands directly, probably you will need lower level methods than SwitchInst ones (TerminatorInst or may be User). After this patch we can reorganize SwitchInst operands and successors as we want. What was done: 1. Changed semantics of index inside the getCaseValue method: getCaseValue(0) means "get first case", not a condition. Use getCondition() if you want to resolve the condition. I propose don't mix SwitchInst case indexing with low level indexing (TI successors indexing, User's operands indexing), since it may be dangerous. 2. By the same reason findCaseValue(ConstantInt*) returns actual number of case value. 0 means first case, not default. If there is no case with given value, ErrorIndex will returned. 3. Added getCaseSuccessor method. I propose to avoid usage of TerminatorInst::getSuccessor if you want to resolve case successor BB. Use getCaseSuccessor instead, since internal SwitchInst organization of operands/successors is hidden and may be changed in any moment. 4. Added resolveSuccessorIndex and resolveCaseIndex. The main purpose of these methods is to see how case successors are really mapped in TerminatorInst. 4.1 "resolveSuccessorIndex" was created if you need to level down from SwitchInst to TerminatorInst. It returns TerminatorInst's successor index for given case successor. 4.2 "resolveCaseIndex" converts low level successors index to case index that curresponds to the given successor. Note: There are also related compatability fix patches for dragonegg, klee, llvm-gcc-4.0, llvm-gcc-4.2, safecode, clang. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@149481 91177308-0d34-0410-b5e6-96231b3b80d8 Stepan Dyatkovskiy 7 years ago
26 changed file(s) with 210 addition(s) and 145 deletion(s). Raw diff Collapse all Expand all
9494
9595 std::string Str;
9696 raw_string_ostream OS(Str);
97 OS << SI->getCaseValue(SuccNo)->getValue();
97 unsigned Case = SI->resolveCaseIndex(SuccNo);
98 OS << SI->getCaseValue(Case)->getValue();
9899 return OS.str();
99100 }
100101 return "";
2323 #include "llvm/ADT/SmallVector.h"
2424 #include "llvm/Support/ErrorHandling.h"
2525 #include
26 #include
2627
2728 namespace llvm {
2829
24662467 protected:
24672468 virtual SwitchInst *clone_impl() const;
24682469 public:
2470
2471 enum { ErrorIndex = UINT_MAX };
2472
24692473 static SwitchInst *Create(Value *Value, BasicBlock *Default,
24702474 unsigned NumCases, Instruction *InsertBefore = 0) {
24712475 return new SwitchInst(Value, Default, NumCases, InsertBefore);
24872491 return cast(getOperand(1));
24882492 }
24892493
2490 /// getNumCases - return the number of 'cases' in this switch instruction.
2491 /// Note that case #0 is always the default case.
2494 void setDefaultDest(BasicBlock *DefaultCase) {
2495 setOperand(1, reinterpret_cast(DefaultCase));
2496 }
2497
2498 /// getNumCases - return the number of 'cases' in this switch instruction,
2499 /// except the default case
24922500 unsigned getNumCases() const {
2493 return getNumOperands()/2;
2494 }
2495
2496 /// getCaseValue - Return the specified case value. Note that case #0, the
2497 /// default destination, does not have a case value.
2501 return getNumOperands()/2 - 1;
2502 }
2503
2504 /// getCaseValue - Return the specified case value. Note that case #0, means
2505 /// first case, not a default case.
24982506 ConstantInt *getCaseValue(unsigned i) {
2499 assert(i && i < getNumCases() && "Illegal case value to get!");
2500 return getSuccessorValue(i);
2501 }
2502
2503 /// getCaseValue - Return the specified case value. Note that case #0, the
2504 /// default destination, does not have a case value.
2507 assert(i < getNumCases() && "Illegal case value to get!");
2508 return reinterpret_cast(getOperand(2 + i*2));
2509 }
2510
2511 /// getCaseValue - Return the specified case value. Note that case #0, means
2512 /// first case, not a default case.
25052513 const ConstantInt *getCaseValue(unsigned i) const {
2506 assert(i && i < getNumCases() && "Illegal case value to get!");
2507 return getSuccessorValue(i);
2514 assert(i < getNumCases() && "Illegal case value to get!");
2515 return reinterpret_cast(getOperand(2 + i*2));
2516 }
2517
2518 // setSuccessorValue - Updates the value associated with the specified
2519 // case.
2520 void setCaseValue(unsigned i, ConstantInt *CaseValue) {
2521 assert(i < getNumCases() && "Case index # out of range!");
2522 setOperand(2 + i*2, reinterpret_cast(CaseValue));
25082523 }
25092524
25102525 /// findCaseValue - Search all of the case values for the specified constant.
25112526 /// If it is explicitly handled, return the case number of it, otherwise
2512 /// return 0 to indicate that it is handled by the default handler.
2527 /// return ErrorIndex to indicate that it is handled by the default handler.
25132528 unsigned findCaseValue(const ConstantInt *C) const {
2514 for (unsigned i = 1, e = getNumCases(); i != e; ++i)
2529 for (unsigned i = 0, e = getNumCases(); i != e; ++i)
25152530 if (getCaseValue(i) == C)
25162531 return i;
2517 return 0;
2532 return ErrorIndex;
2533 }
2534
2535 /// resolveSuccessorIndex - Converts case index to index of its successor
2536 /// index in TerminatorInst successors collection.
2537 /// If CaseIndex == ErrorIndex, "default" successor will returned then.
2538 unsigned resolveSuccessorIndex(unsigned CaseIndex) const {
2539 assert((CaseIndex == ErrorIndex || CaseIndex < getNumCases()) &&
2540 "Case index # out of range!");
2541 return CaseIndex != ErrorIndex ? CaseIndex + 1 : 0;
2542 }
2543
2544 /// resolveCaseIndex - Converts index of successor in TerminatorInst
2545 /// collection to index of case that corresponds to this successor.
2546 unsigned resolveCaseIndex(unsigned SuccessorIndex) const {
2547 assert(SuccessorIndex < getNumSuccessors() &&
2548 "Successor index # out of range!");
2549 return SuccessorIndex != 0 ? SuccessorIndex - 1 : ErrorIndex;
25182550 }
25192551
25202552 /// findCaseDest - Finds the unique case value for a given successor. Returns
25232555 if (BB == getDefaultDest()) return NULL;
25242556
25252557 ConstantInt *CI = NULL;
2526 for (unsigned i = 1, e = getNumCases(); i != e; ++i) {
2527 if (getSuccessor(i) == BB) {
2558 for (unsigned i = 0, e = getNumCases(); i != e; ++i) {
2559 if (getSuccessor(i + 1) == BB) {
25282560 if (CI) return NULL; // Multiple cases lead to BB.
25292561 else CI = getCaseValue(i);
25302562 }
25362568 ///
25372569 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
25382570
2539 /// removeCase - This method removes the specified successor from the switch
2540 /// instruction. Note that this cannot be used to remove the default
2541 /// destination (successor #0). Also note that this operation may reorder the
2571 /// removeCase - This method removes the specified case and its successor
2572 /// from the switch instruction. Note that this operation may reorder the
25422573 /// remaining cases at index idx and above.
25432574 ///
25442575 void removeCase(unsigned idx);
25512582 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
25522583 assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
25532584 setOperand(idx*2+1, (Value*)NewSucc);
2585 }
2586
2587 /// Resolves successor for idx-th case.
2588 /// Use getCaseSuccessor instead of TerminatorInst::getSuccessor,
2589 /// since internal SwitchInst organization of operands/successors is
2590 /// hidden and may be changed in any moment.
2591 BasicBlock *getCaseSuccessor(unsigned idx) const {
2592 return getSuccessor(resolveSuccessorIndex(idx));
2593 }
2594
2595 /// Set new successor for idx-th case.
2596 /// Use setCaseSuccessor instead of TerminatorInst::setSuccessor,
2597 /// since internal SwitchInst organization of operands/successors is
2598 /// hidden and may be changed in any moment.
2599 void setCaseSuccessor(unsigned idx, BasicBlock *NewSucc) {
2600 setSuccessor(resolveSuccessorIndex(idx), NewSucc);
25542601 }
25552602
25562603 // getSuccessorValue - Return the value associated with the specified
853853 // BBFrom to BBTo.
854854 unsigned NumEdges = 0;
855855 ConstantInt *EdgeVal = 0;
856 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
857 if (SI->getSuccessor(i) != BBTo) continue;
856 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
857 if (SI->getCaseSuccessor(i) != BBTo) continue;
858858 if (NumEdges++) break;
859859 EdgeVal = SI->getCaseValue(i);
860860 }
194194 return;
195195 }
196196
197 Succs[SI.findCaseValue(cast(C))] = true;
197 unsigned CCase = SI.findCaseValue(cast(C));
198 Succs[SI.resolveSuccessorIndex(CCase)] = true;
198199 }
199200
200201
11611161 }
11621162 break;
11631163 case Instruction::Switch:
1164 Code = bitc::FUNC_CODE_INST_SWITCH;
1165 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1166 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1167 Vals.push_back(VE.getValueID(I.getOperand(i)));
1164 {
1165 Code = bitc::FUNC_CODE_INST_SWITCH;
1166 SwitchInst &SI = cast(I);
1167 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1168 Vals.push_back(VE.getValueID(SI.getCondition()));
1169 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1170 for (unsigned i = 0, e = SI.getNumCases(); i != e; ++i) {
1171 Vals.push_back(VE.getValueID(SI.getCaseValue(i)));
1172 Vals.push_back(VE.getValueID(SI.getCaseSuccessor(i)));
1173 }
1174 }
11681175 break;
11691176 case Instruction::IndirectBr:
11701177 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
22082208
22092209 CaseRange LHSR(CR.Range.first, Pivot);
22102210 CaseRange RHSR(Pivot, CR.Range.second);
2211 Constant *C = Pivot->Low;
2211 const Constant *C = Pivot->Low;
22122212 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
22132213
22142214 // We know that we branch to the LHS if the Value being switched on is
24012401
24022402 BranchProbabilityInfo *BPI = FuncInfo.BPI;
24032403 // Start with "simple" cases
2404 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2405 BasicBlock *SuccBB = SI.getSuccessor(i);
2404 for (size_t i = 0; i < SI.getNumCases(); ++i) {
2405 BasicBlock *SuccBB = SI.getCaseSuccessor(i);
24062406 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
24072407
24082408 uint32_t ExtraWeight = BPI ? BPI->getEdgeWeight(SI.getParent(), SuccBB) : 0;
24092409
2410 Cases.push_back(Case(SI.getSuccessorValue(i),
2411 SI.getSuccessorValue(i),
2410 Cases.push_back(Case(SI.getCaseValue(i),
2411 SI.getCaseValue(i),
24122412 SMBB, ExtraWeight));
24132413 }
24142414 std::sort(Cases.begin(), Cases.end(), CaseCmp());
24752475
24762476 // If there is only the default destination, branch to it if it is not the
24772477 // next basic block. Otherwise, just fall through.
2478 if (SI.getNumCases() == 1) {
2478 if (!SI.getNumCases()) {
24792479 // Update machine-CFG edges.
24802480
24812481 // If this is not a fall-through branch, emit the branch.
129129 /// Case - A struct to record the Value for a switch case, and the
130130 /// case's target basic block.
131131 struct Case {
132 Constant* Low;
133 Constant* High;
132 const Constant *Low;
133 const Constant *High;
134134 MachineBasicBlock* BB;
135135 uint32_t ExtraWeight;
136136
137137 Case() : Low(0), High(0), BB(0), ExtraWeight(0) { }
138 Case(Constant* low, Constant* high, MachineBasicBlock* bb,
138 Case(const Constant *low, const Constant *high, MachineBasicBlock *bb,
139139 uint32_t extraweight) : Low(low), High(high), BB(bb),
140140 ExtraWeight(extraweight) { }
141141
669669 BasicBlock *Dest = 0;
670670 unsigned NumCases = I.getNumCases();
671671 // Skip the first item since that's the default case.
672 for (unsigned i = 1; i < NumCases; ++i) {
672 for (unsigned i = 0; i < NumCases; ++i) {
673673 GenericValue CaseVal = getOperandValue(I.getCaseValue(i), SF);
674674 if (executeICMP_EQ(CondVal, CaseVal, ElTy).IntVal != 0) {
675 Dest = cast(I.getSuccessor(i));
675 Dest = cast(I.getCaseSuccessor(i));
676676 break;
677677 }
678678 }
24482448
24492449 unsigned NumCases = SI.getNumCases();
24502450 // Skip the first item since that's the default case.
2451 for (unsigned i = 1; i < NumCases; ++i) {
2451 for (unsigned i = 0; i < NumCases; ++i) {
24522452 ConstantInt* CaseVal = SI.getCaseValue(i);
2453 BasicBlock* Succ = SI.getSuccessor(i);
2453 BasicBlock* Succ = SI.getCaseSuccessor(i);
24542454 Out << " case ";
24552455 writeOperand(CaseVal);
24562456 Out << ":\n";
11141114 << SI->getNumCases() << ", " << bbname << ");";
11151115 nl(Out);
11161116 unsigned NumCases = SI->getNumCases();
1117 for (unsigned i = 1; i < NumCases; ++i) {
1117 for (unsigned i = 0; i < NumCases; ++i) {
11181118 const ConstantInt* CaseVal = SI->getCaseValue(i);
1119 const BasicBlock* BB = SI->getSuccessor(i);
1119 const BasicBlock *BB = SI->getCaseSuccessor(i);
11201120 Out << iName << "->addCase("
11211121 << getOpName(CaseVal) << ", "
11221122 << getOpName(BB) << ");";
24542454 ConstantInt *Val =
24552455 dyn_cast(getVal(Values, SI->getCondition()));
24562456 if (!Val) return false; // Cannot determine.
2457 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2457 unsigned ValTISucc = SI->resolveSuccessorIndex(SI->findCaseValue(Val));
2458 NewBB = SI->getSuccessor(ValTISucc);
24582459 } else if (IndirectBrInst *IBI = dyn_cast(CurInst)) {
24592460 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
24602461 if (BlockAddress *BA = dyn_cast(Val))
12501250 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12511251 unsigned NumCases = SI.getNumCases();
12521252 // Skip the first item since that's the default case.
1253 for (unsigned i = 1; i < NumCases; ++i) {
1253 for (unsigned i = 0; i < NumCases; ++i) {
12541254 ConstantInt* CaseVal = SI.getCaseValue(i);
12551255 Constant* NewCaseVal = ConstantExpr::getSub(cast(CaseVal),
12561256 AddRHS);
12571257 assert(isa(NewCaseVal) &&
12581258 "Result of expression should be constant");
1259 SI.setSuccessorValue(i, cast(NewCaseVal));
1259 SI.setCaseValue(i, cast(NewCaseVal));
12601260 }
12611261 SI.setCondition(I->getOperand(0));
12621262 Worklist.Add(I);
18761876 } else if (SwitchInst *SI = dyn_cast(TI)) {
18771877 if (ConstantInt *Cond = dyn_cast(SI->getCondition())) {
18781878 // See if this is an explicit destination.
1879 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1879 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i)
18801880 if (SI->getCaseValue(i) == Cond) {
1881 BasicBlock *ReachableBB = SI->getSuccessor(i);
1881 BasicBlock *ReachableBB = SI->getCaseSuccessor(i);
18821882 Worklist.push_back(ReachableBB);
18831883 continue;
18841884 }
18851885
18861886 // Otherwise it is the default destination.
1887 Worklist.push_back(SI->getSuccessor(0));
1887 Worklist.push_back(SI->getDefaultDest());
18881888 continue;
18891889 }
18901890 }
20842084 Value *SwitchCond = SI->getCondition();
20852085 BasicBlock *Parent = SI->getParent();
20862086 bool Changed = false;
2087 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
2088 BasicBlock *Dst = SI->getSuccessor(i);
2087 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
2088 BasicBlock *Dst = SI->getCaseSuccessor(i);
20892089 if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
20902090 Changed |= propagateEquality(SwitchCond, SI->getCaseValue(i), Dst);
20912091 }
10851085 DestBB = 0;
10861086 else if (BranchInst *BI = dyn_cast(BB->getTerminator()))
10871087 DestBB = BI->getSuccessor(cast(Val)->isZero());
1088 else if (SwitchInst *SI = dyn_cast(BB->getTerminator()))
1089 DestBB = SI->getSuccessor(SI->findCaseValue(cast(Val)));
1090 else {
1088 else if (SwitchInst *SI = dyn_cast(BB->getTerminator())) {
1089 unsigned ValCase = SI->findCaseValue(cast(Val));
1090 DestBB = SI->getSuccessor(SI->resolveSuccessorIndex(ValCase));
1091 } else {
10911092 assert(isa(BB->getTerminator())
10921093 && "Unexpected terminator");
10931094 DestBB = cast(Val)->getBasicBlock();
435435 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
436436 currentLoop, Changed);
437437 unsigned NumCases = SI->getNumCases();
438 if (LoopCond && NumCases > 1) {
438 if (LoopCond && NumCases) {
439439 // Find a value to unswitch on:
440440 // FIXME: this should chose the most expensive case!
441441 // FIXME: scan for a case with a non-critical edge?
444444 // Do not process same value again and again.
445445 // At this point we have some cases already unswitched and
446446 // some not yet unswitched. Let's find the first not yet unswitched one.
447 for (unsigned i = 1; i < NumCases; ++i) {
447 for (unsigned i = 0; i < NumCases; ++i) {
448448 Constant* UnswitchValCandidate = SI->getCaseValue(i);
449449 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
450450 UnswitchVal = UnswitchValCandidate;
573573 // this.
574574 // Note that we can't trivially unswitch on the default case or
575575 // on already unswitched cases.
576 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
576 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
577577 BasicBlock* LoopExitCandidate;
578578 if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
579 SI->getSuccessor(i)))) {
579 SI->getCaseSuccessor(i)))) {
580580 // Okay, we found a trivial case, remember the value that is trivial.
581581 ConstantInt* CaseVal = SI->getCaseValue(i);
582582
11171117 if (SI == 0 || !isa(Val)) continue;
11181118
11191119 unsigned DeadCase = SI->findCaseValue(cast(Val));
1120 if (DeadCase == 0) continue; // Default case is live for multiple values.
1120 // Default case is live for multiple values.
1121 if (DeadCase == SwitchInst::ErrorIndex) continue;
11211122
11221123 // Found a dead case value. Don't remove PHI nodes in the
11231124 // successor if they become single-entry, those PHI nodes may
11241125 // be in the Users list.
11251126
11261127 BasicBlock *Switch = SI->getParent();
1127 BasicBlock *SISucc = SI->getSuccessor(DeadCase);
1128 BasicBlock *SISucc = SI->getCaseSuccessor(DeadCase);
11281129 BasicBlock *Latch = L->getLoopLatch();
11291130
11301131 BranchesInfo.setUnswitched(SI, Val);
11441145 // Compute the successors instead of relying on the return value
11451146 // of SplitEdge, since it may have split the switch successor
11461147 // after PHI nodes.
1147 BasicBlock *NewSISucc = SI->getSuccessor(DeadCase);
1148 BasicBlock *NewSISucc = SI->getCaseSuccessor(DeadCase);
11481149 BasicBlock *OldSISucc = *succ_begin(NewSISucc);
11491150 // Create an "unreachable" destination.
11501151 BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
549549 }
550550
551551 if (SwitchInst *SI = dyn_cast(&TI)) {
552 if (TI.getNumSuccessors() < 2) {
552 if (!SI->getNumCases()) {
553553 Succs[0] = true;
554554 return;
555555 }
563563 return;
564564 }
565565
566 Succs[SI->findCaseValue(CI)] = true;
566 Succs[SI->resolveSuccessorIndex(SI->findCaseValue(CI))] = true;
567567 return;
568568 }
569569
613613 return true;
614614
615615 if (SwitchInst *SI = dyn_cast(TI)) {
616 if (SI->getNumSuccessors() < 2)
616 if (SI->getNumCases() < 1)
617617 return true;
618618
619619 LatticeVal SCValue = getValueState(SI->getCondition());
623623 return !SCValue.isUndefined();
624624
625625 // Make sure to skip the "default value" which isn't a value
626 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
627 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
628 return SI->getSuccessor(i) == To;
626 for (unsigned i = 0, E = SI->getNumCases(); i != E; ++i)
627 if (SI->getCaseValue(i) == CI) // Found the taken branch.
628 return SI->getCaseSuccessor(i) == To;
629629
630630 // If the constant value is not equal to any of the branches, we must
631631 // execute default branch.
14861486 }
14871487
14881488 if (SwitchInst *SI = dyn_cast(TI)) {
1489 if (SI->getNumSuccessors() < 2) // no cases
1489 if (!SI->getNumCases())
14901490 continue;
14911491 if (!getValueState(SI->getCondition()).isUndefined())
14921492 continue;
14941494 // If the input to SCCP is actually switch on undef, fix the undef to
14951495 // the first constant.
14961496 if (isa(SI->getCondition())) {
1497 SI->setCondition(SI->getCaseValue(1));
1498 markEdgeExecutable(BB, TI->getSuccessor(1));
1497 SI->setCondition(SI->getCaseValue(0));
1498 markEdgeExecutable(BB, SI->getCaseSuccessor(0));
14991499 return true;
15001500 }
15011501
1502 markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1502 markForcedConstant(SI->getCondition(), SI->getCaseValue(0));
15031503 return true;
15041504 }
15051505 }
313313 Cond = dyn_cast_or_null(V);
314314 }
315315 if (Cond) { // Constant fold to uncond branch!
316 BasicBlock *Dest = SI->getSuccessor(SI->findCaseValue(Cond));
316 unsigned CaseIndex = SI->findCaseValue(Cond);
317 BasicBlock *Dest = SI->getSuccessor(SI->resolveSuccessorIndex(CaseIndex));
317318 VMap[OldTI] = BranchInst::Create(Dest, NewBB);
318319 ToClone.push_back(Dest);
319320 TerminatorDone = true;
614614 default:
615615 // Otherwise, make the default destination of the switch instruction be one
616616 // of the other successors.
617 TheSwitch->setOperand(0, call);
618 TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumExitBlocks));
619 TheSwitch->removeCase(NumExitBlocks); // Remove redundant case
617 TheSwitch->setCondition(call);
618 TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
619 TheSwitch->removeCase(NumExitBlocks-1); // Remove redundant case
620620 break;
621621 }
622622 }
105105 // If we are switching on a constant, we can convert the switch into a
106106 // single branch instruction!
107107 ConstantInt *CI = dyn_cast(SI->getCondition());
108 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
108 BasicBlock *TheOnlyDest = SI->getDefaultDest(); // The default dest
109109 BasicBlock *DefaultDest = TheOnlyDest;
110 assert(TheOnlyDest == SI->getDefaultDest() &&
111 "Default destination is not successor #0?");
112110
113111 // Figure out which case it goes to.
114 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
112 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
115113 // Found case matching a constant operand?
116 if (SI->getSuccessorValue(i) == CI) {
117 TheOnlyDest = SI->getSuccessor(i);
114 if (SI->getCaseValue(i) == CI) {
115 TheOnlyDest = SI->getCaseSuccessor(i);
118116 break;
119117 }
120118
121119 // Check to see if this branch is going to the same place as the default
122120 // dest. If so, eliminate it as an explicit compare.
123 if (SI->getSuccessor(i) == DefaultDest) {
121 if (SI->getCaseSuccessor(i) == DefaultDest) {
124122 // Remove this entry.
125123 DefaultDest->removePredecessor(SI->getParent());
126124 SI->removeCase(i);
131129 // Otherwise, check to see if the switch only branches to one destination.
132130 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
133131 // destinations.
134 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
132 if (SI->getCaseSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
135133 }
136134
137135 if (CI && !TheOnlyDest) {
165163 return true;
166164 }
167165
168 if (SI->getNumSuccessors() == 2) {
166 if (SI->getNumCases() == 1) {
169167 // Otherwise, we can fold this switch into a conditional branch
170168 // instruction if it has only one non-default destination.
171169 Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
172 SI->getSuccessorValue(1), "cond");
170 SI->getCaseValue(0), "cond");
173171
174172 // Insert the new branch.
175 Builder.CreateCondBr(Cond, SI->getSuccessor(1), SI->getSuccessor(0));
173 Builder.CreateCondBr(Cond, SI->getCaseSuccessor(0), SI->getDefaultDest());
176174
177175 // Delete the old switch.
178176 SI->eraseFromParent();
7575 unsigned caseNo = SI->findCaseValue(ExpectedValue);
7676 std::vector Vec;
7777 unsigned n = SI->getNumCases();
78 Vec.resize(n + 1); // +1 for MDString
78 Vec.resize(n + 1 + 1); // +1 for MDString and +1 for default case
7979
8080 Vec[0] = MDString::get(Context, "branch_weights");
81 Vec[1] = ConstantInt::get(Int32Ty, SwitchInst::ErrorIndex == caseNo ?
82 LikelyBranchWeight : UnlikelyBranchWeight);
8183 for (unsigned i = 0; i < n; ++i) {
82 Vec[i + 1] = ConstantInt::get(Int32Ty, i == caseNo ? LikelyBranchWeight : UnlikelyBranchWeight);
84 Vec[i + 1 + 1] = ConstantInt::get(Int32Ty, i == caseNo ?
85 LikelyBranchWeight : UnlikelyBranchWeight);
8386 }
8487
8588 MDNode *WeightsNode = llvm::MDNode::get(Context, Vec);
236236 unsigned numCmps = 0;
237237
238238 // Start with "simple" cases
239 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
240 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
241 SI->getSuccessorValue(i),
242 SI->getSuccessor(i)));
239 for (unsigned i = 0; i < SI->getNumCases(); ++i)
240 Cases.push_back(CaseRange(SI->getCaseValue(i),
241 SI->getCaseValue(i),
242 SI->getCaseSuccessor(i)));
243243 std::sort(Cases.begin(), Cases.end(), CaseCmp());
244244
245245 // Merge case into clusters
280280 BasicBlock* Default = SI->getDefaultDest();
281281
282282 // If there is only the default destination, don't bother with the code below.
283 if (SI->getNumCases() == 1) {
283 if (!SI->getNumCases()) {
284284 BranchInst::Create(SI->getDefaultDest(), CurBlock);
285285 CurBlock->getInstList().erase(SI);
286286 return;
480480 BasicBlock*> > &Cases) {
481481 if (SwitchInst *SI = dyn_cast(TI)) {
482482 Cases.reserve(SI->getNumCases());
483 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
484 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
483 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i)
484 Cases.push_back(std::make_pair(SI->getCaseValue(i),
485 SI->getCaseSuccessor(i)));
485486 return SI->getDefaultDest();
486487 }
487488
604605 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
605606 << "Through successor TI: " << *TI);
606607
607 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
608 for (unsigned i = SI->getNumCases(); i != 0;) {
609 --i;
608610 if (DeadCases.count(SI->getCaseValue(i))) {
609 SI->getSuccessor(i)->removePredecessor(TI->getParent());
611 SI->getCaseSuccessor(i)->removePredecessor(TI->getParent());
610612 SI->removeCase(i);
611613 }
614 }
612615
613616 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
614617 return true;
20062009
20072010 // Find the relevant condition and destinations.
20082011 Value *Condition = Select->getCondition();
2009 BasicBlock *TrueBB = SI->getSuccessor(SI->findCaseValue(TrueVal));
2010 BasicBlock *FalseBB = SI->getSuccessor(SI->findCaseValue(FalseVal));
2012 unsigned TrueCase = SI->findCaseValue(TrueVal);
2013 unsigned FalseCase = SI->findCaseValue(FalseVal);
2014 BasicBlock *TrueBB = SI->getSuccessor(SI->resolveSuccessorIndex(TrueCase));
2015 BasicBlock *FalseBB = SI->getSuccessor(SI->resolveSuccessorIndex(FalseCase));
20112016
20122017 // Perform the actual simplification.
20132018 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB);
20912096 // Ok, the block is reachable from the default dest. If the constant we're
20922097 // comparing exists in one of the other edges, then we can constant fold ICI
20932098 // and zap it.
2094 if (SI->findCaseValue(Cst) != 0) {
2099 if (SI->findCaseValue(Cst) != SwitchInst::ErrorIndex) {
20952100 Value *V;
20962101 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
20972102 V = ConstantInt::getFalse(BB->getContext());
24642469 }
24652470 }
24662471 } else if (SwitchInst *SI = dyn_cast(TI)) {
2467 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2468 if (SI->getSuccessor(i) == BB) {
2472 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i)
2473 if (SI->getCaseSuccessor(i) == BB) {
24692474 BB->removePredecessor(SI->getParent());
24702475 SI->removeCase(i);
24712476 --i; --e;
24732478 }
24742479 // If the default value is unreachable, figure out the most popular
24752480 // destination and make it the default.
2476 if (SI->getSuccessor(0) == BB) {
2481 if (SI->getDefaultDest() == BB) {
24772482 std::map > Popularity;
2478 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
2483 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
24792484 std::pair &entry =
2480 Popularity[SI->getSuccessor(i)];
2485 Popularity[SI->getCaseSuccessor(i)];
24812486 if (entry.first == 0) {
24822487 entry.first = 1;
24832488 entry.second = i;
25022507 if (MaxBlock) {
25032508 // Make this the new default, allowing us to delete any explicit
25042509 // edges to it.
2505 SI->setSuccessor(0, MaxBlock);
2510 SI->setDefaultDest(MaxBlock);
25062511 Changed = true;
25072512
25082513 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
25112516 for (unsigned i = 0; i != MaxPop-1; ++i)
25122517 MaxBlock->removePredecessor(SI->getParent());
25132518
2514 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2515 if (SI->getSuccessor(i) == MaxBlock) {
2519 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i)
2520 if (SI->getCaseSuccessor(i) == MaxBlock) {
25162521 SI->removeCase(i);
25172522 --i; --e;
25182523 }
25542559 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
25552560 /// integer range comparison into a sub, an icmp and a branch.
25562561 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
2557 assert(SI->getNumCases() > 2 && "Degenerate switch?");
2562 assert(SI->getNumCases() > 1 && "Degenerate switch?");
25582563
25592564 // Make sure all cases point to the same destination and gather the values.
25602565 SmallVector Cases;
2561 Cases.push_back(SI->getCaseValue(1));
2562 for (unsigned I = 2, E = SI->getNumCases(); I != E; ++I) {
2563 if (SI->getSuccessor(I-1) != SI->getSuccessor(I))
2566 Cases.push_back(SI->getCaseValue(0));
2567 for (unsigned I = 1, E = SI->getNumCases(); I != E; ++I) {
2568 if (SI->getCaseSuccessor(I-1) != SI->getCaseSuccessor(I))
25642569 return false;
25652570 Cases.push_back(SI->getCaseValue(I));
25662571 }
2567 assert(Cases.size() == SI->getNumCases()-1 && "Not all cases gathered");
2572 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
25682573
25692574 // Sort the case values, then check if they form a range we can transform.
25702575 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
25742579 }
25752580
25762581 Constant *Offset = ConstantExpr::getNeg(Cases.back());
2577 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()-1);
2582 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
25782583
25792584 Value *Sub = SI->getCondition();
25802585 if (!Offset->isNullValue())
25812586 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
25822587 Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
2583 Builder.CreateCondBr(Cmp, SI->getSuccessor(1), SI->getDefaultDest());
2588 Builder.CreateCondBr(Cmp, SI->getCaseSuccessor(0), SI->getDefaultDest());
25842589
25852590 // Prune obsolete incoming values off the successor's PHI nodes.
2586 for (BasicBlock::iterator BBI = SI->getSuccessor(1)->begin();
2591 for (BasicBlock::iterator BBI = SI->getCaseSuccessor(0)->begin();
25872592 isa(BBI); ++BBI) {
2588 for (unsigned I = 0, E = SI->getNumCases()-2; I != E; ++I)
2593 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
25892594 cast(BBI)->removeIncomingValue(SI->getParent());
25902595 }
25912596 SI->eraseFromParent();
26032608
26042609 // Gather dead cases.
26052610 SmallVector DeadCases;
2606 for (unsigned I = 1, E = SI->getNumCases(); I != E; ++I) {
2611 for (unsigned I = 0, E = SI->getNumCases(); I != E; ++I) {
26072612 if ((SI->getCaseValue(I)->getValue() & KnownZero) != 0 ||
26082613 (SI->getCaseValue(I)->getValue() & KnownOne) != KnownOne) {
26092614 DeadCases.push_back(SI->getCaseValue(I));
26152620 // Remove dead cases from the switch.
26162621 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
26172622 unsigned Case = SI->findCaseValue(DeadCases[I]);
2623 assert(Case != SwitchInst::ErrorIndex &&
2624 "Case was not found. Probably mistake in DeadCases forming.");
26182625 // Prune unused values from PHI nodes.
2619 SI->getSuccessor(Case)->removePredecessor(SI->getParent());
2626 SI->getCaseSuccessor(Case)->removePredecessor(SI->getParent());
26202627 SI->removeCase(Case);
26212628 }
26222629
26652672 typedef DenseMap > ForwardingNodesMap;
26662673 ForwardingNodesMap ForwardingNodes;
26672674
2668 for (unsigned I = 1; I < SI->getNumCases(); ++I) { // 0 is the default case.
2675 for (unsigned I = 0; I < SI->getNumCases(); ++I) { // 0 is the default case.
26692676 ConstantInt *CaseValue = SI->getCaseValue(I);
2670 BasicBlock *CaseDest = SI->getSuccessor(I);
2677 BasicBlock *CaseDest = SI->getCaseSuccessor(I);
26712678
26722679 int PhiIndex;
26732680 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
17371737 Out << ", ";
17381738 writeOperand(SI.getDefaultDest(), true);
17391739 Out << " [";
1740 // Skip the first item since that's the default case.
17411740 unsigned NumCases = SI.getNumCases();
1742 for (unsigned i = 1; i < NumCases; ++i) {
1741 for (unsigned i = 0; i < NumCases; ++i) {
17431742 Out << "\n ";
17441743 writeOperand(SI.getCaseValue(i), true);
17451744 Out << ", ";
1746 writeOperand(SI.getSuccessor(i), true);
1745 writeOperand(SI.getCaseSuccessor(i), true);
17471746 }
17481747 Out << "\n ]";
17491748 } else if (isa(I)) {
31943194 /// addCase - Add an entry to the switch instruction...
31953195 ///
31963196 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3197 unsigned NewCaseIdx = getNumCases();
31973198 unsigned OpNo = NumOperands;
31983199 if (OpNo+2 > ReservedSpace)
31993200 growOperands(); // Get more space!
32003201 // Initialize some new operands.
32013202 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
32023203 NumOperands = OpNo+2;
3203 OperandList[OpNo] = OnVal;
3204 OperandList[OpNo+1] = Dest;
3205 }
3206
3207 /// removeCase - This method removes the specified successor from the switch
3208 /// instruction. Note that this cannot be used to remove the default
3209 /// destination (successor #0).
3210 ///
3204 setCaseValue(NewCaseIdx, OnVal);
3205 setCaseSuccessor(NewCaseIdx, Dest);
3206 }
3207
3208 /// removeCase - This method removes the specified case and its successor
3209 /// from the switch instruction.
32113210 void SwitchInst::removeCase(unsigned idx) {
3212 assert(idx != 0 && "Cannot remove the default case!");
3213 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3211 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
32143212
32153213 unsigned NumOps = getNumOperands();
32163214 Use *OL = OperandList;
32173215
32183216 // Overwrite this case with the end of the list.
3219 if ((idx + 1) * 2 != NumOps) {
3220 OL[idx * 2] = OL[NumOps - 2];
3221 OL[idx * 2 + 1] = OL[NumOps - 1];
3217 if (2 + (idx + 1) * 2 != NumOps) {
3218 OL[2 + idx * 2] = OL[NumOps - 2];
3219 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
32223220 }
32233221
32243222 // Nuke the last value.
811811 // have the same type as the switched-on value.
812812 Type *SwitchTy = SI.getCondition()->getType();
813813 SmallPtrSet Constants;
814 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i) {
814 for (unsigned i = 0, e = SI.getNumCases(); i != e; ++i) {
815815 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
816816 "Switch constants must all be same type as switch value!", &SI);
817817 Assert2(Constants.insert(SI.getCaseValue(i)),
318318 bool Difference = false;
319319
320320 DenseMap LCases;
321 for (unsigned I = 1, E = LI->getNumCases(); I != E; ++I)
322 LCases[LI->getCaseValue(I)] = LI->getSuccessor(I);
323 for (unsigned I = 1, E = RI->getNumCases(); I != E; ++I) {
321 for (unsigned I = 0, E = LI->getNumCases(); I != E; ++I)
322 LCases[LI->getCaseValue(I)] = LI->getCaseSuccessor(I);
323 for (unsigned I = 0, E = RI->getNumCases(); I != E; ++I) {
324324 ConstantInt *CaseValue = RI->getCaseValue(I);
325325 BasicBlock *LCase = LCases[CaseValue];
326326 if (LCase) {
327 if (TryUnify) tryUnify(LCase, RI->getSuccessor(I));
327 if (TryUnify) tryUnify(LCase, RI->getCaseSuccessor(I));
328328 LCases.erase(CaseValue);
329329 } else if (Complain || !Difference) {
330330 if (Complain)