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 #include "llvm/Transforms/Scalar.h"
11 #include "llvm/ADT/MapVector.h"
12 #include "llvm/ADT/SCCIterator.h"
13 #include "llvm/Analysis/LoopInfo.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/IR/PatternMatch.h"
19 #include "llvm/Transforms/Utils/SSAUpdater.h"
22 using namespace llvm::PatternMatch;
24 #define DEBUG_TYPE "structurizecfg"
28 // Definition of the complex types used in this pass.
30 typedef std::pair<BasicBlock *, Value *> BBValuePair;
32 typedef SmallVector<RegionNode*, 8> RNVector;
33 typedef SmallVector<BasicBlock*, 8> BBVector;
34 typedef SmallVector<BranchInst*, 8> BranchVector;
35 typedef SmallVector<BBValuePair, 2> BBValueVector;
37 typedef SmallPtrSet<BasicBlock *, 8> BBSet;
39 typedef MapVector<PHINode *, BBValueVector> PhiMap;
40 typedef MapVector<BasicBlock *, BBVector> BB2BBVecMap;
42 typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap;
43 typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap;
44 typedef DenseMap<BasicBlock *, Value *> BBPredicates;
45 typedef DenseMap<BasicBlock *, BBPredicates> PredMap;
46 typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap;
48 // The name for newly created blocks.
50 static const char *const FlowBlockName = "Flow";
52 /// @brief Find the nearest common dominator for multiple BasicBlocks
54 /// Helper class for StructurizeCFG
55 /// TODO: Maybe move into common code
56 class NearestCommonDominator {
59 DTN2UnsignedMap IndexMap;
63 bool ExplicitMentioned;
66 /// \brief Start a new query
67 NearestCommonDominator(DominatorTree *DomTree) {
72 /// \brief Add BB to the resulting dominator
73 void addBlock(BasicBlock *BB, bool Remember = true) {
74 DomTreeNode *Node = DT->getNode(BB);
77 unsigned Numbering = 0;
78 for (;Node;Node = Node->getIDom())
79 IndexMap[Node] = ++Numbering;
82 ExplicitMentioned = Remember;
86 for (;Node;Node = Node->getIDom())
87 if (IndexMap.count(Node))
92 assert(Node && "Dominator tree invalid!");
94 unsigned Numbering = IndexMap[Node];
95 if (Numbering > ResultIndex) {
96 Result = Node->getBlock();
97 ResultIndex = Numbering;
98 ExplicitMentioned = Remember && (Result == BB);
99 } else if (Numbering == ResultIndex) {
100 ExplicitMentioned |= Remember;
104 /// \brief Is "Result" one of the BBs added with "Remember" = True?
105 bool wasResultExplicitMentioned() {
106 return ExplicitMentioned;
109 /// \brief Get the query result
110 BasicBlock *getResult() {
115 /// @brief Transforms the control flow graph on one single entry/exit region
118 /// After the transform all "If"/"Then"/"Else" style control flow looks like
130 /// | | 1 = "If" block, calculates the condition
131 /// 4 | 2 = "Then" subregion, runs if the condition is true
132 /// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
133 /// |/ 4 = "Else" optional subregion, runs if the condition is false
134 /// 5 5 = "End" block, also rejoins the control flow
137 /// Control flow is expressed as a branch where the true exit goes into the
138 /// "Then"/"Else" region, while the false exit skips the region
139 /// The condition for the optional "Else" region is expressed as a PHI node.
140 /// The incomming values of the PHI node are true for the "If" edge and false
141 /// for the "Then" edge.
143 /// Additionally to that even complicated loops look like this:
150 /// | / 1 = "Entry" block
151 /// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
152 /// 3 3 = "Flow" block, with back edge to entry block
156 /// The back edge of the "Flow" block is always on the false side of the branch
157 /// while the true side continues the general flow. So the loop condition
158 /// consist of a network of PHI nodes where the true incoming values expresses
159 /// breaks and the false values expresses continue states.
160 class StructurizeCFG : public RegionPass {
162 ConstantInt *BoolTrue;
163 ConstantInt *BoolFalse;
164 UndefValue *BoolUndef;
167 Region *ParentRegion;
175 BBPhiMap DeletedPhis;
176 BB2BBVecMap AddedPhis;
179 BranchVector Conditions;
183 BranchVector LoopConds;
185 RegionNode *PrevNode;
189 void analyzeLoops(RegionNode *N);
191 Value *invert(Value *Condition);
193 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
195 void gatherPredicates(RegionNode *N);
199 void insertConditions(bool Loops);
201 void delPhiValues(BasicBlock *From, BasicBlock *To);
203 void addPhiValues(BasicBlock *From, BasicBlock *To);
207 void killTerminator(BasicBlock *BB);
209 void changeExit(RegionNode *Node, BasicBlock *NewExit,
210 bool IncludeDominator);
212 BasicBlock *getNextFlow(BasicBlock *Dominator);
214 BasicBlock *needPrefix(bool NeedEmpty);
216 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
218 void setPrevNode(BasicBlock *BB);
220 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
222 bool isPredictableTrue(RegionNode *Node);
224 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
226 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
237 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
240 using Pass::doInitialization;
241 bool doInitialization(Region *R, RGPassManager &RGM) override;
243 bool runOnRegion(Region *R, RGPassManager &RGM) override;
245 const char *getPassName() const override {
246 return "Structurize control flow";
249 void getAnalysisUsage(AnalysisUsage &AU) const override {
250 AU.addRequiredID(LowerSwitchID);
251 AU.addRequired<DominatorTreeWrapperPass>();
252 AU.addRequired<LoopInfoWrapperPass>();
253 AU.addPreserved<DominatorTreeWrapperPass>();
254 RegionPass::getAnalysisUsage(AU);
258 } // end anonymous namespace
260 char StructurizeCFG::ID = 0;
262 INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
264 INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
265 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
266 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
267 INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
270 /// \brief Initialize the types and constants used in the pass
271 bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
272 LLVMContext &Context = R->getEntry()->getContext();
274 Boolean = Type::getInt1Ty(Context);
275 BoolTrue = ConstantInt::getTrue(Context);
276 BoolFalse = ConstantInt::getFalse(Context);
277 BoolUndef = UndefValue::get(Boolean);
282 /// \brief Build up the general order of nodes
283 void StructurizeCFG::orderNodes() {
284 scc_iterator<Region *> I = scc_begin(ParentRegion);
285 for (Order.clear(); !I.isAtEnd(); ++I) {
286 const std::vector<RegionNode *> &Nodes = *I;
287 Order.append(Nodes.begin(), Nodes.end());
291 /// \brief Determine the end of the loops
292 void StructurizeCFG::analyzeLoops(RegionNode *N) {
293 if (N->isSubRegion()) {
294 // Test for exit as back edge
295 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
296 if (Visited.count(Exit))
297 Loops[Exit] = N->getEntry();
300 // Test for sucessors as back edge
301 BasicBlock *BB = N->getNodeAs<BasicBlock>();
302 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
304 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
305 BasicBlock *Succ = Term->getSuccessor(i);
307 if (Visited.count(Succ) && LI->isLoopHeader(Succ) ) {
314 /// \brief Invert the given condition
315 Value *StructurizeCFG::invert(Value *Condition) {
316 // First: Check if it's a constant
317 if (Condition == BoolTrue)
320 if (Condition == BoolFalse)
323 if (Condition == BoolUndef)
326 // Second: If the condition is already inverted, return the original value
327 if (match(Condition, m_Not(m_Value(Condition))))
330 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
331 // Third: Check all the users for an invert
332 BasicBlock *Parent = Inst->getParent();
333 for (User *U : Condition->users())
334 if (Instruction *I = dyn_cast<Instruction>(U))
335 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
338 // Last option: Create a new instruction
339 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
342 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
343 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
344 return BinaryOperator::CreateNot(Condition,
345 Arg->getName() + ".inv",
346 EntryBlock.getTerminator());
349 llvm_unreachable("Unhandled condition to invert");
352 /// \brief Build the condition for one edge
353 Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
355 Value *Cond = Invert ? BoolFalse : BoolTrue;
356 if (Term->isConditional()) {
357 Cond = Term->getCondition();
359 if (Idx != (unsigned)Invert)
365 /// \brief Analyze the predecessors of each block and build up predicates
366 void StructurizeCFG::gatherPredicates(RegionNode *N) {
367 RegionInfo *RI = ParentRegion->getRegionInfo();
368 BasicBlock *BB = N->getEntry();
369 BBPredicates &Pred = Predicates[BB];
370 BBPredicates &LPred = LoopPreds[BB];
372 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
375 // Ignore it if it's a branch from outside into our region entry
376 if (!ParentRegion->contains(*PI))
379 Region *R = RI->getRegionFor(*PI);
380 if (R == ParentRegion) {
382 // It's a top level block in our region
383 BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
384 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
385 BasicBlock *Succ = Term->getSuccessor(i);
389 if (Visited.count(*PI)) {
390 // Normal forward edge
391 if (Term->isConditional()) {
392 // Try to treat it like an ELSE block
393 BasicBlock *Other = Term->getSuccessor(!i);
394 if (Visited.count(Other) && !Loops.count(Other) &&
395 !Pred.count(Other) && !Pred.count(*PI)) {
397 Pred[Other] = BoolFalse;
398 Pred[*PI] = BoolTrue;
402 Pred[*PI] = buildCondition(Term, i, false);
406 LPred[*PI] = buildCondition(Term, i, true);
412 // It's an exit from a sub region
413 while (R->getParent() != ParentRegion)
416 // Edge from inside a subregion to its entry, ignore it
420 BasicBlock *Entry = R->getEntry();
421 if (Visited.count(Entry))
422 Pred[Entry] = BoolTrue;
424 LPred[Entry] = BoolFalse;
429 /// \brief Collect various loop and predicate infos
430 void StructurizeCFG::collectInfos() {
438 // Reset the visited nodes
441 for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend();
444 // Analyze all the conditions leading to a node
445 gatherPredicates(*OI);
447 // Remember that we've seen this node
448 Visited.insert((*OI)->getEntry());
450 // Find the last back edges
455 /// \brief Insert the missing branch conditions
456 void StructurizeCFG::insertConditions(bool Loops) {
457 BranchVector &Conds = Loops ? LoopConds : Conditions;
458 Value *Default = Loops ? BoolTrue : BoolFalse;
459 SSAUpdater PhiInserter;
461 for (BranchInst *Term : Conds) {
462 assert(Term->isConditional());
464 BasicBlock *Parent = Term->getParent();
465 BasicBlock *SuccTrue = Term->getSuccessor(0);
466 BasicBlock *SuccFalse = Term->getSuccessor(1);
468 PhiInserter.Initialize(Boolean, "");
469 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
470 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
472 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
474 NearestCommonDominator Dominator(DT);
475 Dominator.addBlock(Parent, false);
477 Value *ParentValue = nullptr;
478 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
481 if (PI->first == Parent) {
482 ParentValue = PI->second;
485 PhiInserter.AddAvailableValue(PI->first, PI->second);
486 Dominator.addBlock(PI->first);
490 Term->setCondition(ParentValue);
492 if (!Dominator.wasResultExplicitMentioned())
493 PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
495 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
500 /// \brief Remove all PHI values coming from "From" into "To" and remember
501 /// them in DeletedPhis
502 void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
503 PhiMap &Map = DeletedPhis[To];
504 for (BasicBlock::iterator I = To->begin(), E = To->end();
505 I != E && isa<PHINode>(*I);) {
507 PHINode &Phi = cast<PHINode>(*I++);
508 while (Phi.getBasicBlockIndex(From) != -1) {
509 Value *Deleted = Phi.removeIncomingValue(From, false);
510 Map[&Phi].push_back(std::make_pair(From, Deleted));
515 /// \brief Add a dummy PHI value as soon as we knew the new predecessor
516 void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
517 for (BasicBlock::iterator I = To->begin(), E = To->end();
518 I != E && isa<PHINode>(*I);) {
520 PHINode &Phi = cast<PHINode>(*I++);
521 Value *Undef = UndefValue::get(Phi.getType());
522 Phi.addIncoming(Undef, From);
524 AddedPhis[To].push_back(From);
527 /// \brief Add the real PHI value as soon as everything is set up
528 void StructurizeCFG::setPhiValues() {
530 for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end();
533 BasicBlock *To = AI->first;
534 BBVector &From = AI->second;
536 if (!DeletedPhis.count(To))
539 PhiMap &Map = DeletedPhis[To];
540 for (PhiMap::iterator PI = Map.begin(), PE = Map.end();
543 PHINode *Phi = PI->first;
544 Value *Undef = UndefValue::get(Phi->getType());
545 Updater.Initialize(Phi->getType(), "");
546 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
547 Updater.AddAvailableValue(To, Undef);
549 NearestCommonDominator Dominator(DT);
550 Dominator.addBlock(To, false);
551 for (BBValueVector::iterator VI = PI->second.begin(),
552 VE = PI->second.end(); VI != VE; ++VI) {
554 Updater.AddAvailableValue(VI->first, VI->second);
555 Dominator.addBlock(VI->first);
558 if (!Dominator.wasResultExplicitMentioned())
559 Updater.AddAvailableValue(Dominator.getResult(), Undef);
561 for (BBVector::iterator FI = From.begin(), FE = From.end();
564 int Idx = Phi->getBasicBlockIndex(*FI);
566 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI));
570 DeletedPhis.erase(To);
572 assert(DeletedPhis.empty());
575 /// \brief Remove phi values from all successors and then remove the terminator.
576 void StructurizeCFG::killTerminator(BasicBlock *BB) {
577 TerminatorInst *Term = BB->getTerminator();
581 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
584 delPhiValues(BB, *SI);
587 Term->eraseFromParent();
590 /// \brief Let node exit(s) point to NewExit
591 void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
592 bool IncludeDominator) {
593 if (Node->isSubRegion()) {
594 Region *SubRegion = Node->getNodeAs<Region>();
595 BasicBlock *OldExit = SubRegion->getExit();
596 BasicBlock *Dominator = nullptr;
598 // Find all the edges from the sub region to the exit
599 for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
602 BasicBlock *BB = *I++;
603 if (!SubRegion->contains(BB))
606 // Modify the edges to point to the new exit
607 delPhiValues(BB, OldExit);
608 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
609 addPhiValues(BB, NewExit);
611 // Find the new dominator (if requested)
612 if (IncludeDominator) {
616 Dominator = DT->findNearestCommonDominator(Dominator, BB);
620 // Change the dominator (if requested)
622 DT->changeImmediateDominator(NewExit, Dominator);
624 // Update the region info
625 SubRegion->replaceExit(NewExit);
628 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
630 BranchInst::Create(NewExit, BB);
631 addPhiValues(BB, NewExit);
632 if (IncludeDominator)
633 DT->changeImmediateDominator(NewExit, BB);
637 /// \brief Create a new flow node and update dominator tree and region info
638 BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
639 LLVMContext &Context = Func->getContext();
640 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
641 Order.back()->getEntry();
642 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
644 DT->addNewBlock(Flow, Dominator);
645 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
649 /// \brief Create a new or reuse the previous node as flow node
650 BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
651 BasicBlock *Entry = PrevNode->getEntry();
653 if (!PrevNode->isSubRegion()) {
654 killTerminator(Entry);
655 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
660 // create a new flow node
661 BasicBlock *Flow = getNextFlow(Entry);
664 changeExit(PrevNode, Flow, true);
665 PrevNode = ParentRegion->getBBNode(Flow);
669 /// \brief Returns the region exit if possible, otherwise just a new flow node
670 BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
671 bool ExitUseAllowed) {
672 if (Order.empty() && ExitUseAllowed) {
673 BasicBlock *Exit = ParentRegion->getExit();
674 DT->changeImmediateDominator(Exit, Flow);
675 addPhiValues(Flow, Exit);
678 return getNextFlow(Flow);
681 /// \brief Set the previous node
682 void StructurizeCFG::setPrevNode(BasicBlock *BB) {
683 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
687 /// \brief Does BB dominate all the predicates of Node ?
688 bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
689 BBPredicates &Preds = Predicates[Node->getEntry()];
690 for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
693 if (!DT->dominates(BB, PI->first))
699 /// \brief Can we predict that this node will always be called?
700 bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
701 BBPredicates &Preds = Predicates[Node->getEntry()];
702 bool Dominated = false;
704 // Regionentry is always true
708 for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
711 if (I->second != BoolTrue)
714 if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
718 // TODO: The dominator check is too strict
722 /// Take one node from the order vector and wire it up
723 void StructurizeCFG::wireFlow(bool ExitUseAllowed,
724 BasicBlock *LoopEnd) {
725 RegionNode *Node = Order.pop_back_val();
726 Visited.insert(Node->getEntry());
728 if (isPredictableTrue(Node)) {
729 // Just a linear flow
731 changeExit(PrevNode, Node->getEntry(), true);
736 // Insert extra prefix node (or reuse last one)
737 BasicBlock *Flow = needPrefix(false);
739 // Insert extra postfix node (or use exit instead)
740 BasicBlock *Entry = Node->getEntry();
741 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
743 // let it point to entry and next block
744 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
745 addPhiValues(Flow, Entry);
746 DT->changeImmediateDominator(Entry, Flow);
749 while (!Order.empty() && !Visited.count(LoopEnd) &&
750 dominatesPredicates(Entry, Order.back())) {
751 handleLoops(false, LoopEnd);
754 changeExit(PrevNode, Next, false);
759 void StructurizeCFG::handleLoops(bool ExitUseAllowed,
760 BasicBlock *LoopEnd) {
761 RegionNode *Node = Order.back();
762 BasicBlock *LoopStart = Node->getEntry();
764 if (!Loops.count(LoopStart)) {
765 wireFlow(ExitUseAllowed, LoopEnd);
769 if (!isPredictableTrue(Node))
770 LoopStart = needPrefix(true);
772 LoopEnd = Loops[Node->getEntry()];
773 wireFlow(false, LoopEnd);
774 while (!Visited.count(LoopEnd)) {
775 handleLoops(false, LoopEnd);
778 // If the start of the loop is the entry block, we can't branch to it so
779 // insert a new dummy entry block.
780 Function *LoopFunc = LoopStart->getParent();
781 if (LoopStart == &LoopFunc->getEntryBlock()) {
782 LoopStart->setName("entry.orig");
784 BasicBlock *NewEntry =
785 BasicBlock::Create(LoopStart->getContext(),
789 BranchInst::Create(LoopStart, NewEntry);
792 // Create an extra loop end node
793 LoopEnd = needPrefix(false);
794 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
795 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
796 BoolUndef, LoopEnd));
797 addPhiValues(LoopEnd, LoopStart);
801 /// After this function control flow looks like it should be, but
802 /// branches and PHI nodes only have undefined conditions.
803 void StructurizeCFG::createFlow() {
804 BasicBlock *Exit = ParentRegion->getExit();
805 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
815 while (!Order.empty()) {
816 handleLoops(EntryDominatesExit, nullptr);
820 changeExit(PrevNode, Exit, EntryDominatesExit);
822 assert(EntryDominatesExit);
825 /// Handle a rare case where the disintegrated nodes instructions
826 /// no longer dominate all their uses. Not sure if this is really nessasary
827 void StructurizeCFG::rebuildSSA() {
829 for (const auto &BB : ParentRegion->blocks())
830 for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
833 bool Initialized = false;
834 for (auto I = II->use_begin(), E = II->use_end(); I != E;) {
836 Instruction *User = cast<Instruction>(U.getUser());
837 if (User->getParent() == BB) {
840 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
841 if (UserPN->getIncomingBlock(U) == BB)
845 if (DT->dominates(II, User))
849 Value *Undef = UndefValue::get(II->getType());
850 Updater.Initialize(II->getType(), "");
851 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
852 Updater.AddAvailableValue(BB, II);
855 Updater.RewriteUseAfterInsertions(U);
860 /// \brief Run the transformation for each region found
861 bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
862 if (R->isTopLevelRegion())
865 Func = R->getEntry()->getParent();
868 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
869 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
874 insertConditions(false);
875 insertConditions(true);
893 /// \brief Create the pass
894 Pass *llvm::createStructurizeCFGPass() {
895 return new StructurizeCFG();