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