1 //===-- StructurizeCFG.cpp ------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "structurizecfg"
11 #include "llvm/Transforms/Scalar.h"
12 #include "llvm/ADT/MapVector.h"
13 #include "llvm/ADT/SCCIterator.h"
14 #include "llvm/Analysis/RegionInfo.h"
15 #include "llvm/Analysis/RegionIterator.h"
16 #include "llvm/Analysis/RegionPass.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/Support/PatternMatch.h"
19 #include "llvm/Transforms/Utils/SSAUpdater.h"
22 using namespace llvm::PatternMatch;
26 // Definition of the complex types used in this pass.
28 typedef std::pair<BasicBlock *, Value *> BBValuePair;
30 typedef SmallVector<RegionNode*, 8> RNVector;
31 typedef SmallVector<BasicBlock*, 8> BBVector;
32 typedef SmallVector<BranchInst*, 8> BranchVector;
33 typedef SmallVector<BBValuePair, 2> BBValueVector;
35 typedef SmallPtrSet<BasicBlock *, 8> BBSet;
37 typedef MapVector<PHINode *, BBValueVector> PhiMap;
38 typedef MapVector<BasicBlock *, BBVector> BB2BBVecMap;
40 typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap;
41 typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap;
42 typedef DenseMap<BasicBlock *, Value *> BBPredicates;
43 typedef DenseMap<BasicBlock *, BBPredicates> PredMap;
44 typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap;
46 // The name for newly created blocks.
48 static const char *const FlowBlockName = "Flow";
50 /// @brief Find the nearest common dominator for multiple BasicBlocks
52 /// Helper class for StructurizeCFG
53 /// TODO: Maybe move into common code
54 class NearestCommonDominator {
57 DTN2UnsignedMap IndexMap;
61 bool ExplicitMentioned;
64 /// \brief Start a new query
65 NearestCommonDominator(DominatorTree *DomTree) {
70 /// \brief Add BB to the resulting dominator
71 void addBlock(BasicBlock *BB, bool Remember = true) {
72 DomTreeNode *Node = DT->getNode(BB);
75 unsigned Numbering = 0;
76 for (;Node;Node = Node->getIDom())
77 IndexMap[Node] = ++Numbering;
80 ExplicitMentioned = Remember;
84 for (;Node;Node = Node->getIDom())
85 if (IndexMap.count(Node))
90 assert(Node && "Dominator tree invalid!");
92 unsigned Numbering = IndexMap[Node];
93 if (Numbering > ResultIndex) {
94 Result = Node->getBlock();
95 ResultIndex = Numbering;
96 ExplicitMentioned = Remember && (Result == BB);
97 } else if (Numbering == ResultIndex) {
98 ExplicitMentioned |= Remember;
102 /// \brief Is "Result" one of the BBs added with "Remember" = True?
103 bool wasResultExplicitMentioned() {
104 return ExplicitMentioned;
107 /// \brief Get the query result
108 BasicBlock *getResult() {
113 /// @brief Transforms the control flow graph on one single entry/exit region
116 /// After the transform all "If"/"Then"/"Else" style control flow looks like
128 /// | | 1 = "If" block, calculates the condition
129 /// 4 | 2 = "Then" subregion, runs if the condition is true
130 /// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
131 /// |/ 4 = "Else" optional subregion, runs if the condition is false
132 /// 5 5 = "End" block, also rejoins the control flow
135 /// Control flow is expressed as a branch where the true exit goes into the
136 /// "Then"/"Else" region, while the false exit skips the region
137 /// The condition for the optional "Else" region is expressed as a PHI node.
138 /// The incomming values of the PHI node are true for the "If" edge and false
139 /// for the "Then" edge.
141 /// Additionally to that even complicated loops look like this:
148 /// | / 1 = "Entry" block
149 /// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
150 /// 3 3 = "Flow" block, with back edge to entry block
154 /// The back edge of the "Flow" block is always on the false side of the branch
155 /// while the true side continues the general flow. So the loop condition
156 /// consist of a network of PHI nodes where the true incoming values expresses
157 /// breaks and the false values expresses continue states.
158 class StructurizeCFG : public RegionPass {
160 ConstantInt *BoolTrue;
161 ConstantInt *BoolFalse;
162 UndefValue *BoolUndef;
165 Region *ParentRegion;
172 BBPhiMap DeletedPhis;
173 BB2BBVecMap AddedPhis;
176 BranchVector Conditions;
180 BranchVector LoopConds;
182 RegionNode *PrevNode;
186 void analyzeLoops(RegionNode *N);
188 Value *invert(Value *Condition);
190 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
192 void gatherPredicates(RegionNode *N);
196 void insertConditions(bool Loops);
198 void delPhiValues(BasicBlock *From, BasicBlock *To);
200 void addPhiValues(BasicBlock *From, BasicBlock *To);
204 void killTerminator(BasicBlock *BB);
206 void changeExit(RegionNode *Node, BasicBlock *NewExit,
207 bool IncludeDominator);
209 BasicBlock *getNextFlow(BasicBlock *Dominator);
211 BasicBlock *needPrefix(bool NeedEmpty);
213 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
215 void setPrevNode(BasicBlock *BB);
217 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
219 bool isPredictableTrue(RegionNode *Node);
221 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
223 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
234 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
237 using Pass::doInitialization;
238 virtual bool doInitialization(Region *R, RGPassManager &RGM);
240 virtual bool runOnRegion(Region *R, RGPassManager &RGM);
242 virtual const char *getPassName() const {
243 return "Structurize control flow";
246 void getAnalysisUsage(AnalysisUsage &AU) const {
247 AU.addRequiredID(LowerSwitchID);
248 AU.addRequired<DominatorTreeWrapperPass>();
249 AU.addPreserved<DominatorTreeWrapperPass>();
250 RegionPass::getAnalysisUsage(AU);
254 } // end anonymous namespace
256 char StructurizeCFG::ID = 0;
258 INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
260 INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
261 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
262 INITIALIZE_PASS_DEPENDENCY(RegionInfo)
263 INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
266 /// \brief Initialize the types and constants used in the pass
267 bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
268 LLVMContext &Context = R->getEntry()->getContext();
270 Boolean = Type::getInt1Ty(Context);
271 BoolTrue = ConstantInt::getTrue(Context);
272 BoolFalse = ConstantInt::getFalse(Context);
273 BoolUndef = UndefValue::get(Boolean);
278 /// \brief Build up the general order of nodes
279 void StructurizeCFG::orderNodes() {
280 scc_iterator<Region *> I = scc_begin(ParentRegion);
281 for (Order.clear(); !I.isAtEnd(); ++I) {
282 std::vector<RegionNode *> &Nodes = *I;
283 Order.append(Nodes.begin(), Nodes.end());
287 /// \brief Determine the end of the loops
288 void StructurizeCFG::analyzeLoops(RegionNode *N) {
289 if (N->isSubRegion()) {
290 // Test for exit as back edge
291 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
292 if (Visited.count(Exit))
293 Loops[Exit] = N->getEntry();
296 // Test for sucessors as back edge
297 BasicBlock *BB = N->getNodeAs<BasicBlock>();
298 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
300 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
301 BasicBlock *Succ = Term->getSuccessor(i);
303 if (Visited.count(Succ))
309 /// \brief Invert the given condition
310 Value *StructurizeCFG::invert(Value *Condition) {
311 // First: Check if it's a constant
312 if (Condition == BoolTrue)
315 if (Condition == BoolFalse)
318 if (Condition == BoolUndef)
321 // Second: If the condition is already inverted, return the original value
322 if (match(Condition, m_Not(m_Value(Condition))))
325 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
326 // Third: Check all the users for an invert
327 BasicBlock *Parent = Inst->getParent();
328 for (Value::use_iterator I = Condition->use_begin(),
329 E = Condition->use_end(); I != E; ++I) {
331 Instruction *User = dyn_cast<Instruction>(*I);
332 if (!User || User->getParent() != Parent)
335 if (match(*I, m_Not(m_Specific(Condition))))
339 // Last option: Create a new instruction
340 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
343 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
344 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
345 return BinaryOperator::CreateNot(Condition,
346 Arg->getName() + ".inv",
347 EntryBlock.getTerminator());
350 llvm_unreachable("Unhandled condition to invert");
353 /// \brief Build the condition for one edge
354 Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
356 Value *Cond = Invert ? BoolFalse : BoolTrue;
357 if (Term->isConditional()) {
358 Cond = Term->getCondition();
360 if (Idx != (unsigned)Invert)
366 /// \brief Analyze the predecessors of each block and build up predicates
367 void StructurizeCFG::gatherPredicates(RegionNode *N) {
368 RegionInfo *RI = ParentRegion->getRegionInfo();
369 BasicBlock *BB = N->getEntry();
370 BBPredicates &Pred = Predicates[BB];
371 BBPredicates &LPred = LoopPreds[BB];
373 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
376 // Ignore it if it's a branch from outside into our region entry
377 if (!ParentRegion->contains(*PI))
380 Region *R = RI->getRegionFor(*PI);
381 if (R == ParentRegion) {
383 // It's a top level block in our region
384 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
385 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
386 BasicBlock *Succ = Term->getSuccessor(i);
390 if (Visited.count(*PI)) {
391 // Normal forward edge
392 if (Term->isConditional()) {
393 // Try to treat it like an ELSE block
394 BasicBlock *Other = Term->getSuccessor(!i);
395 if (Visited.count(Other) && !Loops.count(Other) &&
396 !Pred.count(Other) && !Pred.count(*PI)) {
398 Pred[Other] = BoolFalse;
399 Pred[*PI] = BoolTrue;
403 Pred[*PI] = buildCondition(Term, i, false);
407 LPred[*PI] = buildCondition(Term, i, true);
413 // It's an exit from a sub region
414 while(R->getParent() != ParentRegion)
417 // Edge from inside a subregion to its entry, ignore it
421 BasicBlock *Entry = R->getEntry();
422 if (Visited.count(Entry))
423 Pred[Entry] = BoolTrue;
425 LPred[Entry] = BoolFalse;
430 /// \brief Collect various loop and predicate infos
431 void StructurizeCFG::collectInfos() {
439 // Reset the visited nodes
442 for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend();
445 // Analyze all the conditions leading to a node
446 gatherPredicates(*OI);
448 // Remember that we've seen this node
449 Visited.insert((*OI)->getEntry());
451 // Find the last back edges
456 /// \brief Insert the missing branch conditions
457 void StructurizeCFG::insertConditions(bool Loops) {
458 BranchVector &Conds = Loops ? LoopConds : Conditions;
459 Value *Default = Loops ? BoolTrue : BoolFalse;
460 SSAUpdater PhiInserter;
462 for (BranchVector::iterator I = Conds.begin(),
463 E = Conds.end(); I != E; ++I) {
465 BranchInst *Term = *I;
466 assert(Term->isConditional());
468 BasicBlock *Parent = Term->getParent();
469 BasicBlock *SuccTrue = Term->getSuccessor(0);
470 BasicBlock *SuccFalse = Term->getSuccessor(1);
472 PhiInserter.Initialize(Boolean, "");
473 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
474 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
476 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
478 NearestCommonDominator Dominator(DT);
479 Dominator.addBlock(Parent, false);
481 Value *ParentValue = 0;
482 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
485 if (PI->first == Parent) {
486 ParentValue = PI->second;
489 PhiInserter.AddAvailableValue(PI->first, PI->second);
490 Dominator.addBlock(PI->first);
494 Term->setCondition(ParentValue);
496 if (!Dominator.wasResultExplicitMentioned())
497 PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
499 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
504 /// \brief Remove all PHI values coming from "From" into "To" and remember
505 /// them in DeletedPhis
506 void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
507 PhiMap &Map = DeletedPhis[To];
508 for (BasicBlock::iterator I = To->begin(), E = To->end();
509 I != E && isa<PHINode>(*I);) {
511 PHINode &Phi = cast<PHINode>(*I++);
512 while (Phi.getBasicBlockIndex(From) != -1) {
513 Value *Deleted = Phi.removeIncomingValue(From, false);
514 Map[&Phi].push_back(std::make_pair(From, Deleted));
519 /// \brief Add a dummy PHI value as soon as we knew the new predecessor
520 void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
521 for (BasicBlock::iterator I = To->begin(), E = To->end();
522 I != E && isa<PHINode>(*I);) {
524 PHINode &Phi = cast<PHINode>(*I++);
525 Value *Undef = UndefValue::get(Phi.getType());
526 Phi.addIncoming(Undef, From);
528 AddedPhis[To].push_back(From);
531 /// \brief Add the real PHI value as soon as everything is set up
532 void StructurizeCFG::setPhiValues() {
534 for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end();
537 BasicBlock *To = AI->first;
538 BBVector &From = AI->second;
540 if (!DeletedPhis.count(To))
543 PhiMap &Map = DeletedPhis[To];
544 for (PhiMap::iterator PI = Map.begin(), PE = Map.end();
547 PHINode *Phi = PI->first;
548 Value *Undef = UndefValue::get(Phi->getType());
549 Updater.Initialize(Phi->getType(), "");
550 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
551 Updater.AddAvailableValue(To, Undef);
553 NearestCommonDominator Dominator(DT);
554 Dominator.addBlock(To, false);
555 for (BBValueVector::iterator VI = PI->second.begin(),
556 VE = PI->second.end(); VI != VE; ++VI) {
558 Updater.AddAvailableValue(VI->first, VI->second);
559 Dominator.addBlock(VI->first);
562 if (!Dominator.wasResultExplicitMentioned())
563 Updater.AddAvailableValue(Dominator.getResult(), Undef);
565 for (BBVector::iterator FI = From.begin(), FE = From.end();
568 int Idx = Phi->getBasicBlockIndex(*FI);
570 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI));
574 DeletedPhis.erase(To);
576 assert(DeletedPhis.empty());
579 /// \brief Remove phi values from all successors and then remove the terminator.
580 void StructurizeCFG::killTerminator(BasicBlock *BB) {
581 TerminatorInst *Term = BB->getTerminator();
585 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
588 delPhiValues(BB, *SI);
591 Term->eraseFromParent();
594 /// \brief Let node exit(s) point to NewExit
595 void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
596 bool IncludeDominator) {
597 if (Node->isSubRegion()) {
598 Region *SubRegion = Node->getNodeAs<Region>();
599 BasicBlock *OldExit = SubRegion->getExit();
600 BasicBlock *Dominator = 0;
602 // Find all the edges from the sub region to the exit
603 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
606 BasicBlock *BB = *I++;
607 if (!SubRegion->contains(BB))
610 // Modify the edges to point to the new exit
611 delPhiValues(BB, OldExit);
612 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
613 addPhiValues(BB, NewExit);
615 // Find the new dominator (if requested)
616 if (IncludeDominator) {
620 Dominator = DT->findNearestCommonDominator(Dominator, BB);
624 // Change the dominator (if requested)
626 DT->changeImmediateDominator(NewExit, Dominator);
628 // Update the region info
629 SubRegion->replaceExit(NewExit);
632 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
634 BranchInst::Create(NewExit, BB);
635 addPhiValues(BB, NewExit);
636 if (IncludeDominator)
637 DT->changeImmediateDominator(NewExit, BB);
641 /// \brief Create a new flow node and update dominator tree and region info
642 BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
643 LLVMContext &Context = Func->getContext();
644 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
645 Order.back()->getEntry();
646 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
648 DT->addNewBlock(Flow, Dominator);
649 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
653 /// \brief Create a new or reuse the previous node as flow node
654 BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
655 BasicBlock *Entry = PrevNode->getEntry();
657 if (!PrevNode->isSubRegion()) {
658 killTerminator(Entry);
659 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
664 // create a new flow node
665 BasicBlock *Flow = getNextFlow(Entry);
668 changeExit(PrevNode, Flow, true);
669 PrevNode = ParentRegion->getBBNode(Flow);
673 /// \brief Returns the region exit if possible, otherwise just a new flow node
674 BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
675 bool ExitUseAllowed) {
676 if (Order.empty() && ExitUseAllowed) {
677 BasicBlock *Exit = ParentRegion->getExit();
678 DT->changeImmediateDominator(Exit, Flow);
679 addPhiValues(Flow, Exit);
682 return getNextFlow(Flow);
685 /// \brief Set the previous node
686 void StructurizeCFG::setPrevNode(BasicBlock *BB) {
687 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB) : 0;
690 /// \brief Does BB dominate all the predicates of Node ?
691 bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
692 BBPredicates &Preds = Predicates[Node->getEntry()];
693 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
696 if (!DT->dominates(BB, PI->first))
702 /// \brief Can we predict that this node will always be called?
703 bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
704 BBPredicates &Preds = Predicates[Node->getEntry()];
705 bool Dominated = false;
707 // Regionentry is always true
711 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
714 if (I->second != BoolTrue)
717 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
721 // TODO: The dominator check is too strict
725 /// Take one node from the order vector and wire it up
726 void StructurizeCFG::wireFlow(bool ExitUseAllowed,
727 BasicBlock *LoopEnd) {
728 RegionNode *Node = Order.pop_back_val();
729 Visited.insert(Node->getEntry());
731 if (isPredictableTrue(Node)) {
732 // Just a linear flow
734 changeExit(PrevNode, Node->getEntry(), true);
739 // Insert extra prefix node (or reuse last one)
740 BasicBlock *Flow = needPrefix(false);
742 // Insert extra postfix node (or use exit instead)
743 BasicBlock *Entry = Node->getEntry();
744 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
746 // let it point to entry and next block
747 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
748 addPhiValues(Flow, Entry);
749 DT->changeImmediateDominator(Entry, Flow);
752 while (!Order.empty() && !Visited.count(LoopEnd) &&
753 dominatesPredicates(Entry, Order.back())) {
754 handleLoops(false, LoopEnd);
757 changeExit(PrevNode, Next, false);
762 void StructurizeCFG::handleLoops(bool ExitUseAllowed,
763 BasicBlock *LoopEnd) {
764 RegionNode *Node = Order.back();
765 BasicBlock *LoopStart = Node->getEntry();
767 if (!Loops.count(LoopStart)) {
768 wireFlow(ExitUseAllowed, LoopEnd);
772 if (!isPredictableTrue(Node))
773 LoopStart = needPrefix(true);
775 LoopEnd = Loops[Node->getEntry()];
776 wireFlow(false, LoopEnd);
777 while (!Visited.count(LoopEnd)) {
778 handleLoops(false, LoopEnd);
781 // If the start of the loop is the entry block, we can't branch to it so
782 // insert a new dummy entry block.
783 Function *LoopFunc = LoopStart->getParent();
784 if (LoopStart == &LoopFunc->getEntryBlock()) {
785 LoopStart->setName("entry.orig");
787 BasicBlock *NewEntry =
788 BasicBlock::Create(LoopStart->getContext(),
792 BranchInst::Create(LoopStart, NewEntry);
795 // Create an extra loop end node
796 LoopEnd = needPrefix(false);
797 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
798 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
799 BoolUndef, LoopEnd));
800 addPhiValues(LoopEnd, LoopStart);
804 /// After this function control flow looks like it should be, but
805 /// branches and PHI nodes only have undefined conditions.
806 void StructurizeCFG::createFlow() {
807 BasicBlock *Exit = ParentRegion->getExit();
808 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
818 while (!Order.empty()) {
819 handleLoops(EntryDominatesExit, 0);
823 changeExit(PrevNode, Exit, EntryDominatesExit);
825 assert(EntryDominatesExit);
828 /// Handle a rare case where the disintegrated nodes instructions
829 /// no longer dominate all their uses. Not sure if this is really nessasary
830 void StructurizeCFG::rebuildSSA() {
832 for (Region::block_iterator I = ParentRegion->block_begin(),
833 E = ParentRegion->block_end();
837 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
840 bool Initialized = false;
841 for (Use *I = &II->use_begin().getUse(), *Next; I; I = Next) {
845 Instruction *User = cast<Instruction>(I->getUser());
846 if (User->getParent() == BB) {
849 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
850 if (UserPN->getIncomingBlock(*I) == BB)
854 if (DT->dominates(II, User))
858 Value *Undef = UndefValue::get(II->getType());
859 Updater.Initialize(II->getType(), "");
860 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
861 Updater.AddAvailableValue(BB, II);
864 Updater.RewriteUseAfterInsertions(*I);
870 /// \brief Run the transformation for each region found
871 bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
872 if (R->isTopLevelRegion())
875 Func = R->getEntry()->getParent();
878 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
883 insertConditions(false);
884 insertConditions(true);
902 /// \brief Create the pass
903 Pass *llvm::createStructurizeCFGPass() {
904 return new StructurizeCFG();