R600/SI: rework VOP2_* pattern v2
[oota-llvm.git] / lib / Target / R600 / AMDGPUStructurizeCFG.cpp
1 //===-- AMDGPUStructurizeCFG.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 /// \file
11 /// The pass implemented in this file transforms the programs control flow
12 /// graph into a form that's suitable for code generation on hardware that
13 /// implements control flow by execution masking. This currently includes all
14 /// AMD GPUs but may as well be useful for other types of hardware.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "AMDGPU.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/Analysis/RegionInfo.h"
21 #include "llvm/Analysis/RegionIterator.h"
22 #include "llvm/Analysis/RegionPass.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Transforms/Utils/SSAUpdater.h"
25 #include "llvm/Support/PatternMatch.h"
26
27 using namespace llvm;
28 using namespace llvm::PatternMatch;
29
30 namespace {
31
32 // Definition of the complex types used in this pass.
33
34 typedef std::pair<BasicBlock *, Value *> BBValuePair;
35
36 typedef SmallVector<RegionNode*, 8> RNVector;
37 typedef SmallVector<BasicBlock*, 8> BBVector;
38 typedef SmallVector<BranchInst*, 8> BranchVector;
39 typedef SmallVector<BBValuePair, 2> BBValueVector;
40
41 typedef SmallPtrSet<BasicBlock *, 8> BBSet;
42
43 typedef DenseMap<PHINode *, BBValueVector> PhiMap;
44 typedef DenseMap<DomTreeNode *, unsigned> DTN2UnsignedMap;
45 typedef DenseMap<BasicBlock *, PhiMap> BBPhiMap;
46 typedef DenseMap<BasicBlock *, Value *> BBPredicates;
47 typedef DenseMap<BasicBlock *, BBPredicates> PredMap;
48 typedef DenseMap<BasicBlock *, BasicBlock*> BB2BBMap;
49 typedef DenseMap<BasicBlock *, BBVector> BB2BBVecMap;
50
51 // The name for newly created blocks.
52
53 static const char *FlowBlockName = "Flow";
54
55 /// @brief Find the nearest common dominator for multiple BasicBlocks
56 ///
57 /// Helper class for AMDGPUStructurizeCFG
58 /// TODO: Maybe move into common code
59 class NearestCommonDominator {
60
61   DominatorTree *DT;
62
63   DTN2UnsignedMap IndexMap;
64
65   BasicBlock *Result;
66   unsigned ResultIndex;
67   bool ExplicitMentioned;
68
69 public:
70   /// \brief Start a new query
71   NearestCommonDominator(DominatorTree *DomTree) {
72     DT = DomTree;
73     Result = 0;
74   }
75
76   /// \brief Add BB to the resulting dominator
77   void addBlock(BasicBlock *BB, bool Remember = true) {
78
79     DomTreeNode *Node = DT->getNode(BB);
80
81     if (Result == 0) {
82       unsigned Numbering = 0;
83       for (;Node;Node = Node->getIDom())
84         IndexMap[Node] = ++Numbering;
85       Result = BB;
86       ResultIndex = 1;
87       ExplicitMentioned = Remember;
88       return;
89     }
90
91     for (;Node;Node = Node->getIDom())
92       if (IndexMap.count(Node))
93         break;
94       else
95         IndexMap[Node] = 0;
96
97     assert(Node && "Dominator tree invalid!");
98
99     unsigned Numbering = IndexMap[Node];
100     if (Numbering > ResultIndex) {
101       Result = Node->getBlock();
102       ResultIndex = Numbering;
103       ExplicitMentioned = Remember && (Result == BB);
104     } else if (Numbering == ResultIndex) {
105       ExplicitMentioned |= Remember;
106     }
107   }
108
109   /// \brief Is "Result" one of the BBs added with "Remember" = True?
110   bool wasResultExplicitMentioned() {
111     return ExplicitMentioned;
112   }
113
114   /// \brief Get the query result
115   BasicBlock *getResult() {
116     return Result;
117   }
118 };
119
120 /// @brief Transforms the control flow graph on one single entry/exit region
121 /// at a time.
122 ///
123 /// After the transform all "If"/"Then"/"Else" style control flow looks like
124 /// this:
125 ///
126 /// \verbatim
127 /// 1
128 /// ||
129 /// | |
130 /// 2 |
131 /// | /
132 /// |/   
133 /// 3
134 /// ||   Where:
135 /// | |  1 = "If" block, calculates the condition
136 /// 4 |  2 = "Then" subregion, runs if the condition is true
137 /// | /  3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
138 /// |/   4 = "Else" optional subregion, runs if the condition is false
139 /// 5    5 = "End" block, also rejoins the control flow
140 /// \endverbatim
141 ///
142 /// Control flow is expressed as a branch where the true exit goes into the
143 /// "Then"/"Else" region, while the false exit skips the region
144 /// The condition for the optional "Else" region is expressed as a PHI node.
145 /// The incomming values of the PHI node are true for the "If" edge and false
146 /// for the "Then" edge.
147 ///
148 /// Additionally to that even complicated loops look like this:
149 ///
150 /// \verbatim
151 /// 1
152 /// ||
153 /// | |
154 /// 2 ^  Where:
155 /// | /  1 = "Entry" block
156 /// |/   2 = "Loop" optional subregion, with all exits at "Flow" block
157 /// 3    3 = "Flow" block, with back edge to entry block
158 /// |
159 /// \endverbatim
160 ///
161 /// The back edge of the "Flow" block is always on the false side of the branch
162 /// while the true side continues the general flow. So the loop condition
163 /// consist of a network of PHI nodes where the true incoming values expresses
164 /// breaks and the false values expresses continue states.
165 class AMDGPUStructurizeCFG : public RegionPass {
166
167   static char ID;
168
169   Type *Boolean;
170   ConstantInt *BoolTrue;
171   ConstantInt *BoolFalse;
172   UndefValue *BoolUndef;
173
174   Function *Func;
175   Region *ParentRegion;
176
177   DominatorTree *DT;
178
179   RNVector Order;
180   BBSet Visited;
181
182   BBPhiMap DeletedPhis;
183   BB2BBVecMap AddedPhis;
184
185   PredMap Predicates;
186   BranchVector Conditions;
187
188   BB2BBMap Loops;
189   PredMap LoopPreds;
190   BranchVector LoopConds;
191
192   RegionNode *PrevNode;
193
194   void orderNodes();
195
196   void analyzeLoops(RegionNode *N);
197
198   Value *invert(Value *Condition);
199
200   Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
201
202   void gatherPredicates(RegionNode *N);
203
204   void collectInfos();
205
206   void insertConditions(bool Loops);
207
208   void delPhiValues(BasicBlock *From, BasicBlock *To);
209
210   void addPhiValues(BasicBlock *From, BasicBlock *To);
211
212   void setPhiValues();
213
214   void killTerminator(BasicBlock *BB);
215
216   void changeExit(RegionNode *Node, BasicBlock *NewExit,
217                   bool IncludeDominator);
218
219   BasicBlock *getNextFlow(BasicBlock *Dominator);
220
221   BasicBlock *needPrefix(bool NeedEmpty);
222
223   BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
224
225   void setPrevNode(BasicBlock *BB);
226
227   bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
228
229   bool isPredictableTrue(RegionNode *Node);
230
231   void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
232
233   void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
234
235   void createFlow();
236
237   void rebuildSSA();
238
239 public:
240   AMDGPUStructurizeCFG():
241     RegionPass(ID) {
242
243     initializeRegionInfoPass(*PassRegistry::getPassRegistry());
244   }
245
246   virtual bool doInitialization(Region *R, RGPassManager &RGM);
247
248   virtual bool runOnRegion(Region *R, RGPassManager &RGM);
249
250   virtual const char *getPassName() const {
251     return "AMDGPU simplify control flow";
252   }
253
254   void getAnalysisUsage(AnalysisUsage &AU) const {
255
256     AU.addRequired<DominatorTree>();
257     AU.addPreserved<DominatorTree>();
258     RegionPass::getAnalysisUsage(AU);
259   }
260
261 };
262
263 } // end anonymous namespace
264
265 char AMDGPUStructurizeCFG::ID = 0;
266
267 /// \brief Initialize the types and constants used in the pass
268 bool AMDGPUStructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
269   LLVMContext &Context = R->getEntry()->getContext();
270
271   Boolean = Type::getInt1Ty(Context);
272   BoolTrue = ConstantInt::getTrue(Context);
273   BoolFalse = ConstantInt::getFalse(Context);
274   BoolUndef = UndefValue::get(Boolean);
275
276   return false;
277 }
278
279 /// \brief Build up the general order of nodes
280 void AMDGPUStructurizeCFG::orderNodes() {
281   scc_iterator<Region *> I = scc_begin(ParentRegion),
282                          E = scc_end(ParentRegion);
283   for (Order.clear(); I != E; ++I) {
284     std::vector<RegionNode *> &Nodes = *I;
285     Order.append(Nodes.begin(), Nodes.end());
286   }
287 }
288
289 /// \brief Determine the end of the loops
290 void AMDGPUStructurizeCFG::analyzeLoops(RegionNode *N) {
291
292   if (N->isSubRegion()) {
293     // Test for exit as back edge
294     BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
295     if (Visited.count(Exit))
296       Loops[Exit] = N->getEntry();
297
298   } else {
299     // Test for sucessors as back edge
300     BasicBlock *BB = N->getNodeAs<BasicBlock>();
301     BranchInst *Term = cast<BranchInst>(BB->getTerminator());
302
303     for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
304       BasicBlock *Succ = Term->getSuccessor(i);
305
306       if (Visited.count(Succ))
307         Loops[Succ] = BB;
308     }
309   }
310 }
311
312 /// \brief Invert the given condition
313 Value *AMDGPUStructurizeCFG::invert(Value *Condition) {
314
315   // First: Check if it's a constant
316   if (Condition == BoolTrue)
317     return BoolFalse;
318
319   if (Condition == BoolFalse)
320     return BoolTrue;
321
322   if (Condition == BoolUndef)
323     return BoolUndef;
324
325   // Second: If the condition is already inverted, return the original value
326   if (match(Condition, m_Not(m_Value(Condition))))
327     return Condition;
328
329   // Third: Check all the users for an invert
330   BasicBlock *Parent = cast<Instruction>(Condition)->getParent();
331   for (Value::use_iterator I = Condition->use_begin(),
332        E = Condition->use_end(); I != E; ++I) {
333
334     Instruction *User = dyn_cast<Instruction>(*I);
335     if (!User || User->getParent() != Parent)
336       continue;
337
338     if (match(*I, m_Not(m_Specific(Condition))))
339       return *I;
340   }
341
342   // Last option: Create a new instruction
343   return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
344 }
345
346 /// \brief Build the condition for one edge
347 Value *AMDGPUStructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
348                                             bool Invert) {
349   Value *Cond = Invert ? BoolFalse : BoolTrue;
350   if (Term->isConditional()) {
351     Cond = Term->getCondition();
352
353     if (Idx != Invert)
354       Cond = invert(Cond);
355   }
356   return Cond;
357 }
358
359 /// \brief Analyze the predecessors of each block and build up predicates
360 void AMDGPUStructurizeCFG::gatherPredicates(RegionNode *N) {
361
362   RegionInfo *RI = ParentRegion->getRegionInfo();
363   BasicBlock *BB = N->getEntry();
364   BBPredicates &Pred = Predicates[BB];
365   BBPredicates &LPred = LoopPreds[BB];
366
367   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
368        PI != PE; ++PI) {
369
370     // Ignore it if it's a branch from outside into our region entry
371     if (!ParentRegion->contains(*PI))
372       continue;
373
374     Region *R = RI->getRegionFor(*PI);
375     if (R == ParentRegion) {
376
377       // It's a top level block in our region
378       BranchInst *Term = cast<BranchInst>((*PI)->getTerminator());
379       for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
380         BasicBlock *Succ = Term->getSuccessor(i);
381         if (Succ != BB)
382           continue;
383
384         if (Visited.count(*PI)) {
385           // Normal forward edge
386           if (Term->isConditional()) {
387             // Try to treat it like an ELSE block
388             BasicBlock *Other = Term->getSuccessor(!i);
389             if (Visited.count(Other) && !Loops.count(Other) &&
390                 !Pred.count(Other) && !Pred.count(*PI)) {
391
392               Pred[Other] = BoolFalse;
393               Pred[*PI] = BoolTrue;
394               continue;
395             }
396           }
397           Pred[*PI] = buildCondition(Term, i, false);
398  
399         } else {
400           // Back edge
401           LPred[*PI] = buildCondition(Term, i, true);
402         }
403       }
404
405     } else {
406
407       // It's an exit from a sub region
408       while(R->getParent() != ParentRegion)
409         R = R->getParent();
410
411       // Edge from inside a subregion to its entry, ignore it
412       if (R == N)
413         continue;
414
415       BasicBlock *Entry = R->getEntry();
416       if (Visited.count(Entry))
417         Pred[Entry] = BoolTrue;
418       else
419         LPred[Entry] = BoolFalse;
420     }
421   }
422 }
423
424 /// \brief Collect various loop and predicate infos
425 void AMDGPUStructurizeCFG::collectInfos() {
426
427   // Reset predicate
428   Predicates.clear();
429
430   // and loop infos
431   Loops.clear();
432   LoopPreds.clear();
433
434   // Reset the visited nodes
435   Visited.clear();
436
437   for (RNVector::reverse_iterator OI = Order.rbegin(), OE = Order.rend();
438        OI != OE; ++OI) {
439
440     // Analyze all the conditions leading to a node
441     gatherPredicates(*OI);
442
443     // Remember that we've seen this node
444     Visited.insert((*OI)->getEntry());
445
446     // Find the last back edges
447     analyzeLoops(*OI);
448   }
449 }
450
451 /// \brief Insert the missing branch conditions
452 void AMDGPUStructurizeCFG::insertConditions(bool Loops) {
453   BranchVector &Conds = Loops ? LoopConds : Conditions;
454   Value *Default = Loops ? BoolTrue : BoolFalse;
455   SSAUpdater PhiInserter;
456
457   for (BranchVector::iterator I = Conds.begin(),
458        E = Conds.end(); I != E; ++I) {
459
460     BranchInst *Term = *I;
461     assert(Term->isConditional());
462
463     BasicBlock *Parent = Term->getParent();
464     BasicBlock *SuccTrue = Term->getSuccessor(0);
465     BasicBlock *SuccFalse = Term->getSuccessor(1);
466
467     PhiInserter.Initialize(Boolean, "");
468     PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
469     PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
470
471     BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
472
473     NearestCommonDominator Dominator(DT);
474     Dominator.addBlock(Parent, false);
475
476     Value *ParentValue = 0;
477     for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
478          PI != PE; ++PI) {
479
480       if (PI->first == Parent) {
481         ParentValue = PI->second;
482         break;
483       }
484       PhiInserter.AddAvailableValue(PI->first, PI->second);
485       Dominator.addBlock(PI->first);
486     }
487
488     if (ParentValue) {
489       Term->setCondition(ParentValue);
490     } else {
491       if (!Dominator.wasResultExplicitMentioned())
492         PhiInserter.AddAvailableValue(Dominator.getResult(), Default);
493
494       Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
495     }
496   }
497 }
498
499 /// \brief Remove all PHI values coming from "From" into "To" and remember
500 /// them in DeletedPhis
501 void AMDGPUStructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
502   PhiMap &Map = DeletedPhis[To];
503   for (BasicBlock::iterator I = To->begin(), E = To->end();
504        I != E && isa<PHINode>(*I);) {
505
506     PHINode &Phi = cast<PHINode>(*I++);
507     while (Phi.getBasicBlockIndex(From) != -1) {
508       Value *Deleted = Phi.removeIncomingValue(From, false);
509       Map[&Phi].push_back(std::make_pair(From, Deleted));
510     }
511   }
512 }
513
514 /// \brief Add a dummy PHI value as soon as we knew the new predecessor
515 void AMDGPUStructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
516   for (BasicBlock::iterator I = To->begin(), E = To->end();
517        I != E && isa<PHINode>(*I);) {
518
519     PHINode &Phi = cast<PHINode>(*I++);
520     Value *Undef = UndefValue::get(Phi.getType());
521     Phi.addIncoming(Undef, From);
522   }
523   AddedPhis[To].push_back(From);
524 }
525
526 /// \brief Add the real PHI value as soon as everything is set up
527 void AMDGPUStructurizeCFG::setPhiValues() {
528
529   SSAUpdater Updater;
530   for (BB2BBVecMap::iterator AI = AddedPhis.begin(), AE = AddedPhis.end();
531        AI != AE; ++AI) {
532
533     BasicBlock *To = AI->first;
534     BBVector &From = AI->second;
535
536     if (!DeletedPhis.count(To))
537       continue;
538
539     PhiMap &Map = DeletedPhis[To];
540     for (PhiMap::iterator PI = Map.begin(), PE = Map.end();
541          PI != PE; ++PI) {
542
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);
548
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) {
553
554         Updater.AddAvailableValue(VI->first, VI->second);
555         Dominator.addBlock(VI->first);
556       }
557
558       if (!Dominator.wasResultExplicitMentioned())
559         Updater.AddAvailableValue(Dominator.getResult(), Undef);
560
561       for (BBVector::iterator FI = From.begin(), FE = From.end();
562            FI != FE; ++FI) {
563
564         int Idx = Phi->getBasicBlockIndex(*FI);
565         assert(Idx != -1);
566         Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(*FI));
567       }
568     }
569
570     DeletedPhis.erase(To);
571   }
572   assert(DeletedPhis.empty());
573 }
574
575 /// \brief Remove phi values from all successors and then remove the terminator.
576 void AMDGPUStructurizeCFG::killTerminator(BasicBlock *BB) {
577   TerminatorInst *Term = BB->getTerminator();
578   if (!Term)
579     return;
580
581   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
582        SI != SE; ++SI) {
583
584     delPhiValues(BB, *SI);
585   }
586
587   Term->eraseFromParent();
588 }
589
590 /// \brief Let node exit(s) point to NewExit
591 void AMDGPUStructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
592                                       bool IncludeDominator) {
593
594   if (Node->isSubRegion()) {
595     Region *SubRegion = Node->getNodeAs<Region>();
596     BasicBlock *OldExit = SubRegion->getExit();
597     BasicBlock *Dominator = 0;
598
599     // Find all the edges from the sub region to the exit
600     for (pred_iterator I = pred_begin(OldExit), E = pred_end(OldExit);
601          I != E;) {
602
603       BasicBlock *BB = *I++;
604       if (!SubRegion->contains(BB))
605         continue;
606
607       // Modify the edges to point to the new exit
608       delPhiValues(BB, OldExit);
609       BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
610       addPhiValues(BB, NewExit);
611
612       // Find the new dominator (if requested)
613       if (IncludeDominator) {
614         if (!Dominator)
615           Dominator = BB;
616         else
617           Dominator = DT->findNearestCommonDominator(Dominator, BB);
618       }
619     }
620
621     // Change the dominator (if requested)
622     if (Dominator)
623       DT->changeImmediateDominator(NewExit, Dominator);
624
625     // Update the region info
626     SubRegion->replaceExit(NewExit);
627
628   } else {
629     BasicBlock *BB = Node->getNodeAs<BasicBlock>();
630     killTerminator(BB);
631     BranchInst::Create(NewExit, BB);
632     addPhiValues(BB, NewExit);
633     if (IncludeDominator)
634       DT->changeImmediateDominator(NewExit, BB);
635   }
636 }
637
638 /// \brief Create a new flow node and update dominator tree and region info
639 BasicBlock *AMDGPUStructurizeCFG::getNextFlow(BasicBlock *Dominator) {
640   LLVMContext &Context = Func->getContext();
641   BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
642                        Order.back()->getEntry();
643   BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
644                                         Func, Insert);
645   DT->addNewBlock(Flow, Dominator);
646   ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
647   return Flow;
648 }
649
650 /// \brief Create a new or reuse the previous node as flow node
651 BasicBlock *AMDGPUStructurizeCFG::needPrefix(bool NeedEmpty) {
652
653   BasicBlock *Entry = PrevNode->getEntry();
654
655   if (!PrevNode->isSubRegion()) {
656     killTerminator(Entry);
657     if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
658       return Entry;
659
660   } 
661
662   // create a new flow node
663   BasicBlock *Flow = getNextFlow(Entry);
664
665   // and wire it up
666   changeExit(PrevNode, Flow, true);
667   PrevNode = ParentRegion->getBBNode(Flow);
668   return Flow;
669 }
670
671 /// \brief Returns the region exit if possible, otherwise just a new flow node
672 BasicBlock *AMDGPUStructurizeCFG::needPostfix(BasicBlock *Flow,
673                                               bool ExitUseAllowed) {
674
675   if (Order.empty() && ExitUseAllowed) {
676     BasicBlock *Exit = ParentRegion->getExit();
677     DT->changeImmediateDominator(Exit, Flow);
678     addPhiValues(Flow, Exit);
679     return Exit;
680   }
681   return getNextFlow(Flow);
682 }
683
684 /// \brief Set the previous node
685 void AMDGPUStructurizeCFG::setPrevNode(BasicBlock *BB) {
686   PrevNode =  ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB) : 0;
687 }
688
689 /// \brief Does BB dominate all the predicates of Node ?
690 bool AMDGPUStructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
691   BBPredicates &Preds = Predicates[Node->getEntry()];
692   for (BBPredicates::iterator PI = Preds.begin(), PE = Preds.end();
693        PI != PE; ++PI) {
694
695     if (!DT->dominates(BB, PI->first))
696       return false;
697   }
698   return true;
699 }
700
701 /// \brief Can we predict that this node will always be called?
702 bool AMDGPUStructurizeCFG::isPredictableTrue(RegionNode *Node) {
703
704   BBPredicates &Preds = Predicates[Node->getEntry()];
705   bool Dominated = false;
706
707   // Regionentry is always true
708   if (PrevNode == 0)
709     return true;
710
711   for (BBPredicates::iterator I = Preds.begin(), E = Preds.end();
712        I != E; ++I) {
713
714     if (I->second != BoolTrue)
715       return false;
716
717     if (!Dominated && DT->dominates(I->first, PrevNode->getEntry()))
718       Dominated = true;
719   }
720
721   // TODO: The dominator check is too strict
722   return Dominated;
723 }
724
725 /// Take one node from the order vector and wire it up
726 void AMDGPUStructurizeCFG::wireFlow(bool ExitUseAllowed,
727                                     BasicBlock *LoopEnd) {
728
729   RegionNode *Node = Order.pop_back_val();
730   Visited.insert(Node->getEntry());
731
732   if (isPredictableTrue(Node)) {
733     // Just a linear flow
734     if (PrevNode) {
735       changeExit(PrevNode, Node->getEntry(), true);
736     }
737     PrevNode = Node;
738
739   } else {
740     // Insert extra prefix node (or reuse last one)
741     BasicBlock *Flow = needPrefix(false);
742
743     // Insert extra postfix node (or use exit instead)
744     BasicBlock *Entry = Node->getEntry();
745     BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
746
747     // let it point to entry and next block
748     Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
749     addPhiValues(Flow, Entry);
750     DT->changeImmediateDominator(Entry, Flow);
751
752     PrevNode = Node;
753     while (!Order.empty() && !Visited.count(LoopEnd) &&
754            dominatesPredicates(Entry, Order.back())) {
755       handleLoops(false, LoopEnd);
756     }
757
758     changeExit(PrevNode, Next, false);
759     setPrevNode(Next);
760   }
761 }
762
763 void AMDGPUStructurizeCFG::handleLoops(bool ExitUseAllowed,
764                                        BasicBlock *LoopEnd) {
765   RegionNode *Node = Order.back();
766   BasicBlock *LoopStart = Node->getEntry();
767
768   if (!Loops.count(LoopStart)) {
769     wireFlow(ExitUseAllowed, LoopEnd);
770     return;
771   }
772
773   if (!isPredictableTrue(Node))
774     LoopStart = needPrefix(true);
775
776   LoopEnd = Loops[Node->getEntry()];
777   wireFlow(false, LoopEnd);
778   while (!Visited.count(LoopEnd)) {
779     handleLoops(false, LoopEnd);
780   }
781
782   // Create an extra loop end node
783   LoopEnd = needPrefix(false);
784   BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
785   LoopConds.push_back(BranchInst::Create(Next, LoopStart,
786                                          BoolUndef, LoopEnd));
787   addPhiValues(LoopEnd, LoopStart);
788   setPrevNode(Next);
789 }
790
791 /// After this function control flow looks like it should be, but
792 /// branches and PHI nodes only have undefined conditions.
793 void AMDGPUStructurizeCFG::createFlow() {
794
795   BasicBlock *Exit = ParentRegion->getExit();
796   bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
797
798   DeletedPhis.clear();
799   AddedPhis.clear();
800   Conditions.clear();
801   LoopConds.clear();
802
803   PrevNode = 0;
804   Visited.clear();
805
806   while (!Order.empty()) {
807     handleLoops(EntryDominatesExit, 0);
808   }
809
810   if (PrevNode)
811     changeExit(PrevNode, Exit, EntryDominatesExit);
812   else
813     assert(EntryDominatesExit);
814 }
815
816 /// Handle a rare case where the disintegrated nodes instructions
817 /// no longer dominate all their uses. Not sure if this is really nessasary
818 void AMDGPUStructurizeCFG::rebuildSSA() {
819   SSAUpdater Updater;
820   for (Region::block_iterator I = ParentRegion->block_begin(),
821                               E = ParentRegion->block_end();
822        I != E; ++I) {
823
824     BasicBlock *BB = *I;
825     for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
826          II != IE; ++II) {
827
828       bool Initialized = false;
829       for (Use *I = &II->use_begin().getUse(), *Next; I; I = Next) {
830
831         Next = I->getNext();
832
833         Instruction *User = cast<Instruction>(I->getUser());
834         if (User->getParent() == BB) {
835           continue;
836
837         } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
838           if (UserPN->getIncomingBlock(*I) == BB)
839             continue;
840         }
841
842         if (DT->dominates(II, User))
843           continue;
844
845         if (!Initialized) {
846           Value *Undef = UndefValue::get(II->getType());
847           Updater.Initialize(II->getType(), "");
848           Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
849           Updater.AddAvailableValue(BB, II);
850           Initialized = true;
851         }
852         Updater.RewriteUseAfterInsertions(*I);
853       }
854     }
855   }
856 }
857
858 /// \brief Run the transformation for each region found
859 bool AMDGPUStructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
860   if (R->isTopLevelRegion())
861     return false;
862
863   Func = R->getEntry()->getParent();
864   ParentRegion = R;
865
866   DT = &getAnalysis<DominatorTree>();
867
868   orderNodes();
869   collectInfos();
870   createFlow();
871   insertConditions(false);
872   insertConditions(true);
873   setPhiValues();
874   rebuildSSA();
875
876   // Cleanup
877   Order.clear();
878   Visited.clear();
879   DeletedPhis.clear();
880   AddedPhis.clear();
881   Predicates.clear();
882   Conditions.clear();
883   Loops.clear();
884   LoopPreds.clear();
885   LoopConds.clear();
886
887   return true;
888 }
889
890 /// \brief Create the pass
891 Pass *llvm::createAMDGPUStructurizeCFGPass() {
892   return new AMDGPUStructurizeCFG();
893 }