xref: /llvm-project/llvm/lib/Transforms/Scalar/StructurizeCFG.cpp (revision 3c5fd145c5f6fc2ee570e9c329700f8a9960eae0)
1 //===- StructurizeCFG.cpp -------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/ADT/DenseMap.h"
11 #include "llvm/ADT/MapVector.h"
12 #include "llvm/ADT/PostOrderIterator.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/Analysis/DivergenceAnalysis.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Analysis/RegionInfo.h"
19 #include "llvm/Analysis/RegionIterator.h"
20 #include "llvm/Analysis/RegionPass.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/Use.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/Transforms/Utils.h"
44 #include "llvm/Transforms/Utils/SSAUpdater.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <utility>
48 
49 using namespace llvm;
50 using namespace llvm::PatternMatch;
51 
52 #define DEBUG_TYPE "structurizecfg"
53 
54 // The name for newly created blocks.
55 static const char *const FlowBlockName = "Flow";
56 
57 namespace {
58 
59 static cl::opt<bool> ForceSkipUniformRegions(
60   "structurizecfg-skip-uniform-regions",
61   cl::Hidden,
62   cl::desc("Force whether the StructurizeCFG pass skips uniform regions"),
63   cl::init(false));
64 
65 // Definition of the complex types used in this pass.
66 
67 using BBValuePair = std::pair<BasicBlock *, Value *>;
68 
69 using RNVector = SmallVector<RegionNode *, 8>;
70 using BBVector = SmallVector<BasicBlock *, 8>;
71 using BranchVector = SmallVector<BranchInst *, 8>;
72 using BBValueVector = SmallVector<BBValuePair, 2>;
73 
74 using BBSet = SmallPtrSet<BasicBlock *, 8>;
75 
76 using PhiMap = MapVector<PHINode *, BBValueVector>;
77 using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;
78 
79 using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
80 using BBPredicates = DenseMap<BasicBlock *, Value *>;
81 using PredMap = DenseMap<BasicBlock *, BBPredicates>;
82 using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;
83 
84 /// Finds the nearest common dominator of a set of BasicBlocks.
85 ///
86 /// For every BB you add to the set, you can specify whether we "remember" the
87 /// block.  When you get the common dominator, you can also ask whether it's one
88 /// of the blocks we remembered.
89 class NearestCommonDominator {
90   DominatorTree *DT;
91   BasicBlock *Result = nullptr;
92   bool ResultIsRemembered = false;
93 
94   /// Add BB to the resulting dominator.
95   void addBlock(BasicBlock *BB, bool Remember) {
96     if (!Result) {
97       Result = BB;
98       ResultIsRemembered = Remember;
99       return;
100     }
101 
102     BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
103     if (NewResult != Result)
104       ResultIsRemembered = false;
105     if (NewResult == BB)
106       ResultIsRemembered |= Remember;
107     Result = NewResult;
108   }
109 
110 public:
111   explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
112 
113   void addBlock(BasicBlock *BB) {
114     addBlock(BB, /* Remember = */ false);
115   }
116 
117   void addAndRememberBlock(BasicBlock *BB) {
118     addBlock(BB, /* Remember = */ true);
119   }
120 
121   /// Get the nearest common dominator of all the BBs added via addBlock() and
122   /// addAndRememberBlock().
123   BasicBlock *result() { return Result; }
124 
125   /// Is the BB returned by getResult() one of the blocks we added to the set
126   /// with addAndRememberBlock()?
127   bool resultIsRememberedBlock() { return ResultIsRemembered; }
128 };
129 
130 /// Transforms the control flow graph on one single entry/exit region
131 /// at a time.
132 ///
133 /// After the transform all "If"/"Then"/"Else" style control flow looks like
134 /// this:
135 ///
136 /// \verbatim
137 /// 1
138 /// ||
139 /// | |
140 /// 2 |
141 /// | /
142 /// |/
143 /// 3
144 /// ||   Where:
145 /// | |  1 = "If" block, calculates the condition
146 /// 4 |  2 = "Then" subregion, runs if the condition is true
147 /// | /  3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
148 /// |/   4 = "Else" optional subregion, runs if the condition is false
149 /// 5    5 = "End" block, also rejoins the control flow
150 /// \endverbatim
151 ///
152 /// Control flow is expressed as a branch where the true exit goes into the
153 /// "Then"/"Else" region, while the false exit skips the region
154 /// The condition for the optional "Else" region is expressed as a PHI node.
155 /// The incoming values of the PHI node are true for the "If" edge and false
156 /// for the "Then" edge.
157 ///
158 /// Additionally to that even complicated loops look like this:
159 ///
160 /// \verbatim
161 /// 1
162 /// ||
163 /// | |
164 /// 2 ^  Where:
165 /// | /  1 = "Entry" block
166 /// |/   2 = "Loop" optional subregion, with all exits at "Flow" block
167 /// 3    3 = "Flow" block, with back edge to entry block
168 /// |
169 /// \endverbatim
170 ///
171 /// The back edge of the "Flow" block is always on the false side of the branch
172 /// while the true side continues the general flow. So the loop condition
173 /// consist of a network of PHI nodes where the true incoming values expresses
174 /// breaks and the false values expresses continue states.
175 class StructurizeCFG : public RegionPass {
176   bool SkipUniformRegions;
177 
178   Type *Boolean;
179   ConstantInt *BoolTrue;
180   ConstantInt *BoolFalse;
181   UndefValue *BoolUndef;
182 
183   Function *Func;
184   Region *ParentRegion;
185 
186   DivergenceAnalysis *DA;
187   DominatorTree *DT;
188   LoopInfo *LI;
189 
190   SmallVector<RegionNode *, 8> Order;
191   BBSet Visited;
192 
193   BBPhiMap DeletedPhis;
194   BB2BBVecMap AddedPhis;
195 
196   PredMap Predicates;
197   BranchVector Conditions;
198 
199   BB2BBMap Loops;
200   PredMap LoopPreds;
201   BranchVector LoopConds;
202 
203   RegionNode *PrevNode;
204 
205   void orderNodes();
206 
207   void analyzeLoops(RegionNode *N);
208 
209   Value *invert(Value *Condition);
210 
211   Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
212 
213   void gatherPredicates(RegionNode *N);
214 
215   void collectInfos();
216 
217   void insertConditions(bool Loops);
218 
219   void delPhiValues(BasicBlock *From, BasicBlock *To);
220 
221   void addPhiValues(BasicBlock *From, BasicBlock *To);
222 
223   void setPhiValues();
224 
225   void killTerminator(BasicBlock *BB);
226 
227   void changeExit(RegionNode *Node, BasicBlock *NewExit,
228                   bool IncludeDominator);
229 
230   BasicBlock *getNextFlow(BasicBlock *Dominator);
231 
232   BasicBlock *needPrefix(bool NeedEmpty);
233 
234   BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
235 
236   void setPrevNode(BasicBlock *BB);
237 
238   bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
239 
240   bool isPredictableTrue(RegionNode *Node);
241 
242   void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
243 
244   void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
245 
246   void createFlow();
247 
248   void rebuildSSA();
249 
250 public:
251   static char ID;
252 
253   explicit StructurizeCFG(bool SkipUniformRegions_ = false)
254       : RegionPass(ID),
255         SkipUniformRegions(SkipUniformRegions_) {
256     if (ForceSkipUniformRegions.getNumOccurrences())
257       SkipUniformRegions = ForceSkipUniformRegions.getValue();
258     initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
259   }
260 
261   bool doInitialization(Region *R, RGPassManager &RGM) override;
262 
263   bool runOnRegion(Region *R, RGPassManager &RGM) override;
264 
265   StringRef getPassName() const override { return "Structurize control flow"; }
266 
267   void getAnalysisUsage(AnalysisUsage &AU) const override {
268     if (SkipUniformRegions)
269       AU.addRequired<DivergenceAnalysis>();
270     AU.addRequiredID(LowerSwitchID);
271     AU.addRequired<DominatorTreeWrapperPass>();
272     AU.addRequired<LoopInfoWrapperPass>();
273 
274     AU.addPreserved<DominatorTreeWrapperPass>();
275     RegionPass::getAnalysisUsage(AU);
276   }
277 };
278 
279 } // end anonymous namespace
280 
281 char StructurizeCFG::ID = 0;
282 
283 INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
284                       false, false)
285 INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
286 INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
287 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
288 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
289 INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
290                     false, false)
291 
292 /// Initialize the types and constants used in the pass
293 bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
294   LLVMContext &Context = R->getEntry()->getContext();
295 
296   Boolean = Type::getInt1Ty(Context);
297   BoolTrue = ConstantInt::getTrue(Context);
298   BoolFalse = ConstantInt::getFalse(Context);
299   BoolUndef = UndefValue::get(Boolean);
300 
301   return false;
302 }
303 
304 /// Build up the general order of nodes
305 void StructurizeCFG::orderNodes() {
306   ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
307   SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
308 
309   // The reverse post-order traversal of the list gives us an ordering close
310   // to what we want.  The only problem with it is that sometimes backedges
311   // for outer loops will be visited before backedges for inner loops.
312   for (RegionNode *RN : RPOT) {
313     BasicBlock *BB = RN->getEntry();
314     Loop *Loop = LI->getLoopFor(BB);
315     ++LoopBlocks[Loop];
316   }
317 
318   unsigned CurrentLoopDepth = 0;
319   Loop *CurrentLoop = nullptr;
320   for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
321     BasicBlock *BB = (*I)->getEntry();
322     unsigned LoopDepth = LI->getLoopDepth(BB);
323 
324     if (is_contained(Order, *I))
325       continue;
326 
327     if (LoopDepth < CurrentLoopDepth) {
328       // Make sure we have visited all blocks in this loop before moving back to
329       // the outer loop.
330 
331       auto LoopI = I;
332       while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
333         LoopI++;
334         BasicBlock *LoopBB = (*LoopI)->getEntry();
335         if (LI->getLoopFor(LoopBB) == CurrentLoop) {
336           --BlockCount;
337           Order.push_back(*LoopI);
338         }
339       }
340     }
341 
342     CurrentLoop = LI->getLoopFor(BB);
343     if (CurrentLoop)
344       LoopBlocks[CurrentLoop]--;
345 
346     CurrentLoopDepth = LoopDepth;
347     Order.push_back(*I);
348   }
349 
350   // This pass originally used a post-order traversal and then operated on
351   // the list in reverse. Now that we are using a reverse post-order traversal
352   // rather than re-working the whole pass to operate on the list in order,
353   // we just reverse the list and continue to operate on it in reverse.
354   std::reverse(Order.begin(), Order.end());
355 }
356 
357 /// Determine the end of the loops
358 void StructurizeCFG::analyzeLoops(RegionNode *N) {
359   if (N->isSubRegion()) {
360     // Test for exit as back edge
361     BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
362     if (Visited.count(Exit))
363       Loops[Exit] = N->getEntry();
364 
365   } else {
366     // Test for successors as back edge
367     BasicBlock *BB = N->getNodeAs<BasicBlock>();
368     BranchInst *Term = cast<BranchInst>(BB->getTerminator());
369 
370     for (BasicBlock *Succ : Term->successors())
371       if (Visited.count(Succ))
372         Loops[Succ] = BB;
373   }
374 }
375 
376 /// Invert the given condition
377 Value *StructurizeCFG::invert(Value *Condition) {
378   // First: Check if it's a constant
379   if (Constant *C = dyn_cast<Constant>(Condition))
380     return ConstantExpr::getNot(C);
381 
382   // Second: If the condition is already inverted, return the original value
383   Value *NotCondition;
384   if (match(Condition, m_Not(m_Value(NotCondition))))
385     return NotCondition;
386 
387   if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
388     // Third: Check all the users for an invert
389     BasicBlock *Parent = Inst->getParent();
390     for (User *U : Condition->users())
391       if (Instruction *I = dyn_cast<Instruction>(U))
392         if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
393           return I;
394 
395     // Last option: Create a new instruction
396     return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
397   }
398 
399   if (Argument *Arg = dyn_cast<Argument>(Condition)) {
400     BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
401     return BinaryOperator::CreateNot(Condition,
402                                      Arg->getName() + ".inv",
403                                      EntryBlock.getTerminator());
404   }
405 
406   llvm_unreachable("Unhandled condition to invert");
407 }
408 
409 /// Build the condition for one edge
410 Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
411                                       bool Invert) {
412   Value *Cond = Invert ? BoolFalse : BoolTrue;
413   if (Term->isConditional()) {
414     Cond = Term->getCondition();
415 
416     if (Idx != (unsigned)Invert)
417       Cond = invert(Cond);
418   }
419   return Cond;
420 }
421 
422 /// Analyze the predecessors of each block and build up predicates
423 void StructurizeCFG::gatherPredicates(RegionNode *N) {
424   RegionInfo *RI = ParentRegion->getRegionInfo();
425   BasicBlock *BB = N->getEntry();
426   BBPredicates &Pred = Predicates[BB];
427   BBPredicates &LPred = LoopPreds[BB];
428 
429   for (BasicBlock *P : predecessors(BB)) {
430     // Ignore it if it's a branch from outside into our region entry
431     if (!ParentRegion->contains(P))
432       continue;
433 
434     Region *R = RI->getRegionFor(P);
435     if (R == ParentRegion) {
436       // It's a top level block in our region
437       BranchInst *Term = cast<BranchInst>(P->getTerminator());
438       for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
439         BasicBlock *Succ = Term->getSuccessor(i);
440         if (Succ != BB)
441           continue;
442 
443         if (Visited.count(P)) {
444           // Normal forward edge
445           if (Term->isConditional()) {
446             // Try to treat it like an ELSE block
447             BasicBlock *Other = Term->getSuccessor(!i);
448             if (Visited.count(Other) && !Loops.count(Other) &&
449                 !Pred.count(Other) && !Pred.count(P)) {
450 
451               Pred[Other] = BoolFalse;
452               Pred[P] = BoolTrue;
453               continue;
454             }
455           }
456           Pred[P] = buildCondition(Term, i, false);
457         } else {
458           // Back edge
459           LPred[P] = buildCondition(Term, i, true);
460         }
461       }
462     } else {
463       // It's an exit from a sub region
464       while (R->getParent() != ParentRegion)
465         R = R->getParent();
466 
467       // Edge from inside a subregion to its entry, ignore it
468       if (*R == *N)
469         continue;
470 
471       BasicBlock *Entry = R->getEntry();
472       if (Visited.count(Entry))
473         Pred[Entry] = BoolTrue;
474       else
475         LPred[Entry] = BoolFalse;
476     }
477   }
478 }
479 
480 /// Collect various loop and predicate infos
481 void StructurizeCFG::collectInfos() {
482   // Reset predicate
483   Predicates.clear();
484 
485   // and loop infos
486   Loops.clear();
487   LoopPreds.clear();
488 
489   // Reset the visited nodes
490   Visited.clear();
491 
492   for (RegionNode *RN : reverse(Order)) {
493     LLVM_DEBUG(dbgs() << "Visiting: "
494                       << (RN->isSubRegion() ? "SubRegion with entry: " : "")
495                       << RN->getEntry()->getName() << " Loop Depth: "
496                       << LI->getLoopDepth(RN->getEntry()) << "\n");
497 
498     // Analyze all the conditions leading to a node
499     gatherPredicates(RN);
500 
501     // Remember that we've seen this node
502     Visited.insert(RN->getEntry());
503 
504     // Find the last back edges
505     analyzeLoops(RN);
506   }
507 }
508 
509 /// Insert the missing branch conditions
510 void StructurizeCFG::insertConditions(bool Loops) {
511   BranchVector &Conds = Loops ? LoopConds : Conditions;
512   Value *Default = Loops ? BoolTrue : BoolFalse;
513   SSAUpdater PhiInserter;
514 
515   for (BranchInst *Term : Conds) {
516     assert(Term->isConditional());
517 
518     BasicBlock *Parent = Term->getParent();
519     BasicBlock *SuccTrue = Term->getSuccessor(0);
520     BasicBlock *SuccFalse = Term->getSuccessor(1);
521 
522     PhiInserter.Initialize(Boolean, "");
523     PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
524     PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
525 
526     BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
527 
528     NearestCommonDominator Dominator(DT);
529     Dominator.addBlock(Parent);
530 
531     Value *ParentValue = nullptr;
532     for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
533       BasicBlock *BB = BBAndPred.first;
534       Value *Pred = BBAndPred.second;
535 
536       if (BB == Parent) {
537         ParentValue = Pred;
538         break;
539       }
540       PhiInserter.AddAvailableValue(BB, Pred);
541       Dominator.addAndRememberBlock(BB);
542     }
543 
544     if (ParentValue) {
545       Term->setCondition(ParentValue);
546     } else {
547       if (!Dominator.resultIsRememberedBlock())
548         PhiInserter.AddAvailableValue(Dominator.result(), Default);
549 
550       Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
551     }
552   }
553 }
554 
555 /// Remove all PHI values coming from "From" into "To" and remember
556 /// them in DeletedPhis
557 void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
558   PhiMap &Map = DeletedPhis[To];
559   for (PHINode &Phi : To->phis()) {
560     while (Phi.getBasicBlockIndex(From) != -1) {
561       Value *Deleted = Phi.removeIncomingValue(From, false);
562       Map[&Phi].push_back(std::make_pair(From, Deleted));
563     }
564   }
565 }
566 
567 /// Add a dummy PHI value as soon as we knew the new predecessor
568 void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
569   for (PHINode &Phi : To->phis()) {
570     Value *Undef = UndefValue::get(Phi.getType());
571     Phi.addIncoming(Undef, From);
572   }
573   AddedPhis[To].push_back(From);
574 }
575 
576 /// Add the real PHI value as soon as everything is set up
577 void StructurizeCFG::setPhiValues() {
578   SSAUpdater Updater;
579   for (const auto &AddedPhi : AddedPhis) {
580     BasicBlock *To = AddedPhi.first;
581     const BBVector &From = AddedPhi.second;
582 
583     if (!DeletedPhis.count(To))
584       continue;
585 
586     PhiMap &Map = DeletedPhis[To];
587     for (const auto &PI : Map) {
588       PHINode *Phi = PI.first;
589       Value *Undef = UndefValue::get(Phi->getType());
590       Updater.Initialize(Phi->getType(), "");
591       Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
592       Updater.AddAvailableValue(To, Undef);
593 
594       NearestCommonDominator Dominator(DT);
595       Dominator.addBlock(To);
596       for (const auto &VI : PI.second) {
597         Updater.AddAvailableValue(VI.first, VI.second);
598         Dominator.addAndRememberBlock(VI.first);
599       }
600 
601       if (!Dominator.resultIsRememberedBlock())
602         Updater.AddAvailableValue(Dominator.result(), Undef);
603 
604       for (BasicBlock *FI : From) {
605         int Idx = Phi->getBasicBlockIndex(FI);
606         assert(Idx != -1);
607         Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
608       }
609     }
610 
611     DeletedPhis.erase(To);
612   }
613   assert(DeletedPhis.empty());
614 }
615 
616 /// Remove phi values from all successors and then remove the terminator.
617 void StructurizeCFG::killTerminator(BasicBlock *BB) {
618   TerminatorInst *Term = BB->getTerminator();
619   if (!Term)
620     return;
621 
622   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
623        SI != SE; ++SI)
624     delPhiValues(BB, *SI);
625 
626   if (DA)
627     DA->removeValue(Term);
628   Term->eraseFromParent();
629 }
630 
631 /// Let node exit(s) point to NewExit
632 void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
633                                 bool IncludeDominator) {
634   if (Node->isSubRegion()) {
635     Region *SubRegion = Node->getNodeAs<Region>();
636     BasicBlock *OldExit = SubRegion->getExit();
637     BasicBlock *Dominator = nullptr;
638 
639     // Find all the edges from the sub region to the exit
640     for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
641       // Incrememt BBI before mucking with BB's terminator.
642       BasicBlock *BB = *BBI++;
643 
644       if (!SubRegion->contains(BB))
645         continue;
646 
647       // Modify the edges to point to the new exit
648       delPhiValues(BB, OldExit);
649       BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
650       addPhiValues(BB, NewExit);
651 
652       // Find the new dominator (if requested)
653       if (IncludeDominator) {
654         if (!Dominator)
655           Dominator = BB;
656         else
657           Dominator = DT->findNearestCommonDominator(Dominator, BB);
658       }
659     }
660 
661     // Change the dominator (if requested)
662     if (Dominator)
663       DT->changeImmediateDominator(NewExit, Dominator);
664 
665     // Update the region info
666     SubRegion->replaceExit(NewExit);
667   } else {
668     BasicBlock *BB = Node->getNodeAs<BasicBlock>();
669     killTerminator(BB);
670     BranchInst::Create(NewExit, BB);
671     addPhiValues(BB, NewExit);
672     if (IncludeDominator)
673       DT->changeImmediateDominator(NewExit, BB);
674   }
675 }
676 
677 /// Create a new flow node and update dominator tree and region info
678 BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
679   LLVMContext &Context = Func->getContext();
680   BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
681                        Order.back()->getEntry();
682   BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
683                                         Func, Insert);
684   DT->addNewBlock(Flow, Dominator);
685   ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
686   return Flow;
687 }
688 
689 /// Create a new or reuse the previous node as flow node
690 BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
691   BasicBlock *Entry = PrevNode->getEntry();
692 
693   if (!PrevNode->isSubRegion()) {
694     killTerminator(Entry);
695     if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
696       return Entry;
697   }
698 
699   // create a new flow node
700   BasicBlock *Flow = getNextFlow(Entry);
701 
702   // and wire it up
703   changeExit(PrevNode, Flow, true);
704   PrevNode = ParentRegion->getBBNode(Flow);
705   return Flow;
706 }
707 
708 /// Returns the region exit if possible, otherwise just a new flow node
709 BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
710                                         bool ExitUseAllowed) {
711   if (!Order.empty() || !ExitUseAllowed)
712     return getNextFlow(Flow);
713 
714   BasicBlock *Exit = ParentRegion->getExit();
715   DT->changeImmediateDominator(Exit, Flow);
716   addPhiValues(Flow, Exit);
717   return Exit;
718 }
719 
720 /// Set the previous node
721 void StructurizeCFG::setPrevNode(BasicBlock *BB) {
722   PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
723                                         : nullptr;
724 }
725 
726 /// Does BB dominate all the predicates of Node?
727 bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
728   BBPredicates &Preds = Predicates[Node->getEntry()];
729   return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
730     return DT->dominates(BB, Pred.first);
731   });
732 }
733 
734 /// Can we predict that this node will always be called?
735 bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
736   BBPredicates &Preds = Predicates[Node->getEntry()];
737   bool Dominated = false;
738 
739   // Regionentry is always true
740   if (!PrevNode)
741     return true;
742 
743   for (std::pair<BasicBlock*, Value*> Pred : Preds) {
744     BasicBlock *BB = Pred.first;
745     Value *V = Pred.second;
746 
747     if (V != BoolTrue)
748       return false;
749 
750     if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
751       Dominated = true;
752   }
753 
754   // TODO: The dominator check is too strict
755   return Dominated;
756 }
757 
758 /// Take one node from the order vector and wire it up
759 void StructurizeCFG::wireFlow(bool ExitUseAllowed,
760                               BasicBlock *LoopEnd) {
761   RegionNode *Node = Order.pop_back_val();
762   Visited.insert(Node->getEntry());
763 
764   if (isPredictableTrue(Node)) {
765     // Just a linear flow
766     if (PrevNode) {
767       changeExit(PrevNode, Node->getEntry(), true);
768     }
769     PrevNode = Node;
770   } else {
771     // Insert extra prefix node (or reuse last one)
772     BasicBlock *Flow = needPrefix(false);
773 
774     // Insert extra postfix node (or use exit instead)
775     BasicBlock *Entry = Node->getEntry();
776     BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
777 
778     // let it point to entry and next block
779     Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
780     addPhiValues(Flow, Entry);
781     DT->changeImmediateDominator(Entry, Flow);
782 
783     PrevNode = Node;
784     while (!Order.empty() && !Visited.count(LoopEnd) &&
785            dominatesPredicates(Entry, Order.back())) {
786       handleLoops(false, LoopEnd);
787     }
788 
789     changeExit(PrevNode, Next, false);
790     setPrevNode(Next);
791   }
792 }
793 
794 void StructurizeCFG::handleLoops(bool ExitUseAllowed,
795                                  BasicBlock *LoopEnd) {
796   RegionNode *Node = Order.back();
797   BasicBlock *LoopStart = Node->getEntry();
798 
799   if (!Loops.count(LoopStart)) {
800     wireFlow(ExitUseAllowed, LoopEnd);
801     return;
802   }
803 
804   if (!isPredictableTrue(Node))
805     LoopStart = needPrefix(true);
806 
807   LoopEnd = Loops[Node->getEntry()];
808   wireFlow(false, LoopEnd);
809   while (!Visited.count(LoopEnd)) {
810     handleLoops(false, LoopEnd);
811   }
812 
813   // If the start of the loop is the entry block, we can't branch to it so
814   // insert a new dummy entry block.
815   Function *LoopFunc = LoopStart->getParent();
816   if (LoopStart == &LoopFunc->getEntryBlock()) {
817     LoopStart->setName("entry.orig");
818 
819     BasicBlock *NewEntry =
820       BasicBlock::Create(LoopStart->getContext(),
821                          "entry",
822                          LoopFunc,
823                          LoopStart);
824     BranchInst::Create(LoopStart, NewEntry);
825     DT->setNewRoot(NewEntry);
826   }
827 
828   // Create an extra loop end node
829   LoopEnd = needPrefix(false);
830   BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
831   LoopConds.push_back(BranchInst::Create(Next, LoopStart,
832                                          BoolUndef, LoopEnd));
833   addPhiValues(LoopEnd, LoopStart);
834   setPrevNode(Next);
835 }
836 
837 /// After this function control flow looks like it should be, but
838 /// branches and PHI nodes only have undefined conditions.
839 void StructurizeCFG::createFlow() {
840   BasicBlock *Exit = ParentRegion->getExit();
841   bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
842 
843   DeletedPhis.clear();
844   AddedPhis.clear();
845   Conditions.clear();
846   LoopConds.clear();
847 
848   PrevNode = nullptr;
849   Visited.clear();
850 
851   while (!Order.empty()) {
852     handleLoops(EntryDominatesExit, nullptr);
853   }
854 
855   if (PrevNode)
856     changeExit(PrevNode, Exit, EntryDominatesExit);
857   else
858     assert(EntryDominatesExit);
859 }
860 
861 /// Handle a rare case where the disintegrated nodes instructions
862 /// no longer dominate all their uses. Not sure if this is really nessasary
863 void StructurizeCFG::rebuildSSA() {
864   SSAUpdater Updater;
865   for (BasicBlock *BB : ParentRegion->blocks())
866     for (Instruction &I : *BB) {
867       bool Initialized = false;
868       // We may modify the use list as we iterate over it, so be careful to
869       // compute the next element in the use list at the top of the loop.
870       for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
871         Use &U = *UI++;
872         Instruction *User = cast<Instruction>(U.getUser());
873         if (User->getParent() == BB) {
874           continue;
875         } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
876           if (UserPN->getIncomingBlock(U) == BB)
877             continue;
878         }
879 
880         if (DT->dominates(&I, User))
881           continue;
882 
883         if (!Initialized) {
884           Value *Undef = UndefValue::get(I.getType());
885           Updater.Initialize(I.getType(), "");
886           Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
887           Updater.AddAvailableValue(BB, &I);
888           Initialized = true;
889         }
890         Updater.RewriteUseAfterInsertions(U);
891       }
892     }
893 }
894 
895 static bool hasOnlyUniformBranches(Region *R, unsigned UniformMDKindID,
896                                    const DivergenceAnalysis &DA) {
897   for (auto E : R->elements()) {
898     if (!E->isSubRegion()) {
899       auto Br = dyn_cast<BranchInst>(E->getEntry()->getTerminator());
900       if (!Br || !Br->isConditional())
901         continue;
902 
903       if (!DA.isUniform(Br))
904         return false;
905       LLVM_DEBUG(dbgs() << "BB: " << Br->getParent()->getName()
906                         << " has uniform terminator\n");
907     } else {
908       // Explicitly refuse to treat regions as uniform if they have non-uniform
909       // subregions. We cannot rely on DivergenceAnalysis for branches in
910       // subregions because those branches may have been removed and re-created,
911       // so we look for our metadata instead.
912       //
913       // Warning: It would be nice to treat regions as uniform based only on
914       // their direct child basic blocks' terminators, regardless of whether
915       // subregions are uniform or not. However, this requires a very careful
916       // look at SIAnnotateControlFlow to make sure nothing breaks there.
917       for (auto BB : E->getNodeAs<Region>()->blocks()) {
918         auto Br = dyn_cast<BranchInst>(BB->getTerminator());
919         if (!Br || !Br->isConditional())
920           continue;
921 
922         if (!Br->getMetadata(UniformMDKindID))
923           return false;
924       }
925     }
926   }
927   return true;
928 }
929 
930 /// Run the transformation for each region found
931 bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
932   if (R->isTopLevelRegion())
933     return false;
934 
935   DA = nullptr;
936 
937   if (SkipUniformRegions) {
938     // TODO: We could probably be smarter here with how we handle sub-regions.
939     // We currently rely on the fact that metadata is set by earlier invocations
940     // of the pass on sub-regions, and that this metadata doesn't get lost --
941     // but we shouldn't rely on metadata for correctness!
942     unsigned UniformMDKindID =
943         R->getEntry()->getContext().getMDKindID("structurizecfg.uniform");
944     DA = &getAnalysis<DivergenceAnalysis>();
945 
946     if (hasOnlyUniformBranches(R, UniformMDKindID, *DA)) {
947       LLVM_DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R
948                         << '\n');
949 
950       // Mark all direct child block terminators as having been treated as
951       // uniform. To account for a possible future in which non-uniform
952       // sub-regions are treated more cleverly, indirect children are not
953       // marked as uniform.
954       MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
955       for (RegionNode *E : R->elements()) {
956         if (E->isSubRegion())
957           continue;
958 
959         if (Instruction *Term = E->getEntry()->getTerminator())
960           Term->setMetadata(UniformMDKindID, MD);
961       }
962 
963       return false;
964     }
965   }
966 
967   Func = R->getEntry()->getParent();
968   ParentRegion = R;
969 
970   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
971   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
972 
973   orderNodes();
974   collectInfos();
975   createFlow();
976   insertConditions(false);
977   insertConditions(true);
978   setPhiValues();
979   rebuildSSA();
980 
981   // Cleanup
982   Order.clear();
983   Visited.clear();
984   DeletedPhis.clear();
985   AddedPhis.clear();
986   Predicates.clear();
987   Conditions.clear();
988   Loops.clear();
989   LoopPreds.clear();
990   LoopConds.clear();
991 
992   return true;
993 }
994 
995 Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
996   return new StructurizeCFG(SkipUniformRegions);
997 }
998