xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUMachineCFGStructurizer.cpp (revision 179219ea046f46927d6478d43431e8b541703539)
1 //===- AMDGPUMachineCFGStructurizer.cpp - Machine code if conversion pass. ===//
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 // This file implements the machine instruction level CFG structurizer pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AMDGPU.h"
14 #include "GCNSubtarget.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegionInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/TargetRegisterInfo.h"
24 #include "llvm/InitializePasses.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "amdgpucfgstructurizer"
29 
30 namespace {
31 
32 class PHILinearizeDestIterator;
33 
34 class PHILinearize {
35   friend class PHILinearizeDestIterator;
36 
37 public:
38   using PHISourceT = std::pair<unsigned, MachineBasicBlock *>;
39 
40 private:
41   using PHISourcesT = DenseSet<PHISourceT>;
42   using PHIInfoElementT = struct {
43     unsigned DestReg;
44     DebugLoc DL;
45     PHISourcesT Sources;
46   };
47   using PHIInfoT = SmallPtrSet<PHIInfoElementT *, 2>;
48   PHIInfoT PHIInfo;
49 
50   static unsigned phiInfoElementGetDest(PHIInfoElementT *Info);
51   static void phiInfoElementSetDef(PHIInfoElementT *Info, unsigned NewDef);
52   static PHISourcesT &phiInfoElementGetSources(PHIInfoElementT *Info);
53   static void phiInfoElementAddSource(PHIInfoElementT *Info, unsigned SourceReg,
54                                       MachineBasicBlock *SourceMBB);
55   static void phiInfoElementRemoveSource(PHIInfoElementT *Info,
56                                          unsigned SourceReg,
57                                          MachineBasicBlock *SourceMBB);
58   PHIInfoElementT *findPHIInfoElement(unsigned DestReg);
59   PHIInfoElementT *findPHIInfoElementFromSource(unsigned SourceReg,
60                                                 MachineBasicBlock *SourceMBB);
61 
62 public:
63   bool findSourcesFromMBB(MachineBasicBlock *SourceMBB,
64                           SmallVector<unsigned, 4> &Sources);
65   void addDest(unsigned DestReg, const DebugLoc &DL);
66   void replaceDef(unsigned OldDestReg, unsigned NewDestReg);
67   void deleteDef(unsigned DestReg);
68   void addSource(unsigned DestReg, unsigned SourceReg,
69                  MachineBasicBlock *SourceMBB);
70   void removeSource(unsigned DestReg, unsigned SourceReg,
71                     MachineBasicBlock *SourceMBB = nullptr);
72   bool findDest(unsigned SourceReg, MachineBasicBlock *SourceMBB,
73                 unsigned &DestReg);
74   bool isSource(unsigned Reg, MachineBasicBlock *SourceMBB = nullptr);
75   unsigned getNumSources(unsigned DestReg);
76   void dump(MachineRegisterInfo *MRI);
77   void clear();
78 
79   using source_iterator = PHISourcesT::iterator;
80   using dest_iterator = PHILinearizeDestIterator;
81 
82   dest_iterator dests_begin();
83   dest_iterator dests_end();
84 
85   source_iterator sources_begin(unsigned Reg);
86   source_iterator sources_end(unsigned Reg);
87 };
88 
89 class PHILinearizeDestIterator {
90 private:
91   PHILinearize::PHIInfoT::iterator Iter;
92 
93 public:
94   PHILinearizeDestIterator(PHILinearize::PHIInfoT::iterator I) : Iter(I) {}
95 
96   unsigned operator*() { return PHILinearize::phiInfoElementGetDest(*Iter); }
97   PHILinearizeDestIterator &operator++() {
98     ++Iter;
99     return *this;
100   }
101   bool operator==(const PHILinearizeDestIterator &I) const {
102     return I.Iter == Iter;
103   }
104   bool operator!=(const PHILinearizeDestIterator &I) const {
105     return I.Iter != Iter;
106   }
107 };
108 
109 } // end anonymous namespace
110 
111 unsigned PHILinearize::phiInfoElementGetDest(PHIInfoElementT *Info) {
112   return Info->DestReg;
113 }
114 
115 void PHILinearize::phiInfoElementSetDef(PHIInfoElementT *Info,
116                                         unsigned NewDef) {
117   Info->DestReg = NewDef;
118 }
119 
120 PHILinearize::PHISourcesT &
121 PHILinearize::phiInfoElementGetSources(PHIInfoElementT *Info) {
122   return Info->Sources;
123 }
124 
125 void PHILinearize::phiInfoElementAddSource(PHIInfoElementT *Info,
126                                            unsigned SourceReg,
127                                            MachineBasicBlock *SourceMBB) {
128   // Assertion ensures we don't use the same SourceMBB for the
129   // sources, because we cannot have different registers with
130   // identical predecessors, but we can have the same register for
131   // multiple predecessors.
132 #if !defined(NDEBUG)
133   for (auto SI : phiInfoElementGetSources(Info)) {
134     assert((SI.second != SourceMBB || SourceReg == SI.first));
135   }
136 #endif
137 
138   phiInfoElementGetSources(Info).insert(PHISourceT(SourceReg, SourceMBB));
139 }
140 
141 void PHILinearize::phiInfoElementRemoveSource(PHIInfoElementT *Info,
142                                               unsigned SourceReg,
143                                               MachineBasicBlock *SourceMBB) {
144   auto &Sources = phiInfoElementGetSources(Info);
145   SmallVector<PHISourceT, 4> ElimiatedSources;
146   for (auto SI : Sources) {
147     if (SI.first == SourceReg &&
148         (SI.second == nullptr || SI.second == SourceMBB)) {
149       ElimiatedSources.push_back(PHISourceT(SI.first, SI.second));
150     }
151   }
152 
153   for (auto &Source : ElimiatedSources) {
154     Sources.erase(Source);
155   }
156 }
157 
158 PHILinearize::PHIInfoElementT *
159 PHILinearize::findPHIInfoElement(unsigned DestReg) {
160   for (auto I : PHIInfo) {
161     if (phiInfoElementGetDest(I) == DestReg) {
162       return I;
163     }
164   }
165   return nullptr;
166 }
167 
168 PHILinearize::PHIInfoElementT *
169 PHILinearize::findPHIInfoElementFromSource(unsigned SourceReg,
170                                            MachineBasicBlock *SourceMBB) {
171   for (auto I : PHIInfo) {
172     for (auto SI : phiInfoElementGetSources(I)) {
173       if (SI.first == SourceReg &&
174           (SI.second == nullptr || SI.second == SourceMBB)) {
175         return I;
176       }
177     }
178   }
179   return nullptr;
180 }
181 
182 bool PHILinearize::findSourcesFromMBB(MachineBasicBlock *SourceMBB,
183                                       SmallVector<unsigned, 4> &Sources) {
184   bool FoundSource = false;
185   for (auto I : PHIInfo) {
186     for (auto SI : phiInfoElementGetSources(I)) {
187       if (SI.second == SourceMBB) {
188         FoundSource = true;
189         Sources.push_back(SI.first);
190       }
191     }
192   }
193   return FoundSource;
194 }
195 
196 void PHILinearize::addDest(unsigned DestReg, const DebugLoc &DL) {
197   assert(findPHIInfoElement(DestReg) == nullptr && "Dest already exsists");
198   PHISourcesT EmptySet;
199   PHIInfoElementT *NewElement = new PHIInfoElementT();
200   NewElement->DestReg = DestReg;
201   NewElement->DL = DL;
202   NewElement->Sources = EmptySet;
203   PHIInfo.insert(NewElement);
204 }
205 
206 void PHILinearize::replaceDef(unsigned OldDestReg, unsigned NewDestReg) {
207   phiInfoElementSetDef(findPHIInfoElement(OldDestReg), NewDestReg);
208 }
209 
210 void PHILinearize::deleteDef(unsigned DestReg) {
211   PHIInfoElementT *InfoElement = findPHIInfoElement(DestReg);
212   PHIInfo.erase(InfoElement);
213   delete InfoElement;
214 }
215 
216 void PHILinearize::addSource(unsigned DestReg, unsigned SourceReg,
217                              MachineBasicBlock *SourceMBB) {
218   phiInfoElementAddSource(findPHIInfoElement(DestReg), SourceReg, SourceMBB);
219 }
220 
221 void PHILinearize::removeSource(unsigned DestReg, unsigned SourceReg,
222                                 MachineBasicBlock *SourceMBB) {
223   phiInfoElementRemoveSource(findPHIInfoElement(DestReg), SourceReg, SourceMBB);
224 }
225 
226 bool PHILinearize::findDest(unsigned SourceReg, MachineBasicBlock *SourceMBB,
227                             unsigned &DestReg) {
228   PHIInfoElementT *InfoElement =
229       findPHIInfoElementFromSource(SourceReg, SourceMBB);
230   if (InfoElement != nullptr) {
231     DestReg = phiInfoElementGetDest(InfoElement);
232     return true;
233   }
234   return false;
235 }
236 
237 bool PHILinearize::isSource(unsigned Reg, MachineBasicBlock *SourceMBB) {
238   unsigned DestReg;
239   return findDest(Reg, SourceMBB, DestReg);
240 }
241 
242 unsigned PHILinearize::getNumSources(unsigned DestReg) {
243   return phiInfoElementGetSources(findPHIInfoElement(DestReg)).size();
244 }
245 
246 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
247 LLVM_DUMP_METHOD void PHILinearize::dump(MachineRegisterInfo *MRI) {
248   const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
249   dbgs() << "=PHIInfo Start=\n";
250   for (auto PII : this->PHIInfo) {
251     PHIInfoElementT &Element = *PII;
252     dbgs() << "Dest: " << printReg(Element.DestReg, TRI)
253            << " Sources: {";
254     for (auto &SI : Element.Sources) {
255       dbgs() << printReg(SI.first, TRI) << '(' << printMBBReference(*SI.second)
256              << "),";
257     }
258     dbgs() << "}\n";
259   }
260   dbgs() << "=PHIInfo End=\n";
261 }
262 #endif
263 
264 void PHILinearize::clear() { PHIInfo = PHIInfoT(); }
265 
266 PHILinearize::dest_iterator PHILinearize::dests_begin() {
267   return PHILinearizeDestIterator(PHIInfo.begin());
268 }
269 
270 PHILinearize::dest_iterator PHILinearize::dests_end() {
271   return PHILinearizeDestIterator(PHIInfo.end());
272 }
273 
274 PHILinearize::source_iterator PHILinearize::sources_begin(unsigned Reg) {
275   auto InfoElement = findPHIInfoElement(Reg);
276   return phiInfoElementGetSources(InfoElement).begin();
277 }
278 
279 PHILinearize::source_iterator PHILinearize::sources_end(unsigned Reg) {
280   auto InfoElement = findPHIInfoElement(Reg);
281   return phiInfoElementGetSources(InfoElement).end();
282 }
283 
284 static unsigned getPHINumInputs(MachineInstr &PHI) {
285   assert(PHI.isPHI());
286   return (PHI.getNumOperands() - 1) / 2;
287 }
288 
289 static MachineBasicBlock *getPHIPred(MachineInstr &PHI, unsigned Index) {
290   assert(PHI.isPHI());
291   return PHI.getOperand(Index * 2 + 2).getMBB();
292 }
293 
294 static void setPhiPred(MachineInstr &PHI, unsigned Index,
295                        MachineBasicBlock *NewPred) {
296   PHI.getOperand(Index * 2 + 2).setMBB(NewPred);
297 }
298 
299 static unsigned getPHISourceReg(MachineInstr &PHI, unsigned Index) {
300   assert(PHI.isPHI());
301   return PHI.getOperand(Index * 2 + 1).getReg();
302 }
303 
304 static unsigned getPHIDestReg(MachineInstr &PHI) {
305   assert(PHI.isPHI());
306   return PHI.getOperand(0).getReg();
307 }
308 
309 namespace {
310 
311 class RegionMRT;
312 class MBBMRT;
313 
314 class LinearizedRegion {
315 protected:
316   MachineBasicBlock *Entry;
317   // The exit block is part of the region, and is the last
318   // merge block before exiting the region.
319   MachineBasicBlock *Exit;
320   DenseSet<unsigned> LiveOuts;
321   SmallPtrSet<MachineBasicBlock *, 1> MBBs;
322   bool HasLoop;
323   LinearizedRegion *Parent;
324   RegionMRT *RMRT;
325 
326   void storeLiveOutReg(MachineBasicBlock *MBB, Register Reg,
327                        MachineInstr *DefInstr, const MachineRegisterInfo *MRI,
328                        const TargetRegisterInfo *TRI, PHILinearize &PHIInfo);
329 
330   void storeLiveOutRegRegion(RegionMRT *Region, Register Reg,
331                              MachineInstr *DefInstr,
332                              const MachineRegisterInfo *MRI,
333                              const TargetRegisterInfo *TRI,
334                              PHILinearize &PHIInfo);
335 
336   void storeMBBLiveOuts(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI,
337                         const TargetRegisterInfo *TRI, PHILinearize &PHIInfo,
338                         RegionMRT *TopRegion);
339 
340   void storeLiveOuts(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI,
341                      const TargetRegisterInfo *TRI, PHILinearize &PHIInfo);
342 
343   void storeLiveOuts(RegionMRT *Region, const MachineRegisterInfo *MRI,
344                      const TargetRegisterInfo *TRI, PHILinearize &PHIInfo,
345                      RegionMRT *TopRegion = nullptr);
346 
347 public:
348   LinearizedRegion();
349   LinearizedRegion(MachineBasicBlock *MBB, const MachineRegisterInfo *MRI,
350                    const TargetRegisterInfo *TRI, PHILinearize &PHIInfo);
351   ~LinearizedRegion() = default;
352 
353   void setRegionMRT(RegionMRT *Region) { RMRT = Region; }
354 
355   RegionMRT *getRegionMRT() { return RMRT; }
356 
357   void setParent(LinearizedRegion *P) { Parent = P; }
358 
359   LinearizedRegion *getParent() { return Parent; }
360 
361   void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr);
362 
363   void setBBSelectRegIn(unsigned Reg);
364 
365   unsigned getBBSelectRegIn();
366 
367   void setBBSelectRegOut(unsigned Reg, bool IsLiveOut);
368 
369   unsigned getBBSelectRegOut();
370 
371   void setHasLoop(bool Value);
372 
373   bool getHasLoop();
374 
375   void addLiveOut(unsigned VReg);
376 
377   void removeLiveOut(unsigned Reg);
378 
379   void replaceLiveOut(unsigned OldReg, unsigned NewReg);
380 
381   void replaceRegister(unsigned Register, class Register NewRegister,
382                        MachineRegisterInfo *MRI, bool ReplaceInside,
383                        bool ReplaceOutside, bool IncludeLoopPHIs);
384 
385   void replaceRegisterInsideRegion(unsigned Register, unsigned NewRegister,
386                                    bool IncludeLoopPHIs,
387                                    MachineRegisterInfo *MRI);
388 
389   void replaceRegisterOutsideRegion(unsigned Register, unsigned NewRegister,
390                                     bool IncludeLoopPHIs,
391                                     MachineRegisterInfo *MRI);
392 
393   DenseSet<unsigned> *getLiveOuts();
394 
395   void setEntry(MachineBasicBlock *NewEntry);
396 
397   MachineBasicBlock *getEntry();
398 
399   void setExit(MachineBasicBlock *NewExit);
400 
401   MachineBasicBlock *getExit();
402 
403   void addMBB(MachineBasicBlock *MBB);
404 
405   void addMBBs(LinearizedRegion *InnerRegion);
406 
407   bool contains(MachineBasicBlock *MBB);
408 
409   bool isLiveOut(unsigned Reg);
410 
411   bool hasNoDef(unsigned Reg, MachineRegisterInfo *MRI);
412 
413   void removeFalseRegisterKills(MachineRegisterInfo *MRI);
414 
415   void initLiveOut(RegionMRT *Region, const MachineRegisterInfo *MRI,
416                    const TargetRegisterInfo *TRI, PHILinearize &PHIInfo);
417 };
418 
419 class MRT {
420 protected:
421   RegionMRT *Parent;
422   unsigned BBSelectRegIn;
423   unsigned BBSelectRegOut;
424 
425 public:
426   virtual ~MRT() = default;
427 
428   unsigned getBBSelectRegIn() { return BBSelectRegIn; }
429 
430   unsigned getBBSelectRegOut() { return BBSelectRegOut; }
431 
432   void setBBSelectRegIn(unsigned Reg) { BBSelectRegIn = Reg; }
433 
434   void setBBSelectRegOut(unsigned Reg) { BBSelectRegOut = Reg; }
435 
436   virtual RegionMRT *getRegionMRT() { return nullptr; }
437 
438   virtual MBBMRT *getMBBMRT() { return nullptr; }
439 
440   bool isRegion() { return getRegionMRT() != nullptr; }
441 
442   bool isMBB() { return getMBBMRT() != nullptr; }
443 
444   bool isRoot() { return Parent == nullptr; }
445 
446   void setParent(RegionMRT *Region) { Parent = Region; }
447 
448   RegionMRT *getParent() { return Parent; }
449 
450   static MachineBasicBlock *
451   initializeMRT(MachineFunction &MF, const MachineRegionInfo *RegionInfo,
452                 DenseMap<MachineRegion *, RegionMRT *> &RegionMap);
453 
454   static RegionMRT *buildMRT(MachineFunction &MF,
455                              const MachineRegionInfo *RegionInfo,
456                              const SIInstrInfo *TII,
457                              MachineRegisterInfo *MRI);
458 
459   virtual void dump(const TargetRegisterInfo *TRI, int depth = 0) = 0;
460 
461   void dumpDepth(int depth) {
462     for (int i = depth; i > 0; --i) {
463       dbgs() << "  ";
464     }
465   }
466 };
467 
468 class MBBMRT : public MRT {
469   MachineBasicBlock *MBB;
470 
471 public:
472   MBBMRT(MachineBasicBlock *BB) : MBB(BB) {
473     setParent(nullptr);
474     setBBSelectRegOut(0);
475     setBBSelectRegIn(0);
476   }
477 
478   MBBMRT *getMBBMRT() override { return this; }
479 
480   MachineBasicBlock *getMBB() { return MBB; }
481 
482   void dump(const TargetRegisterInfo *TRI, int depth = 0) override {
483     dumpDepth(depth);
484     dbgs() << "MBB: " << getMBB()->getNumber();
485     dbgs() << " In: " << printReg(getBBSelectRegIn(), TRI);
486     dbgs() << ", Out: " << printReg(getBBSelectRegOut(), TRI) << "\n";
487   }
488 };
489 
490 class RegionMRT : public MRT {
491 protected:
492   MachineRegion *Region;
493   LinearizedRegion *LRegion = nullptr;
494   MachineBasicBlock *Succ = nullptr;
495   SetVector<MRT *> Children;
496 
497 public:
498   RegionMRT(MachineRegion *MachineRegion) : Region(MachineRegion) {
499     setParent(nullptr);
500     setBBSelectRegOut(0);
501     setBBSelectRegIn(0);
502   }
503 
504   ~RegionMRT() override {
505     if (LRegion) {
506       delete LRegion;
507     }
508 
509     for (auto CI : Children) {
510       delete &(*CI);
511     }
512   }
513 
514   RegionMRT *getRegionMRT() override { return this; }
515 
516   void setLinearizedRegion(LinearizedRegion *LinearizeRegion) {
517     LRegion = LinearizeRegion;
518   }
519 
520   LinearizedRegion *getLinearizedRegion() { return LRegion; }
521 
522   MachineRegion *getMachineRegion() { return Region; }
523 
524   unsigned getInnerOutputRegister() {
525     return (*(Children.begin()))->getBBSelectRegOut();
526   }
527 
528   void addChild(MRT *Tree) { Children.insert(Tree); }
529 
530   SetVector<MRT *> *getChildren() { return &Children; }
531 
532   void dump(const TargetRegisterInfo *TRI, int depth = 0) override {
533     dumpDepth(depth);
534     dbgs() << "Region: " << (void *)Region;
535     dbgs() << " In: " << printReg(getBBSelectRegIn(), TRI);
536     dbgs() << ", Out: " << printReg(getBBSelectRegOut(), TRI) << "\n";
537 
538     dumpDepth(depth);
539     if (getSucc())
540       dbgs() << "Succ: " << getSucc()->getNumber() << "\n";
541     else
542       dbgs() << "Succ: none \n";
543     for (auto MRTI : Children) {
544       MRTI->dump(TRI, depth + 1);
545     }
546   }
547 
548   MRT *getEntryTree() { return Children.back(); }
549 
550   MRT *getExitTree() { return Children.front(); }
551 
552   MachineBasicBlock *getEntry() {
553     MRT *Tree = Children.back();
554     return (Tree->isRegion()) ? Tree->getRegionMRT()->getEntry()
555                               : Tree->getMBBMRT()->getMBB();
556   }
557 
558   MachineBasicBlock *getExit() {
559     MRT *Tree = Children.front();
560     return (Tree->isRegion()) ? Tree->getRegionMRT()->getExit()
561                               : Tree->getMBBMRT()->getMBB();
562   }
563 
564   void setSucc(MachineBasicBlock *MBB) { Succ = MBB; }
565 
566   MachineBasicBlock *getSucc() { return Succ; }
567 
568   bool contains(MachineBasicBlock *MBB) {
569     for (auto CI : Children) {
570       if (CI->isMBB()) {
571         if (MBB == CI->getMBBMRT()->getMBB()) {
572           return true;
573         }
574       } else {
575         if (CI->getRegionMRT()->contains(MBB)) {
576           return true;
577         } else if (CI->getRegionMRT()->getLinearizedRegion() != nullptr &&
578                    CI->getRegionMRT()->getLinearizedRegion()->contains(MBB)) {
579           return true;
580         }
581       }
582     }
583     return false;
584   }
585 
586   void replaceLiveOutReg(unsigned Register, unsigned NewRegister) {
587     LinearizedRegion *LRegion = getLinearizedRegion();
588     LRegion->replaceLiveOut(Register, NewRegister);
589     for (auto &CI : Children) {
590       if (CI->isRegion()) {
591         CI->getRegionMRT()->replaceLiveOutReg(Register, NewRegister);
592       }
593     }
594   }
595 };
596 
597 } // end anonymous namespace
598 
599 static unsigned createBBSelectReg(const SIInstrInfo *TII,
600                                   MachineRegisterInfo *MRI) {
601   return MRI->createVirtualRegister(TII->getPreferredSelectRegClass(32));
602 }
603 
604 MachineBasicBlock *
605 MRT::initializeMRT(MachineFunction &MF, const MachineRegionInfo *RegionInfo,
606                    DenseMap<MachineRegion *, RegionMRT *> &RegionMap) {
607   for (auto &MFI : MF) {
608     MachineBasicBlock *ExitMBB = &MFI;
609     if (ExitMBB->succ_size() == 0) {
610       return ExitMBB;
611     }
612   }
613   llvm_unreachable("CFG has no exit block");
614   return nullptr;
615 }
616 
617 RegionMRT *MRT::buildMRT(MachineFunction &MF,
618                          const MachineRegionInfo *RegionInfo,
619                          const SIInstrInfo *TII, MachineRegisterInfo *MRI) {
620   SmallPtrSet<MachineRegion *, 4> PlacedRegions;
621   DenseMap<MachineRegion *, RegionMRT *> RegionMap;
622   MachineRegion *TopLevelRegion = RegionInfo->getTopLevelRegion();
623   RegionMRT *Result = new RegionMRT(TopLevelRegion);
624   RegionMap[TopLevelRegion] = Result;
625 
626   // Insert the exit block first, we need it to be the merge node
627   // for the top level region.
628   MachineBasicBlock *Exit = initializeMRT(MF, RegionInfo, RegionMap);
629 
630   unsigned BBSelectRegIn = createBBSelectReg(TII, MRI);
631   MBBMRT *ExitMRT = new MBBMRT(Exit);
632   RegionMap[RegionInfo->getRegionFor(Exit)]->addChild(ExitMRT);
633   ExitMRT->setBBSelectRegIn(BBSelectRegIn);
634 
635   for (auto MBBI : post_order(&(MF.front()))) {
636     MachineBasicBlock *MBB = &(*MBBI);
637 
638     // Skip Exit since we already added it
639     if (MBB == Exit) {
640       continue;
641     }
642 
643     LLVM_DEBUG(dbgs() << "Visiting " << printMBBReference(*MBB) << "\n");
644     MBBMRT *NewMBB = new MBBMRT(MBB);
645     MachineRegion *Region = RegionInfo->getRegionFor(MBB);
646 
647     // Ensure we have the MRT region
648     if (RegionMap.count(Region) == 0) {
649       RegionMRT *NewMRTRegion = new RegionMRT(Region);
650       RegionMap[Region] = NewMRTRegion;
651 
652       // Ensure all parents are in the RegionMap
653       MachineRegion *Parent = Region->getParent();
654       while (RegionMap.count(Parent) == 0) {
655         RegionMRT *NewMRTParent = new RegionMRT(Parent);
656         NewMRTParent->addChild(NewMRTRegion);
657         NewMRTRegion->setParent(NewMRTParent);
658         RegionMap[Parent] = NewMRTParent;
659         NewMRTRegion = NewMRTParent;
660         Parent = Parent->getParent();
661       }
662       RegionMap[Parent]->addChild(NewMRTRegion);
663       NewMRTRegion->setParent(RegionMap[Parent]);
664     }
665 
666     // Add MBB to Region MRT
667     RegionMap[Region]->addChild(NewMBB);
668     NewMBB->setParent(RegionMap[Region]);
669     RegionMap[Region]->setSucc(Region->getExit());
670   }
671   return Result;
672 }
673 
674 void LinearizedRegion::storeLiveOutReg(MachineBasicBlock *MBB, Register Reg,
675                                        MachineInstr *DefInstr,
676                                        const MachineRegisterInfo *MRI,
677                                        const TargetRegisterInfo *TRI,
678                                        PHILinearize &PHIInfo) {
679   if (Reg.isVirtual()) {
680     LLVM_DEBUG(dbgs() << "Considering Register: " << printReg(Reg, TRI)
681                       << "\n");
682     // If this is a source register to a PHI we are chaining, it
683     // must be live out.
684     if (PHIInfo.isSource(Reg)) {
685       LLVM_DEBUG(dbgs() << "Add LiveOut (PHI): " << printReg(Reg, TRI) << "\n");
686       addLiveOut(Reg);
687     } else {
688       // If this is live out of the MBB
689       for (auto &UI : MRI->use_operands(Reg)) {
690         if (UI.getParent()->getParent() != MBB) {
691           LLVM_DEBUG(dbgs() << "Add LiveOut (MBB " << printMBBReference(*MBB)
692                             << "): " << printReg(Reg, TRI) << "\n");
693           addLiveOut(Reg);
694         } else {
695           // If the use is in the same MBB we have to make sure
696           // it is after the def, otherwise it is live out in a loop
697           MachineInstr *UseInstr = UI.getParent();
698           for (MachineBasicBlock::instr_iterator
699                    MII = UseInstr->getIterator(),
700                    MIE = UseInstr->getParent()->instr_end();
701                MII != MIE; ++MII) {
702             if ((&(*MII)) == DefInstr) {
703               LLVM_DEBUG(dbgs() << "Add LiveOut (Loop): " << printReg(Reg, TRI)
704                                 << "\n");
705               addLiveOut(Reg);
706             }
707           }
708         }
709       }
710     }
711   }
712 }
713 
714 void LinearizedRegion::storeLiveOutRegRegion(RegionMRT *Region, Register Reg,
715                                              MachineInstr *DefInstr,
716                                              const MachineRegisterInfo *MRI,
717                                              const TargetRegisterInfo *TRI,
718                                              PHILinearize &PHIInfo) {
719   if (Reg.isVirtual()) {
720     LLVM_DEBUG(dbgs() << "Considering Register: " << printReg(Reg, TRI)
721                       << "\n");
722     for (auto &UI : MRI->use_operands(Reg)) {
723       if (!Region->contains(UI.getParent()->getParent())) {
724         LLVM_DEBUG(dbgs() << "Add LiveOut (Region " << (void *)Region
725                           << "): " << printReg(Reg, TRI) << "\n");
726         addLiveOut(Reg);
727       }
728     }
729   }
730 }
731 
732 void LinearizedRegion::storeLiveOuts(MachineBasicBlock *MBB,
733                                      const MachineRegisterInfo *MRI,
734                                      const TargetRegisterInfo *TRI,
735                                      PHILinearize &PHIInfo) {
736   LLVM_DEBUG(dbgs() << "-Store Live Outs Begin (" << printMBBReference(*MBB)
737                     << ")-\n");
738   for (auto &II : *MBB) {
739     for (auto &RI : II.defs()) {
740       storeLiveOutReg(MBB, RI.getReg(), RI.getParent(), MRI, TRI, PHIInfo);
741     }
742     for (auto &IRI : II.implicit_operands()) {
743       if (IRI.isDef()) {
744         storeLiveOutReg(MBB, IRI.getReg(), IRI.getParent(), MRI, TRI, PHIInfo);
745       }
746     }
747   }
748 
749   // If we have a successor with a PHI, source coming from this MBB we have to
750   // add the register as live out
751   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
752                                         E = MBB->succ_end();
753        SI != E; ++SI) {
754     for (auto &II : *(*SI)) {
755       if (II.isPHI()) {
756         MachineInstr &PHI = II;
757         int numPreds = getPHINumInputs(PHI);
758         for (int i = 0; i < numPreds; ++i) {
759           if (getPHIPred(PHI, i) == MBB) {
760             unsigned PHIReg = getPHISourceReg(PHI, i);
761             LLVM_DEBUG(dbgs()
762                        << "Add LiveOut (PhiSource " << printMBBReference(*MBB)
763                        << " -> " << printMBBReference(*(*SI))
764                        << "): " << printReg(PHIReg, TRI) << "\n");
765             addLiveOut(PHIReg);
766           }
767         }
768       }
769     }
770   }
771 
772   LLVM_DEBUG(dbgs() << "-Store Live Outs Endn-\n");
773 }
774 
775 void LinearizedRegion::storeMBBLiveOuts(MachineBasicBlock *MBB,
776                                         const MachineRegisterInfo *MRI,
777                                         const TargetRegisterInfo *TRI,
778                                         PHILinearize &PHIInfo,
779                                         RegionMRT *TopRegion) {
780   for (auto &II : *MBB) {
781     for (auto &RI : II.defs()) {
782       storeLiveOutRegRegion(TopRegion, RI.getReg(), RI.getParent(), MRI, TRI,
783                             PHIInfo);
784     }
785     for (auto &IRI : II.implicit_operands()) {
786       if (IRI.isDef()) {
787         storeLiveOutRegRegion(TopRegion, IRI.getReg(), IRI.getParent(), MRI,
788                               TRI, PHIInfo);
789       }
790     }
791   }
792 }
793 
794 void LinearizedRegion::storeLiveOuts(RegionMRT *Region,
795                                      const MachineRegisterInfo *MRI,
796                                      const TargetRegisterInfo *TRI,
797                                      PHILinearize &PHIInfo,
798                                      RegionMRT *CurrentTopRegion) {
799   MachineBasicBlock *Exit = Region->getSucc();
800 
801   RegionMRT *TopRegion =
802       CurrentTopRegion == nullptr ? Region : CurrentTopRegion;
803 
804   // Check if exit is end of function, if so, no live outs.
805   if (Exit == nullptr)
806     return;
807 
808   auto Children = Region->getChildren();
809   for (auto CI : *Children) {
810     if (CI->isMBB()) {
811       auto MBB = CI->getMBBMRT()->getMBB();
812       storeMBBLiveOuts(MBB, MRI, TRI, PHIInfo, TopRegion);
813     } else {
814       LinearizedRegion *SubRegion = CI->getRegionMRT()->getLinearizedRegion();
815       // We should be limited to only store registers that are live out from the
816       // lineaized region
817       for (auto MBBI : SubRegion->MBBs) {
818         storeMBBLiveOuts(MBBI, MRI, TRI, PHIInfo, TopRegion);
819       }
820     }
821   }
822 
823   if (CurrentTopRegion == nullptr) {
824     auto Succ = Region->getSucc();
825     for (auto &II : *Succ) {
826       if (II.isPHI()) {
827         MachineInstr &PHI = II;
828         int numPreds = getPHINumInputs(PHI);
829         for (int i = 0; i < numPreds; ++i) {
830           if (Region->contains(getPHIPred(PHI, i))) {
831             unsigned PHIReg = getPHISourceReg(PHI, i);
832             LLVM_DEBUG(dbgs() << "Add Region LiveOut (" << (void *)Region
833                               << "): " << printReg(PHIReg, TRI) << "\n");
834             addLiveOut(PHIReg);
835           }
836         }
837       }
838     }
839   }
840 }
841 
842 #ifndef NDEBUG
843 void LinearizedRegion::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
844   OS << "Linearized Region {";
845   bool IsFirst = true;
846   for (auto MBB : MBBs) {
847     if (IsFirst) {
848       IsFirst = false;
849     } else {
850       OS << " ,";
851     }
852     OS << MBB->getNumber();
853   }
854   OS << "} (" << Entry->getNumber() << ", "
855      << (Exit == nullptr ? -1 : Exit->getNumber())
856      << "): In:" << printReg(getBBSelectRegIn(), TRI)
857      << " Out:" << printReg(getBBSelectRegOut(), TRI) << " {";
858   for (auto &LI : LiveOuts) {
859     OS << printReg(LI, TRI) << " ";
860   }
861   OS << "} \n";
862 }
863 #endif
864 
865 unsigned LinearizedRegion::getBBSelectRegIn() {
866   return getRegionMRT()->getBBSelectRegIn();
867 }
868 
869 unsigned LinearizedRegion::getBBSelectRegOut() {
870   return getRegionMRT()->getBBSelectRegOut();
871 }
872 
873 void LinearizedRegion::setHasLoop(bool Value) { HasLoop = Value; }
874 
875 bool LinearizedRegion::getHasLoop() { return HasLoop; }
876 
877 void LinearizedRegion::addLiveOut(unsigned VReg) { LiveOuts.insert(VReg); }
878 
879 void LinearizedRegion::removeLiveOut(unsigned Reg) {
880   if (isLiveOut(Reg))
881     LiveOuts.erase(Reg);
882 }
883 
884 void LinearizedRegion::replaceLiveOut(unsigned OldReg, unsigned NewReg) {
885   if (isLiveOut(OldReg)) {
886     removeLiveOut(OldReg);
887     addLiveOut(NewReg);
888   }
889 }
890 
891 void LinearizedRegion::replaceRegister(unsigned Register,
892                                        class Register NewRegister,
893                                        MachineRegisterInfo *MRI,
894                                        bool ReplaceInside, bool ReplaceOutside,
895                                        bool IncludeLoopPHI) {
896   assert(Register != NewRegister && "Cannot replace a reg with itself");
897 
898   LLVM_DEBUG(
899       dbgs() << "Pepareing to replace register (region): "
900              << printReg(Register, MRI->getTargetRegisterInfo()) << " with "
901              << printReg(NewRegister, MRI->getTargetRegisterInfo()) << "\n");
902 
903   // If we are replacing outside, we also need to update the LiveOuts
904   if (ReplaceOutside &&
905       (isLiveOut(Register) || this->getParent()->isLiveOut(Register))) {
906     LinearizedRegion *Current = this;
907     while (Current != nullptr && Current->getEntry() != nullptr) {
908       LLVM_DEBUG(dbgs() << "Region before register replace\n");
909       LLVM_DEBUG(Current->print(dbgs(), MRI->getTargetRegisterInfo()));
910       Current->replaceLiveOut(Register, NewRegister);
911       LLVM_DEBUG(dbgs() << "Region after register replace\n");
912       LLVM_DEBUG(Current->print(dbgs(), MRI->getTargetRegisterInfo()));
913       Current = Current->getParent();
914     }
915   }
916 
917   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Register),
918                                          E = MRI->reg_end();
919        I != E;) {
920     MachineOperand &O = *I;
921     ++I;
922 
923     // We don't rewrite defs.
924     if (O.isDef())
925       continue;
926 
927     bool IsInside = contains(O.getParent()->getParent());
928     bool IsLoopPHI = IsInside && (O.getParent()->isPHI() &&
929                                   O.getParent()->getParent() == getEntry());
930     bool ShouldReplace = (IsInside && ReplaceInside) ||
931                          (!IsInside && ReplaceOutside) ||
932                          (IncludeLoopPHI && IsLoopPHI);
933     if (ShouldReplace) {
934 
935       if (NewRegister.isPhysical()) {
936         LLVM_DEBUG(dbgs() << "Trying to substitute physical register: "
937                           << printReg(NewRegister, MRI->getTargetRegisterInfo())
938                           << "\n");
939         llvm_unreachable("Cannot substitute physical registers");
940       } else {
941         LLVM_DEBUG(dbgs() << "Replacing register (region): "
942                           << printReg(Register, MRI->getTargetRegisterInfo())
943                           << " with "
944                           << printReg(NewRegister, MRI->getTargetRegisterInfo())
945                           << "\n");
946         O.setReg(NewRegister);
947       }
948     }
949   }
950 }
951 
952 void LinearizedRegion::replaceRegisterInsideRegion(unsigned Register,
953                                                    unsigned NewRegister,
954                                                    bool IncludeLoopPHIs,
955                                                    MachineRegisterInfo *MRI) {
956   replaceRegister(Register, NewRegister, MRI, true, false, IncludeLoopPHIs);
957 }
958 
959 void LinearizedRegion::replaceRegisterOutsideRegion(unsigned Register,
960                                                     unsigned NewRegister,
961                                                     bool IncludeLoopPHIs,
962                                                     MachineRegisterInfo *MRI) {
963   replaceRegister(Register, NewRegister, MRI, false, true, IncludeLoopPHIs);
964 }
965 
966 DenseSet<unsigned> *LinearizedRegion::getLiveOuts() { return &LiveOuts; }
967 
968 void LinearizedRegion::setEntry(MachineBasicBlock *NewEntry) {
969   Entry = NewEntry;
970 }
971 
972 MachineBasicBlock *LinearizedRegion::getEntry() { return Entry; }
973 
974 void LinearizedRegion::setExit(MachineBasicBlock *NewExit) { Exit = NewExit; }
975 
976 MachineBasicBlock *LinearizedRegion::getExit() { return Exit; }
977 
978 void LinearizedRegion::addMBB(MachineBasicBlock *MBB) { MBBs.insert(MBB); }
979 
980 void LinearizedRegion::addMBBs(LinearizedRegion *InnerRegion) {
981   for (auto MBB : InnerRegion->MBBs) {
982     addMBB(MBB);
983   }
984 }
985 
986 bool LinearizedRegion::contains(MachineBasicBlock *MBB) {
987   return MBBs.contains(MBB);
988 }
989 
990 bool LinearizedRegion::isLiveOut(unsigned Reg) {
991   return LiveOuts.contains(Reg);
992 }
993 
994 bool LinearizedRegion::hasNoDef(unsigned Reg, MachineRegisterInfo *MRI) {
995   return MRI->def_begin(Reg) == MRI->def_end();
996 }
997 
998 // After the code has been structurized, what was flagged as kills
999 // before are no longer register kills.
1000 void LinearizedRegion::removeFalseRegisterKills(MachineRegisterInfo *MRI) {
1001   const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
1002   (void)TRI; // It's used by LLVM_DEBUG.
1003 
1004   for (auto MBBI : MBBs) {
1005     MachineBasicBlock *MBB = MBBI;
1006     for (auto &II : *MBB) {
1007       for (auto &RI : II.uses()) {
1008         if (RI.isReg()) {
1009           Register Reg = RI.getReg();
1010           if (Reg.isVirtual()) {
1011             if (hasNoDef(Reg, MRI))
1012               continue;
1013             if (!MRI->hasOneDef(Reg)) {
1014               LLVM_DEBUG(this->getEntry()->getParent()->dump());
1015               LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << "\n");
1016             }
1017 
1018             if (MRI->def_begin(Reg) == MRI->def_end()) {
1019               LLVM_DEBUG(dbgs() << "Register "
1020                                 << printReg(Reg, MRI->getTargetRegisterInfo())
1021                                 << " has NO defs\n");
1022             } else if (!MRI->hasOneDef(Reg)) {
1023               LLVM_DEBUG(dbgs() << "Register "
1024                                 << printReg(Reg, MRI->getTargetRegisterInfo())
1025                                 << " has multiple defs\n");
1026             }
1027 
1028             assert(MRI->hasOneDef(Reg) && "Register has multiple definitions");
1029             MachineOperand *Def = &(*(MRI->def_begin(Reg)));
1030             MachineOperand *UseOperand = &(RI);
1031             bool UseIsOutsideDefMBB = Def->getParent()->getParent() != MBB;
1032             if (UseIsOutsideDefMBB && UseOperand->isKill()) {
1033               LLVM_DEBUG(dbgs() << "Removing kill flag on register: "
1034                                 << printReg(Reg, TRI) << "\n");
1035               UseOperand->setIsKill(false);
1036             }
1037           }
1038         }
1039       }
1040     }
1041   }
1042 }
1043 
1044 void LinearizedRegion::initLiveOut(RegionMRT *Region,
1045                                    const MachineRegisterInfo *MRI,
1046                                    const TargetRegisterInfo *TRI,
1047                                    PHILinearize &PHIInfo) {
1048   storeLiveOuts(Region, MRI, TRI, PHIInfo);
1049 }
1050 
1051 LinearizedRegion::LinearizedRegion(MachineBasicBlock *MBB,
1052                                    const MachineRegisterInfo *MRI,
1053                                    const TargetRegisterInfo *TRI,
1054                                    PHILinearize &PHIInfo) {
1055   setEntry(MBB);
1056   setExit(MBB);
1057   storeLiveOuts(MBB, MRI, TRI, PHIInfo);
1058   MBBs.insert(MBB);
1059   Parent = nullptr;
1060 }
1061 
1062 LinearizedRegion::LinearizedRegion() {
1063   setEntry(nullptr);
1064   setExit(nullptr);
1065   Parent = nullptr;
1066 }
1067 
1068 namespace {
1069 
1070 class AMDGPUMachineCFGStructurizer : public MachineFunctionPass {
1071 private:
1072   const MachineRegionInfo *Regions;
1073   const SIInstrInfo *TII;
1074   const TargetRegisterInfo *TRI;
1075   MachineRegisterInfo *MRI;
1076   unsigned BBSelectRegister;
1077   PHILinearize PHIInfo;
1078   DenseMap<MachineBasicBlock *, MachineBasicBlock *> FallthroughMap;
1079   RegionMRT *RMRT;
1080 
1081   void getPHIRegionIndices(RegionMRT *Region, MachineInstr &PHI,
1082                            SmallVector<unsigned, 2> &RegionIndices);
1083   void getPHIRegionIndices(LinearizedRegion *Region, MachineInstr &PHI,
1084                            SmallVector<unsigned, 2> &RegionIndices);
1085   void getPHINonRegionIndices(LinearizedRegion *Region, MachineInstr &PHI,
1086                               SmallVector<unsigned, 2> &PHINonRegionIndices);
1087 
1088   void storePHILinearizationInfoDest(
1089       unsigned LDestReg, MachineInstr &PHI,
1090       SmallVector<unsigned, 2> *RegionIndices = nullptr);
1091 
1092   unsigned storePHILinearizationInfo(MachineInstr &PHI,
1093                                      SmallVector<unsigned, 2> *RegionIndices);
1094 
1095   void extractKilledPHIs(MachineBasicBlock *MBB);
1096 
1097   bool shrinkPHI(MachineInstr &PHI, SmallVector<unsigned, 2> &PHIIndices,
1098                  unsigned *ReplaceReg);
1099 
1100   bool shrinkPHI(MachineInstr &PHI, unsigned CombinedSourceReg,
1101                  MachineBasicBlock *SourceMBB,
1102                  SmallVector<unsigned, 2> &PHIIndices, unsigned *ReplaceReg);
1103 
1104   void replacePHI(MachineInstr &PHI, unsigned CombinedSourceReg,
1105                   MachineBasicBlock *LastMerge,
1106                   SmallVector<unsigned, 2> &PHIRegionIndices);
1107   void replaceEntryPHI(MachineInstr &PHI, unsigned CombinedSourceReg,
1108                        MachineBasicBlock *IfMBB,
1109                        SmallVector<unsigned, 2> &PHIRegionIndices);
1110   void replaceLiveOutRegs(MachineInstr &PHI,
1111                           SmallVector<unsigned, 2> &PHIRegionIndices,
1112                           unsigned CombinedSourceReg,
1113                           LinearizedRegion *LRegion);
1114   void rewriteRegionExitPHI(RegionMRT *Region, MachineBasicBlock *LastMerge,
1115                             MachineInstr &PHI, LinearizedRegion *LRegion);
1116 
1117   void rewriteRegionExitPHIs(RegionMRT *Region, MachineBasicBlock *LastMerge,
1118                              LinearizedRegion *LRegion);
1119   void rewriteRegionEntryPHI(LinearizedRegion *Region, MachineBasicBlock *IfMBB,
1120                              MachineInstr &PHI);
1121   void rewriteRegionEntryPHIs(LinearizedRegion *Region,
1122                               MachineBasicBlock *IfMBB);
1123 
1124   bool regionIsSimpleIf(RegionMRT *Region);
1125 
1126   void transformSimpleIfRegion(RegionMRT *Region);
1127 
1128   void eliminateDeadBranchOperands(MachineBasicBlock::instr_iterator &II);
1129 
1130   void insertUnconditionalBranch(MachineBasicBlock *MBB,
1131                                  MachineBasicBlock *Dest,
1132                                  const DebugLoc &DL = DebugLoc());
1133 
1134   MachineBasicBlock *createLinearizedExitBlock(RegionMRT *Region);
1135 
1136   void insertMergePHI(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB,
1137                       MachineBasicBlock *MergeBB, unsigned DestRegister,
1138                       unsigned IfSourceRegister, unsigned CodeSourceRegister,
1139                       bool IsUndefIfSource = false);
1140 
1141   MachineBasicBlock *createIfBlock(MachineBasicBlock *MergeBB,
1142                                    MachineBasicBlock *CodeBBStart,
1143                                    MachineBasicBlock *CodeBBEnd,
1144                                    MachineBasicBlock *SelectBB, unsigned IfReg,
1145                                    bool InheritPreds);
1146 
1147   void prunePHIInfo(MachineBasicBlock *MBB);
1148   void createEntryPHI(LinearizedRegion *CurrentRegion, unsigned DestReg);
1149 
1150   void createEntryPHIs(LinearizedRegion *CurrentRegion);
1151   void resolvePHIInfos(MachineBasicBlock *FunctionEntry);
1152 
1153   void replaceRegisterWith(unsigned Register, class Register NewRegister);
1154 
1155   MachineBasicBlock *createIfRegion(MachineBasicBlock *MergeBB,
1156                                     MachineBasicBlock *CodeBB,
1157                                     LinearizedRegion *LRegion,
1158                                     unsigned BBSelectRegIn,
1159                                     unsigned BBSelectRegOut);
1160 
1161   MachineBasicBlock *
1162   createIfRegion(MachineBasicBlock *MergeMBB, LinearizedRegion *InnerRegion,
1163                  LinearizedRegion *CurrentRegion, MachineBasicBlock *SelectBB,
1164                  unsigned BBSelectRegIn, unsigned BBSelectRegOut);
1165   void ensureCondIsNotKilled(SmallVector<MachineOperand, 1> Cond);
1166 
1167   void rewriteCodeBBTerminator(MachineBasicBlock *CodeBB,
1168                                MachineBasicBlock *MergeBB,
1169                                unsigned BBSelectReg);
1170 
1171   MachineInstr *getDefInstr(unsigned Reg);
1172   void insertChainedPHI(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB,
1173                         MachineBasicBlock *MergeBB,
1174                         LinearizedRegion *InnerRegion, unsigned DestReg,
1175                         unsigned SourceReg);
1176   bool containsDef(MachineBasicBlock *MBB, LinearizedRegion *InnerRegion,
1177                    unsigned Register);
1178   void rewriteLiveOutRegs(MachineBasicBlock *IfBB, MachineBasicBlock *CodeBB,
1179                           MachineBasicBlock *MergeBB,
1180                           LinearizedRegion *InnerRegion,
1181                           LinearizedRegion *LRegion);
1182 
1183   void splitLoopPHI(MachineInstr &PHI, MachineBasicBlock *Entry,
1184                     MachineBasicBlock *EntrySucc, LinearizedRegion *LRegion);
1185   void splitLoopPHIs(MachineBasicBlock *Entry, MachineBasicBlock *EntrySucc,
1186                      LinearizedRegion *LRegion);
1187 
1188   MachineBasicBlock *splitExit(LinearizedRegion *LRegion);
1189 
1190   MachineBasicBlock *splitEntry(LinearizedRegion *LRegion);
1191 
1192   LinearizedRegion *initLinearizedRegion(RegionMRT *Region);
1193 
1194   bool structurizeComplexRegion(RegionMRT *Region);
1195 
1196   bool structurizeRegion(RegionMRT *Region);
1197 
1198   bool structurizeRegions(RegionMRT *Region, bool isTopRegion);
1199 
1200 public:
1201   static char ID;
1202 
1203   AMDGPUMachineCFGStructurizer() : MachineFunctionPass(ID) {
1204     initializeAMDGPUMachineCFGStructurizerPass(*PassRegistry::getPassRegistry());
1205   }
1206 
1207   void getAnalysisUsage(AnalysisUsage &AU) const override {
1208     AU.addRequired<MachineRegionInfoPass>();
1209     MachineFunctionPass::getAnalysisUsage(AU);
1210   }
1211 
1212   void initFallthroughMap(MachineFunction &MF);
1213 
1214   void createLinearizedRegion(RegionMRT *Region, unsigned SelectOut);
1215 
1216   unsigned initializeSelectRegisters(MRT *MRT, unsigned ExistingExitReg,
1217                                      MachineRegisterInfo *MRI,
1218                                      const SIInstrInfo *TII);
1219 
1220   void setRegionMRT(RegionMRT *RegionTree) { RMRT = RegionTree; }
1221 
1222   RegionMRT *getRegionMRT() { return RMRT; }
1223 
1224   bool runOnMachineFunction(MachineFunction &MF) override;
1225 };
1226 
1227 } // end anonymous namespace
1228 
1229 char AMDGPUMachineCFGStructurizer::ID = 0;
1230 
1231 bool AMDGPUMachineCFGStructurizer::regionIsSimpleIf(RegionMRT *Region) {
1232   MachineBasicBlock *Entry = Region->getEntry();
1233   MachineBasicBlock *Succ = Region->getSucc();
1234   bool FoundBypass = false;
1235   bool FoundIf = false;
1236 
1237   if (Entry->succ_size() != 2) {
1238     return false;
1239   }
1240 
1241   for (MachineBasicBlock::const_succ_iterator SI = Entry->succ_begin(),
1242                                               E = Entry->succ_end();
1243        SI != E; ++SI) {
1244     MachineBasicBlock *Current = *SI;
1245 
1246     if (Current == Succ) {
1247       FoundBypass = true;
1248     } else if ((Current->succ_size() == 1) &&
1249                *(Current->succ_begin()) == Succ) {
1250       FoundIf = true;
1251     }
1252   }
1253 
1254   return FoundIf && FoundBypass;
1255 }
1256 
1257 void AMDGPUMachineCFGStructurizer::transformSimpleIfRegion(RegionMRT *Region) {
1258   MachineBasicBlock *Entry = Region->getEntry();
1259   MachineBasicBlock *Exit = Region->getExit();
1260   TII->convertNonUniformIfRegion(Entry, Exit);
1261 }
1262 
1263 static void fixMBBTerminator(MachineBasicBlock *MBB) {
1264   if (MBB->succ_size() == 1) {
1265     auto *Succ = *(MBB->succ_begin());
1266     for (auto &TI : MBB->terminators()) {
1267       for (auto &UI : TI.uses()) {
1268         if (UI.isMBB() && UI.getMBB() != Succ) {
1269           UI.setMBB(Succ);
1270         }
1271       }
1272     }
1273   }
1274 }
1275 
1276 static void fixRegionTerminator(RegionMRT *Region) {
1277   MachineBasicBlock *InternalSucc = nullptr;
1278   MachineBasicBlock *ExternalSucc = nullptr;
1279   LinearizedRegion *LRegion = Region->getLinearizedRegion();
1280   auto Exit = LRegion->getExit();
1281 
1282   SmallPtrSet<MachineBasicBlock *, 2> Successors;
1283   for (MachineBasicBlock::const_succ_iterator SI = Exit->succ_begin(),
1284                                               SE = Exit->succ_end();
1285        SI != SE; ++SI) {
1286     MachineBasicBlock *Succ = *SI;
1287     if (LRegion->contains(Succ)) {
1288       // Do not allow re-assign
1289       assert(InternalSucc == nullptr);
1290       InternalSucc = Succ;
1291     } else {
1292       // Do not allow re-assign
1293       assert(ExternalSucc == nullptr);
1294       ExternalSucc = Succ;
1295     }
1296   }
1297 
1298   for (auto &TI : Exit->terminators()) {
1299     for (auto &UI : TI.uses()) {
1300       if (UI.isMBB()) {
1301         auto Target = UI.getMBB();
1302         if (Target != InternalSucc && Target != ExternalSucc) {
1303           UI.setMBB(ExternalSucc);
1304         }
1305       }
1306     }
1307   }
1308 }
1309 
1310 // If a region region is just a sequence of regions (and the exit
1311 // block in the case of the top level region), we can simply skip
1312 // linearizing it, because it is already linear
1313 bool regionIsSequence(RegionMRT *Region) {
1314   auto Children = Region->getChildren();
1315   for (auto CI : *Children) {
1316     if (!CI->isRegion()) {
1317       if (CI->getMBBMRT()->getMBB()->succ_size() > 1) {
1318         return false;
1319       }
1320     }
1321   }
1322   return true;
1323 }
1324 
1325 void fixupRegionExits(RegionMRT *Region) {
1326   auto Children = Region->getChildren();
1327   for (auto CI : *Children) {
1328     if (!CI->isRegion()) {
1329       fixMBBTerminator(CI->getMBBMRT()->getMBB());
1330     } else {
1331       fixRegionTerminator(CI->getRegionMRT());
1332     }
1333   }
1334 }
1335 
1336 void AMDGPUMachineCFGStructurizer::getPHIRegionIndices(
1337     RegionMRT *Region, MachineInstr &PHI,
1338     SmallVector<unsigned, 2> &PHIRegionIndices) {
1339   unsigned NumInputs = getPHINumInputs(PHI);
1340   for (unsigned i = 0; i < NumInputs; ++i) {
1341     MachineBasicBlock *Pred = getPHIPred(PHI, i);
1342     if (Region->contains(Pred)) {
1343       PHIRegionIndices.push_back(i);
1344     }
1345   }
1346 }
1347 
1348 void AMDGPUMachineCFGStructurizer::getPHIRegionIndices(
1349     LinearizedRegion *Region, MachineInstr &PHI,
1350     SmallVector<unsigned, 2> &PHIRegionIndices) {
1351   unsigned NumInputs = getPHINumInputs(PHI);
1352   for (unsigned i = 0; i < NumInputs; ++i) {
1353     MachineBasicBlock *Pred = getPHIPred(PHI, i);
1354     if (Region->contains(Pred)) {
1355       PHIRegionIndices.push_back(i);
1356     }
1357   }
1358 }
1359 
1360 void AMDGPUMachineCFGStructurizer::getPHINonRegionIndices(
1361     LinearizedRegion *Region, MachineInstr &PHI,
1362     SmallVector<unsigned, 2> &PHINonRegionIndices) {
1363   unsigned NumInputs = getPHINumInputs(PHI);
1364   for (unsigned i = 0; i < NumInputs; ++i) {
1365     MachineBasicBlock *Pred = getPHIPred(PHI, i);
1366     if (!Region->contains(Pred)) {
1367       PHINonRegionIndices.push_back(i);
1368     }
1369   }
1370 }
1371 
1372 void AMDGPUMachineCFGStructurizer::storePHILinearizationInfoDest(
1373     unsigned LDestReg, MachineInstr &PHI,
1374     SmallVector<unsigned, 2> *RegionIndices) {
1375   if (RegionIndices) {
1376     for (auto i : *RegionIndices) {
1377       PHIInfo.addSource(LDestReg, getPHISourceReg(PHI, i), getPHIPred(PHI, i));
1378     }
1379   } else {
1380     unsigned NumInputs = getPHINumInputs(PHI);
1381     for (unsigned i = 0; i < NumInputs; ++i) {
1382       PHIInfo.addSource(LDestReg, getPHISourceReg(PHI, i), getPHIPred(PHI, i));
1383     }
1384   }
1385 }
1386 
1387 unsigned AMDGPUMachineCFGStructurizer::storePHILinearizationInfo(
1388     MachineInstr &PHI, SmallVector<unsigned, 2> *RegionIndices) {
1389   unsigned DestReg = getPHIDestReg(PHI);
1390   Register LinearizeDestReg =
1391       MRI->createVirtualRegister(MRI->getRegClass(DestReg));
1392   PHIInfo.addDest(LinearizeDestReg, PHI.getDebugLoc());
1393   storePHILinearizationInfoDest(LinearizeDestReg, PHI, RegionIndices);
1394   return LinearizeDestReg;
1395 }
1396 
1397 void AMDGPUMachineCFGStructurizer::extractKilledPHIs(MachineBasicBlock *MBB) {
1398   // We need to create a new chain for the killed phi, but there is no
1399   // need to do the renaming outside or inside the block.
1400   SmallPtrSet<MachineInstr *, 2> PHIs;
1401   for (MachineBasicBlock::instr_iterator I = MBB->instr_begin(),
1402                                          E = MBB->instr_end();
1403        I != E; ++I) {
1404     MachineInstr &Instr = *I;
1405     if (Instr.isPHI()) {
1406       unsigned PHIDestReg = getPHIDestReg(Instr);
1407       LLVM_DEBUG(dbgs() << "Extractking killed phi:\n");
1408       LLVM_DEBUG(Instr.dump());
1409       PHIs.insert(&Instr);
1410       PHIInfo.addDest(PHIDestReg, Instr.getDebugLoc());
1411       storePHILinearizationInfoDest(PHIDestReg, Instr);
1412     }
1413   }
1414 
1415   for (auto PI : PHIs) {
1416     PI->eraseFromParent();
1417   }
1418 }
1419 
1420 static bool isPHIRegionIndex(SmallVector<unsigned, 2> PHIRegionIndices,
1421                              unsigned Index) {
1422   for (auto i : PHIRegionIndices) {
1423     if (i == Index)
1424       return true;
1425   }
1426   return false;
1427 }
1428 
1429 bool AMDGPUMachineCFGStructurizer::shrinkPHI(MachineInstr &PHI,
1430                                        SmallVector<unsigned, 2> &PHIIndices,
1431                                        unsigned *ReplaceReg) {
1432   return shrinkPHI(PHI, 0, nullptr, PHIIndices, ReplaceReg);
1433 }
1434 
1435 bool AMDGPUMachineCFGStructurizer::shrinkPHI(MachineInstr &PHI,
1436                                        unsigned CombinedSourceReg,
1437                                        MachineBasicBlock *SourceMBB,
1438                                        SmallVector<unsigned, 2> &PHIIndices,
1439                                        unsigned *ReplaceReg) {
1440   LLVM_DEBUG(dbgs() << "Shrink PHI: ");
1441   LLVM_DEBUG(PHI.dump());
1442   LLVM_DEBUG(dbgs() << " to " << printReg(getPHIDestReg(PHI), TRI)
1443                     << " = PHI(");
1444 
1445   bool Replaced = false;
1446   unsigned NumInputs = getPHINumInputs(PHI);
1447   int SingleExternalEntryIndex = -1;
1448   for (unsigned i = 0; i < NumInputs; ++i) {
1449     if (!isPHIRegionIndex(PHIIndices, i)) {
1450       if (SingleExternalEntryIndex == -1) {
1451         // Single entry
1452         SingleExternalEntryIndex = i;
1453       } else {
1454         // Multiple entries
1455         SingleExternalEntryIndex = -2;
1456       }
1457     }
1458   }
1459 
1460   if (SingleExternalEntryIndex > -1) {
1461     *ReplaceReg = getPHISourceReg(PHI, SingleExternalEntryIndex);
1462     // We should not rewrite the code, we should only pick up the single value
1463     // that represents the shrunk PHI.
1464     Replaced = true;
1465   } else {
1466     MachineBasicBlock *MBB = PHI.getParent();
1467     MachineInstrBuilder MIB =
1468         BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI),
1469                 getPHIDestReg(PHI));
1470     if (SourceMBB) {
1471       MIB.addReg(CombinedSourceReg);
1472       MIB.addMBB(SourceMBB);
1473       LLVM_DEBUG(dbgs() << printReg(CombinedSourceReg, TRI) << ", "
1474                         << printMBBReference(*SourceMBB));
1475     }
1476 
1477     for (unsigned i = 0; i < NumInputs; ++i) {
1478       if (isPHIRegionIndex(PHIIndices, i)) {
1479         continue;
1480       }
1481       unsigned SourceReg = getPHISourceReg(PHI, i);
1482       MachineBasicBlock *SourcePred = getPHIPred(PHI, i);
1483       MIB.addReg(SourceReg);
1484       MIB.addMBB(SourcePred);
1485       LLVM_DEBUG(dbgs() << printReg(SourceReg, TRI) << ", "
1486                         << printMBBReference(*SourcePred));
1487     }
1488     LLVM_DEBUG(dbgs() << ")\n");
1489   }
1490   PHI.eraseFromParent();
1491   return Replaced;
1492 }
1493 
1494 void AMDGPUMachineCFGStructurizer::replacePHI(
1495     MachineInstr &PHI, unsigned CombinedSourceReg, MachineBasicBlock *LastMerge,
1496     SmallVector<unsigned, 2> &PHIRegionIndices) {
1497   LLVM_DEBUG(dbgs() << "Replace PHI: ");
1498   LLVM_DEBUG(PHI.dump());
1499   LLVM_DEBUG(dbgs() << " with " << printReg(getPHIDestReg(PHI), TRI)
1500                     << " = PHI(");
1501 
1502   bool HasExternalEdge = false;
1503   unsigned NumInputs = getPHINumInputs(PHI);
1504   for (unsigned i = 0; i < NumInputs; ++i) {
1505     if (!isPHIRegionIndex(PHIRegionIndices, i)) {
1506       HasExternalEdge = true;
1507     }
1508   }
1509 
1510   if (HasExternalEdge) {
1511     MachineBasicBlock *MBB = PHI.getParent();
1512     MachineInstrBuilder MIB =
1513         BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI),
1514                 getPHIDestReg(PHI));
1515     MIB.addReg(CombinedSourceReg);
1516     MIB.addMBB(LastMerge);
1517     LLVM_DEBUG(dbgs() << printReg(CombinedSourceReg, TRI) << ", "
1518                       << printMBBReference(*LastMerge));
1519     for (unsigned i = 0; i < NumInputs; ++i) {
1520       if (isPHIRegionIndex(PHIRegionIndices, i)) {
1521         continue;
1522       }
1523       unsigned SourceReg = getPHISourceReg(PHI, i);
1524       MachineBasicBlock *SourcePred = getPHIPred(PHI, i);
1525       MIB.addReg(SourceReg);
1526       MIB.addMBB(SourcePred);
1527       LLVM_DEBUG(dbgs() << printReg(SourceReg, TRI) << ", "
1528                         << printMBBReference(*SourcePred));
1529     }
1530     LLVM_DEBUG(dbgs() << ")\n");
1531   } else {
1532     replaceRegisterWith(getPHIDestReg(PHI), CombinedSourceReg);
1533   }
1534   PHI.eraseFromParent();
1535 }
1536 
1537 void AMDGPUMachineCFGStructurizer::replaceEntryPHI(
1538     MachineInstr &PHI, unsigned CombinedSourceReg, MachineBasicBlock *IfMBB,
1539     SmallVector<unsigned, 2> &PHIRegionIndices) {
1540   LLVM_DEBUG(dbgs() << "Replace entry PHI: ");
1541   LLVM_DEBUG(PHI.dump());
1542   LLVM_DEBUG(dbgs() << " with ");
1543 
1544   unsigned NumInputs = getPHINumInputs(PHI);
1545   unsigned NumNonRegionInputs = NumInputs;
1546   for (unsigned i = 0; i < NumInputs; ++i) {
1547     if (isPHIRegionIndex(PHIRegionIndices, i)) {
1548       NumNonRegionInputs--;
1549     }
1550   }
1551 
1552   if (NumNonRegionInputs == 0) {
1553     auto DestReg = getPHIDestReg(PHI);
1554     replaceRegisterWith(DestReg, CombinedSourceReg);
1555     LLVM_DEBUG(dbgs() << " register " << printReg(CombinedSourceReg, TRI)
1556                       << "\n");
1557     PHI.eraseFromParent();
1558   } else {
1559     LLVM_DEBUG(dbgs() << printReg(getPHIDestReg(PHI), TRI) << " = PHI(");
1560     MachineBasicBlock *MBB = PHI.getParent();
1561     MachineInstrBuilder MIB =
1562         BuildMI(*MBB, PHI, PHI.getDebugLoc(), TII->get(TargetOpcode::PHI),
1563                 getPHIDestReg(PHI));
1564     MIB.addReg(CombinedSourceReg);
1565     MIB.addMBB(IfMBB);
1566     LLVM_DEBUG(dbgs() << printReg(CombinedSourceReg, TRI) << ", "
1567                       << printMBBReference(*IfMBB));
1568     unsigned NumInputs = getPHINumInputs(PHI);
1569     for (unsigned i = 0; i < NumInputs; ++i) {
1570       if (isPHIRegionIndex(PHIRegionIndices, i)) {
1571         continue;
1572       }
1573       unsigned SourceReg = getPHISourceReg(PHI, i);
1574       MachineBasicBlock *SourcePred = getPHIPred(PHI, i);
1575       MIB.addReg(SourceReg);
1576       MIB.addMBB(SourcePred);
1577       LLVM_DEBUG(dbgs() << printReg(SourceReg, TRI) << ", "
1578                         << printMBBReference(*SourcePred));
1579     }
1580     LLVM_DEBUG(dbgs() << ")\n");
1581     PHI.eraseFromParent();
1582   }
1583 }
1584 
1585 void AMDGPUMachineCFGStructurizer::replaceLiveOutRegs(
1586     MachineInstr &PHI, SmallVector<unsigned, 2> &PHIRegionIndices,
1587     unsigned CombinedSourceReg, LinearizedRegion *LRegion) {
1588   bool WasLiveOut = false;
1589   for (auto PII : PHIRegionIndices) {
1590     unsigned Reg = getPHISourceReg(PHI, PII);
1591     if (LRegion->isLiveOut(Reg)) {
1592       bool IsDead = true;
1593 
1594       // Check if register is live out of the basic block
1595       MachineBasicBlock *DefMBB = getDefInstr(Reg)->getParent();
1596       for (auto UI = MRI->use_begin(Reg), E = MRI->use_end(); UI != E; ++UI) {
1597         if ((*UI).getParent()->getParent() != DefMBB) {
1598           IsDead = false;
1599         }
1600       }
1601 
1602       LLVM_DEBUG(dbgs() << "Register " << printReg(Reg, TRI) << " is "
1603                         << (IsDead ? "dead" : "alive")
1604                         << " after PHI replace\n");
1605       if (IsDead) {
1606         LRegion->removeLiveOut(Reg);
1607       }
1608       WasLiveOut = true;
1609     }
1610   }
1611 
1612   if (WasLiveOut)
1613     LRegion->addLiveOut(CombinedSourceReg);
1614 }
1615 
1616 void AMDGPUMachineCFGStructurizer::rewriteRegionExitPHI(RegionMRT *Region,
1617                                                   MachineBasicBlock *LastMerge,
1618                                                   MachineInstr &PHI,
1619                                                   LinearizedRegion *LRegion) {
1620   SmallVector<unsigned, 2> PHIRegionIndices;
1621   getPHIRegionIndices(Region, PHI, PHIRegionIndices);
1622   unsigned LinearizedSourceReg =
1623       storePHILinearizationInfo(PHI, &PHIRegionIndices);
1624 
1625   replacePHI(PHI, LinearizedSourceReg, LastMerge, PHIRegionIndices);
1626   replaceLiveOutRegs(PHI, PHIRegionIndices, LinearizedSourceReg, LRegion);
1627 }
1628 
1629 void AMDGPUMachineCFGStructurizer::rewriteRegionEntryPHI(LinearizedRegion *Region,
1630                                                    MachineBasicBlock *IfMBB,
1631                                                    MachineInstr &PHI) {
1632   SmallVector<unsigned, 2> PHINonRegionIndices;
1633   getPHINonRegionIndices(Region, PHI, PHINonRegionIndices);
1634   unsigned LinearizedSourceReg =
1635       storePHILinearizationInfo(PHI, &PHINonRegionIndices);
1636   replaceEntryPHI(PHI, LinearizedSourceReg, IfMBB, PHINonRegionIndices);
1637 }
1638 
1639 static void collectPHIs(MachineBasicBlock *MBB,
1640                         SmallVector<MachineInstr *, 2> &PHIs) {
1641   for (auto &BBI : *MBB) {
1642     if (BBI.isPHI()) {
1643       PHIs.push_back(&BBI);
1644     }
1645   }
1646 }
1647 
1648 void AMDGPUMachineCFGStructurizer::rewriteRegionExitPHIs(RegionMRT *Region,
1649                                                    MachineBasicBlock *LastMerge,
1650                                                    LinearizedRegion *LRegion) {
1651   SmallVector<MachineInstr *, 2> PHIs;
1652   auto Exit = Region->getSucc();
1653   if (Exit == nullptr)
1654     return;
1655 
1656   collectPHIs(Exit, PHIs);
1657 
1658   for (auto PHII : PHIs) {
1659     rewriteRegionExitPHI(Region, LastMerge, *PHII, LRegion);
1660   }
1661 }
1662 
1663 void AMDGPUMachineCFGStructurizer::rewriteRegionEntryPHIs(LinearizedRegion *Region,
1664                                                     MachineBasicBlock *IfMBB) {
1665   SmallVector<MachineInstr *, 2> PHIs;
1666   auto Entry = Region->getEntry();
1667 
1668   collectPHIs(Entry, PHIs);
1669 
1670   for (auto PHII : PHIs) {
1671     rewriteRegionEntryPHI(Region, IfMBB, *PHII);
1672   }
1673 }
1674 
1675 void AMDGPUMachineCFGStructurizer::insertUnconditionalBranch(MachineBasicBlock *MBB,
1676                                                        MachineBasicBlock *Dest,
1677                                                        const DebugLoc &DL) {
1678   LLVM_DEBUG(dbgs() << "Inserting unconditional branch: " << MBB->getNumber()
1679                     << " -> " << Dest->getNumber() << "\n");
1680   MachineBasicBlock::instr_iterator Terminator = MBB->getFirstInstrTerminator();
1681   bool HasTerminator = Terminator != MBB->instr_end();
1682   if (HasTerminator) {
1683     TII->ReplaceTailWithBranchTo(Terminator, Dest);
1684   }
1685   if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(Dest)) {
1686     TII->insertUnconditionalBranch(*MBB, Dest, DL);
1687   }
1688 }
1689 
1690 static MachineBasicBlock *getSingleExitNode(MachineFunction &MF) {
1691   MachineBasicBlock *result = nullptr;
1692   for (auto &MFI : MF) {
1693     if (MFI.succ_size() == 0) {
1694       if (result == nullptr) {
1695         result = &MFI;
1696       } else {
1697         return nullptr;
1698       }
1699     }
1700   }
1701 
1702   return result;
1703 }
1704 
1705 static bool hasOneExitNode(MachineFunction &MF) {
1706   return getSingleExitNode(MF) != nullptr;
1707 }
1708 
1709 MachineBasicBlock *
1710 AMDGPUMachineCFGStructurizer::createLinearizedExitBlock(RegionMRT *Region) {
1711   auto Exit = Region->getSucc();
1712 
1713   // If the exit is the end of the function, we just use the existing
1714   MachineFunction *MF = Region->getEntry()->getParent();
1715   if (Exit == nullptr && hasOneExitNode(*MF)) {
1716     return &(*(--(Region->getEntry()->getParent()->end())));
1717   }
1718 
1719   MachineBasicBlock *LastMerge = MF->CreateMachineBasicBlock();
1720   if (Exit == nullptr) {
1721     MachineFunction::iterator ExitIter = MF->end();
1722     MF->insert(ExitIter, LastMerge);
1723   } else {
1724     MachineFunction::iterator ExitIter = Exit->getIterator();
1725     MF->insert(ExitIter, LastMerge);
1726     LastMerge->addSuccessor(Exit);
1727     insertUnconditionalBranch(LastMerge, Exit);
1728     LLVM_DEBUG(dbgs() << "Created exit block: " << LastMerge->getNumber()
1729                       << "\n");
1730   }
1731   return LastMerge;
1732 }
1733 
1734 void AMDGPUMachineCFGStructurizer::insertMergePHI(MachineBasicBlock *IfBB,
1735                                             MachineBasicBlock *CodeBB,
1736                                             MachineBasicBlock *MergeBB,
1737                                             unsigned DestRegister,
1738                                             unsigned IfSourceRegister,
1739                                             unsigned CodeSourceRegister,
1740                                             bool IsUndefIfSource) {
1741   // If this is the function exit block, we don't need a phi.
1742   if (MergeBB->succ_begin() == MergeBB->succ_end()) {
1743     return;
1744   }
1745   LLVM_DEBUG(dbgs() << "Merge PHI (" << printMBBReference(*MergeBB)
1746                     << "): " << printReg(DestRegister, TRI) << " = PHI("
1747                     << printReg(IfSourceRegister, TRI) << ", "
1748                     << printMBBReference(*IfBB)
1749                     << printReg(CodeSourceRegister, TRI) << ", "
1750                     << printMBBReference(*CodeBB) << ")\n");
1751   const DebugLoc &DL = MergeBB->findDebugLoc(MergeBB->begin());
1752   MachineInstrBuilder MIB = BuildMI(*MergeBB, MergeBB->instr_begin(), DL,
1753                                     TII->get(TargetOpcode::PHI), DestRegister);
1754   if (IsUndefIfSource && false) {
1755     MIB.addReg(IfSourceRegister, RegState::Undef);
1756   } else {
1757     MIB.addReg(IfSourceRegister);
1758   }
1759   MIB.addMBB(IfBB);
1760   MIB.addReg(CodeSourceRegister);
1761   MIB.addMBB(CodeBB);
1762 }
1763 
1764 static void removeExternalCFGSuccessors(MachineBasicBlock *MBB) {
1765   for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
1766                                         E = MBB->succ_end();
1767        PI != E; ++PI) {
1768     if ((*PI) != MBB) {
1769       (MBB)->removeSuccessor(*PI);
1770     }
1771   }
1772 }
1773 
1774 static void removeExternalCFGEdges(MachineBasicBlock *StartMBB,
1775                                    MachineBasicBlock *EndMBB) {
1776 
1777   // We have to check against the StartMBB successor becasuse a
1778   // structurized region with a loop will have the entry block split,
1779   // and the backedge will go to the entry successor.
1780   DenseSet<std::pair<MachineBasicBlock *, MachineBasicBlock *>> Succs;
1781   unsigned SuccSize = StartMBB->succ_size();
1782   if (SuccSize > 0) {
1783     MachineBasicBlock *StartMBBSucc = *(StartMBB->succ_begin());
1784     for (MachineBasicBlock::succ_iterator PI = EndMBB->succ_begin(),
1785                                           E = EndMBB->succ_end();
1786          PI != E; ++PI) {
1787       // Either we have a back-edge to the entry block, or a back-edge to the
1788       // successor of the entry block since the block may be split.
1789       if ((*PI) != StartMBB &&
1790           !((*PI) == StartMBBSucc && StartMBB != EndMBB && SuccSize == 1)) {
1791         Succs.insert(
1792             std::pair<MachineBasicBlock *, MachineBasicBlock *>(EndMBB, *PI));
1793       }
1794     }
1795   }
1796 
1797   for (MachineBasicBlock::pred_iterator PI = StartMBB->pred_begin(),
1798                                         E = StartMBB->pred_end();
1799        PI != E; ++PI) {
1800     if ((*PI) != EndMBB) {
1801       Succs.insert(
1802           std::pair<MachineBasicBlock *, MachineBasicBlock *>(*PI, StartMBB));
1803     }
1804   }
1805 
1806   for (auto SI : Succs) {
1807     std::pair<MachineBasicBlock *, MachineBasicBlock *> Edge = SI;
1808     LLVM_DEBUG(dbgs() << "Removing edge: " << printMBBReference(*Edge.first)
1809                       << " -> " << printMBBReference(*Edge.second) << "\n");
1810     Edge.first->removeSuccessor(Edge.second);
1811   }
1812 }
1813 
1814 MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfBlock(
1815     MachineBasicBlock *MergeBB, MachineBasicBlock *CodeBBStart,
1816     MachineBasicBlock *CodeBBEnd, MachineBasicBlock *SelectBB, unsigned IfReg,
1817     bool InheritPreds) {
1818   MachineFunction *MF = MergeBB->getParent();
1819   MachineBasicBlock *IfBB = MF->CreateMachineBasicBlock();
1820 
1821   if (InheritPreds) {
1822     for (MachineBasicBlock::pred_iterator PI = CodeBBStart->pred_begin(),
1823                                           E = CodeBBStart->pred_end();
1824          PI != E; ++PI) {
1825       if ((*PI) != CodeBBEnd) {
1826         MachineBasicBlock *Pred = (*PI);
1827         Pred->addSuccessor(IfBB);
1828       }
1829     }
1830   }
1831 
1832   removeExternalCFGEdges(CodeBBStart, CodeBBEnd);
1833 
1834   auto CodeBBStartI = CodeBBStart->getIterator();
1835   auto CodeBBEndI = CodeBBEnd->getIterator();
1836   auto MergeIter = MergeBB->getIterator();
1837   MF->insert(MergeIter, IfBB);
1838   MF->splice(MergeIter, CodeBBStartI, ++CodeBBEndI);
1839   IfBB->addSuccessor(MergeBB);
1840   IfBB->addSuccessor(CodeBBStart);
1841 
1842   LLVM_DEBUG(dbgs() << "Created If block: " << IfBB->getNumber() << "\n");
1843   // Ensure that the MergeBB is a successor of the CodeEndBB.
1844   if (!CodeBBEnd->isSuccessor(MergeBB))
1845     CodeBBEnd->addSuccessor(MergeBB);
1846 
1847   LLVM_DEBUG(dbgs() << "Moved " << printMBBReference(*CodeBBStart)
1848                     << " through " << printMBBReference(*CodeBBEnd) << "\n");
1849 
1850   // If we have a single predecessor we can find a reasonable debug location
1851   MachineBasicBlock *SinglePred =
1852       CodeBBStart->pred_size() == 1 ? *(CodeBBStart->pred_begin()) : nullptr;
1853   const DebugLoc &DL = SinglePred
1854                     ? SinglePred->findDebugLoc(SinglePred->getFirstTerminator())
1855                     : DebugLoc();
1856 
1857   Register Reg =
1858       TII->insertEQ(IfBB, IfBB->begin(), DL, IfReg,
1859                     SelectBB->getNumber() /* CodeBBStart->getNumber() */);
1860   if (&(*(IfBB->getParent()->begin())) == IfBB) {
1861     TII->materializeImmediate(*IfBB, IfBB->begin(), DL, IfReg,
1862                               CodeBBStart->getNumber());
1863   }
1864   MachineOperand RegOp = MachineOperand::CreateReg(Reg, false, false, true);
1865   ArrayRef<MachineOperand> Cond(RegOp);
1866   TII->insertBranch(*IfBB, MergeBB, CodeBBStart, Cond, DL);
1867 
1868   return IfBB;
1869 }
1870 
1871 void AMDGPUMachineCFGStructurizer::ensureCondIsNotKilled(
1872     SmallVector<MachineOperand, 1> Cond) {
1873   if (Cond.size() != 1)
1874     return;
1875   if (!Cond[0].isReg())
1876     return;
1877 
1878   Register CondReg = Cond[0].getReg();
1879   for (auto UI = MRI->use_begin(CondReg), E = MRI->use_end(); UI != E; ++UI) {
1880     (*UI).setIsKill(false);
1881   }
1882 }
1883 
1884 void AMDGPUMachineCFGStructurizer::rewriteCodeBBTerminator(MachineBasicBlock *CodeBB,
1885                                                      MachineBasicBlock *MergeBB,
1886                                                      unsigned BBSelectReg) {
1887   MachineBasicBlock *TrueBB = nullptr;
1888   MachineBasicBlock *FalseBB = nullptr;
1889   SmallVector<MachineOperand, 1> Cond;
1890   MachineBasicBlock *FallthroughBB = FallthroughMap[CodeBB];
1891   TII->analyzeBranch(*CodeBB, TrueBB, FalseBB, Cond);
1892 
1893   const DebugLoc &DL = CodeBB->findDebugLoc(CodeBB->getFirstTerminator());
1894 
1895   if (FalseBB == nullptr && TrueBB == nullptr && FallthroughBB == nullptr) {
1896     // This is an exit block, hence no successors. We will assign the
1897     // bb select register to the entry block.
1898     TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL,
1899                               BBSelectReg,
1900                               CodeBB->getParent()->begin()->getNumber());
1901     insertUnconditionalBranch(CodeBB, MergeBB, DL);
1902     return;
1903   }
1904 
1905   if (FalseBB == nullptr && TrueBB == nullptr) {
1906     TrueBB = FallthroughBB;
1907   } else if (TrueBB != nullptr) {
1908     FalseBB =
1909         (FallthroughBB && (FallthroughBB != TrueBB)) ? FallthroughBB : FalseBB;
1910   }
1911 
1912   if ((TrueBB != nullptr && FalseBB == nullptr) || (TrueBB == FalseBB)) {
1913     TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL,
1914                               BBSelectReg, TrueBB->getNumber());
1915   } else {
1916     const TargetRegisterClass *RegClass = MRI->getRegClass(BBSelectReg);
1917     Register TrueBBReg = MRI->createVirtualRegister(RegClass);
1918     Register FalseBBReg = MRI->createVirtualRegister(RegClass);
1919     TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL,
1920                               TrueBBReg, TrueBB->getNumber());
1921     TII->materializeImmediate(*CodeBB, CodeBB->getFirstTerminator(), DL,
1922                               FalseBBReg, FalseBB->getNumber());
1923     ensureCondIsNotKilled(Cond);
1924     TII->insertVectorSelect(*CodeBB, CodeBB->getFirstTerminator(), DL,
1925                             BBSelectReg, Cond, TrueBBReg, FalseBBReg);
1926   }
1927 
1928   insertUnconditionalBranch(CodeBB, MergeBB, DL);
1929 }
1930 
1931 MachineInstr *AMDGPUMachineCFGStructurizer::getDefInstr(unsigned Reg) {
1932   if (MRI->def_begin(Reg) == MRI->def_end()) {
1933     LLVM_DEBUG(dbgs() << "Register "
1934                       << printReg(Reg, MRI->getTargetRegisterInfo())
1935                       << " has NO defs\n");
1936   } else if (!MRI->hasOneDef(Reg)) {
1937     LLVM_DEBUG(dbgs() << "Register "
1938                       << printReg(Reg, MRI->getTargetRegisterInfo())
1939                       << " has multiple defs\n");
1940     LLVM_DEBUG(dbgs() << "DEFS BEGIN:\n");
1941     for (auto DI = MRI->def_begin(Reg), DE = MRI->def_end(); DI != DE; ++DI) {
1942       LLVM_DEBUG(DI->getParent()->dump());
1943     }
1944     LLVM_DEBUG(dbgs() << "DEFS END\n");
1945   }
1946 
1947   assert(MRI->hasOneDef(Reg) && "Register has multiple definitions");
1948   return (*(MRI->def_begin(Reg))).getParent();
1949 }
1950 
1951 void AMDGPUMachineCFGStructurizer::insertChainedPHI(MachineBasicBlock *IfBB,
1952                                               MachineBasicBlock *CodeBB,
1953                                               MachineBasicBlock *MergeBB,
1954                                               LinearizedRegion *InnerRegion,
1955                                               unsigned DestReg,
1956                                               unsigned SourceReg) {
1957   // In this function we know we are part of a chain already, so we need
1958   // to add the registers to the existing chain, and rename the register
1959   // inside the region.
1960   bool IsSingleBB = InnerRegion->getEntry() == InnerRegion->getExit();
1961   MachineInstr *DefInstr = getDefInstr(SourceReg);
1962   if (DefInstr->isPHI() && DefInstr->getParent() == CodeBB && IsSingleBB) {
1963     // Handle the case where the def is a PHI-def inside a basic
1964     // block, then we only need to do renaming. Special care needs to
1965     // be taken if the PHI-def is part of an existing chain, or if a
1966     // new one needs to be created.
1967     InnerRegion->replaceRegisterInsideRegion(SourceReg, DestReg, true, MRI);
1968 
1969     // We collect all PHI Information, and if we are at the region entry,
1970     // all PHIs will be removed, and then re-introduced if needed.
1971     storePHILinearizationInfoDest(DestReg, *DefInstr);
1972     // We have picked up all the information we need now and can remove
1973     // the PHI
1974     PHIInfo.removeSource(DestReg, SourceReg, CodeBB);
1975     DefInstr->eraseFromParent();
1976   } else {
1977     // If this is not a phi-def, or it is a phi-def but from a linearized region
1978     if (IsSingleBB && DefInstr->getParent() == InnerRegion->getEntry()) {
1979       // If this is a single BB and the definition is in this block we
1980       // need to replace any uses outside the region.
1981       InnerRegion->replaceRegisterOutsideRegion(SourceReg, DestReg, false, MRI);
1982     }
1983     const TargetRegisterClass *RegClass = MRI->getRegClass(DestReg);
1984     Register NextDestReg = MRI->createVirtualRegister(RegClass);
1985     bool IsLastDef = PHIInfo.getNumSources(DestReg) == 1;
1986     LLVM_DEBUG(dbgs() << "Insert Chained PHI\n");
1987     insertMergePHI(IfBB, InnerRegion->getExit(), MergeBB, DestReg, NextDestReg,
1988                    SourceReg, IsLastDef);
1989 
1990     PHIInfo.removeSource(DestReg, SourceReg, CodeBB);
1991     if (IsLastDef) {
1992       const DebugLoc &DL = IfBB->findDebugLoc(IfBB->getFirstTerminator());
1993       TII->materializeImmediate(*IfBB, IfBB->getFirstTerminator(), DL,
1994                                 NextDestReg, 0);
1995       PHIInfo.deleteDef(DestReg);
1996     } else {
1997       PHIInfo.replaceDef(DestReg, NextDestReg);
1998     }
1999   }
2000 }
2001 
2002 bool AMDGPUMachineCFGStructurizer::containsDef(MachineBasicBlock *MBB,
2003                                          LinearizedRegion *InnerRegion,
2004                                          unsigned Register) {
2005   return getDefInstr(Register)->getParent() == MBB ||
2006          InnerRegion->contains(getDefInstr(Register)->getParent());
2007 }
2008 
2009 void AMDGPUMachineCFGStructurizer::rewriteLiveOutRegs(MachineBasicBlock *IfBB,
2010                                                 MachineBasicBlock *CodeBB,
2011                                                 MachineBasicBlock *MergeBB,
2012                                                 LinearizedRegion *InnerRegion,
2013                                                 LinearizedRegion *LRegion) {
2014   DenseSet<unsigned> *LiveOuts = InnerRegion->getLiveOuts();
2015   SmallVector<unsigned, 4> OldLiveOuts;
2016   bool IsSingleBB = InnerRegion->getEntry() == InnerRegion->getExit();
2017   for (auto OLI : *LiveOuts) {
2018     OldLiveOuts.push_back(OLI);
2019   }
2020 
2021   for (auto LI : OldLiveOuts) {
2022     LLVM_DEBUG(dbgs() << "LiveOut: " << printReg(LI, TRI));
2023     if (!containsDef(CodeBB, InnerRegion, LI) ||
2024         (!IsSingleBB && (getDefInstr(LI)->getParent() == LRegion->getExit()))) {
2025       // If the register simly lives through the CodeBB, we don't have
2026       // to rewrite anything since the register is not defined in this
2027       // part of the code.
2028       LLVM_DEBUG(dbgs() << "- through");
2029       continue;
2030     }
2031     LLVM_DEBUG(dbgs() << "\n");
2032     unsigned Reg = LI;
2033     if (/*!PHIInfo.isSource(Reg) &&*/ Reg != InnerRegion->getBBSelectRegOut()) {
2034       // If the register is live out, we do want to create a phi,
2035       // unless it is from the Exit block, becasuse in that case there
2036       // is already a PHI, and no need to create a new one.
2037 
2038       // If the register is just a live out def and not part of a phi
2039       // chain, we need to create a PHI node to handle the if region,
2040       // and replace all uses outside of the region with the new dest
2041       // register, unless it is the outgoing BB select register. We have
2042       // already creaed phi nodes for these.
2043       const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
2044       Register PHIDestReg = MRI->createVirtualRegister(RegClass);
2045       Register IfSourceReg = MRI->createVirtualRegister(RegClass);
2046       // Create initializer, this value is never used, but is needed
2047       // to satisfy SSA.
2048       LLVM_DEBUG(dbgs() << "Initializer for reg: " << printReg(Reg) << "\n");
2049       TII->materializeImmediate(*IfBB, IfBB->getFirstTerminator(), DebugLoc(),
2050                         IfSourceReg, 0);
2051 
2052       InnerRegion->replaceRegisterOutsideRegion(Reg, PHIDestReg, true, MRI);
2053       LLVM_DEBUG(dbgs() << "Insert Non-Chained Live out PHI\n");
2054       insertMergePHI(IfBB, InnerRegion->getExit(), MergeBB, PHIDestReg,
2055                      IfSourceReg, Reg, true);
2056     }
2057   }
2058 
2059   // Handle the chained definitions in PHIInfo, checking if this basic block
2060   // is a source block for a definition.
2061   SmallVector<unsigned, 4> Sources;
2062   if (PHIInfo.findSourcesFromMBB(CodeBB, Sources)) {
2063     LLVM_DEBUG(dbgs() << "Inserting PHI Live Out from "
2064                       << printMBBReference(*CodeBB) << "\n");
2065     for (auto SI : Sources) {
2066       unsigned DestReg;
2067       PHIInfo.findDest(SI, CodeBB, DestReg);
2068       insertChainedPHI(IfBB, CodeBB, MergeBB, InnerRegion, DestReg, SI);
2069     }
2070     LLVM_DEBUG(dbgs() << "Insertion done.\n");
2071   }
2072 
2073   LLVM_DEBUG(PHIInfo.dump(MRI));
2074 }
2075 
2076 void AMDGPUMachineCFGStructurizer::prunePHIInfo(MachineBasicBlock *MBB) {
2077   LLVM_DEBUG(dbgs() << "Before PHI Prune\n");
2078   LLVM_DEBUG(PHIInfo.dump(MRI));
2079   SmallVector<std::tuple<unsigned, unsigned, MachineBasicBlock *>, 4>
2080       ElimiatedSources;
2081   for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE;
2082        ++DRI) {
2083 
2084     unsigned DestReg = *DRI;
2085     auto SE = PHIInfo.sources_end(DestReg);
2086 
2087     bool MBBContainsPHISource = false;
2088     // Check if there is a PHI source in this MBB
2089     for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) {
2090       unsigned SourceReg = (*SRI).first;
2091       MachineOperand *Def = &(*(MRI->def_begin(SourceReg)));
2092       if (Def->getParent()->getParent() == MBB) {
2093         MBBContainsPHISource = true;
2094       }
2095     }
2096 
2097     // If so, all other sources are useless since we know this block
2098     // is always executed when the region is executed.
2099     if (MBBContainsPHISource) {
2100       for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) {
2101         PHILinearize::PHISourceT Source = *SRI;
2102         unsigned SourceReg = Source.first;
2103         MachineBasicBlock *SourceMBB = Source.second;
2104         MachineOperand *Def = &(*(MRI->def_begin(SourceReg)));
2105         if (Def->getParent()->getParent() != MBB) {
2106           ElimiatedSources.push_back(
2107               std::make_tuple(DestReg, SourceReg, SourceMBB));
2108         }
2109       }
2110     }
2111   }
2112 
2113   // Remove the PHI sources that are in the given MBB
2114   for (auto &SourceInfo : ElimiatedSources) {
2115     PHIInfo.removeSource(std::get<0>(SourceInfo), std::get<1>(SourceInfo),
2116                          std::get<2>(SourceInfo));
2117   }
2118   LLVM_DEBUG(dbgs() << "After PHI Prune\n");
2119   LLVM_DEBUG(PHIInfo.dump(MRI));
2120 }
2121 
2122 void AMDGPUMachineCFGStructurizer::createEntryPHI(LinearizedRegion *CurrentRegion,
2123                                             unsigned DestReg) {
2124   MachineBasicBlock *Entry = CurrentRegion->getEntry();
2125   MachineBasicBlock *Exit = CurrentRegion->getExit();
2126 
2127   LLVM_DEBUG(dbgs() << "RegionExit: " << Exit->getNumber() << " Pred: "
2128                     << (*(Entry->pred_begin()))->getNumber() << "\n");
2129 
2130   int NumSources = 0;
2131   auto SE = PHIInfo.sources_end(DestReg);
2132 
2133   for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) {
2134     NumSources++;
2135   }
2136 
2137   if (NumSources == 1) {
2138     auto SRI = PHIInfo.sources_begin(DestReg);
2139     unsigned SourceReg = (*SRI).first;
2140     replaceRegisterWith(DestReg, SourceReg);
2141   } else {
2142     const DebugLoc &DL = Entry->findDebugLoc(Entry->begin());
2143     MachineInstrBuilder MIB = BuildMI(*Entry, Entry->instr_begin(), DL,
2144                                       TII->get(TargetOpcode::PHI), DestReg);
2145     LLVM_DEBUG(dbgs() << "Entry PHI " << printReg(DestReg, TRI) << " = PHI(");
2146 
2147     unsigned CurrentBackedgeReg = 0;
2148 
2149     for (auto SRI = PHIInfo.sources_begin(DestReg); SRI != SE; ++SRI) {
2150       unsigned SourceReg = (*SRI).first;
2151 
2152       if (CurrentRegion->contains((*SRI).second)) {
2153         if (CurrentBackedgeReg == 0) {
2154           CurrentBackedgeReg = SourceReg;
2155         } else {
2156           MachineInstr *PHIDefInstr = getDefInstr(SourceReg);
2157           MachineBasicBlock *PHIDefMBB = PHIDefInstr->getParent();
2158           const TargetRegisterClass *RegClass =
2159               MRI->getRegClass(CurrentBackedgeReg);
2160           Register NewBackedgeReg = MRI->createVirtualRegister(RegClass);
2161           MachineInstrBuilder BackedgePHI =
2162               BuildMI(*PHIDefMBB, PHIDefMBB->instr_begin(), DL,
2163                       TII->get(TargetOpcode::PHI), NewBackedgeReg);
2164           BackedgePHI.addReg(CurrentBackedgeReg);
2165           BackedgePHI.addMBB(getPHIPred(*PHIDefInstr, 0));
2166           BackedgePHI.addReg(getPHISourceReg(*PHIDefInstr, 1));
2167           BackedgePHI.addMBB((*SRI).second);
2168           CurrentBackedgeReg = NewBackedgeReg;
2169           LLVM_DEBUG(dbgs()
2170                      << "Inserting backedge PHI: "
2171                      << printReg(NewBackedgeReg, TRI) << " = PHI("
2172                      << printReg(CurrentBackedgeReg, TRI) << ", "
2173                      << printMBBReference(*getPHIPred(*PHIDefInstr, 0)) << ", "
2174                      << printReg(getPHISourceReg(*PHIDefInstr, 1), TRI) << ", "
2175                      << printMBBReference(*(*SRI).second));
2176         }
2177       } else {
2178         MIB.addReg(SourceReg);
2179         MIB.addMBB((*SRI).second);
2180         LLVM_DEBUG(dbgs() << printReg(SourceReg, TRI) << ", "
2181                           << printMBBReference(*(*SRI).second) << ", ");
2182       }
2183     }
2184 
2185     // Add the final backedge register source to the entry phi
2186     if (CurrentBackedgeReg != 0) {
2187       MIB.addReg(CurrentBackedgeReg);
2188       MIB.addMBB(Exit);
2189       LLVM_DEBUG(dbgs() << printReg(CurrentBackedgeReg, TRI) << ", "
2190                         << printMBBReference(*Exit) << ")\n");
2191     } else {
2192       LLVM_DEBUG(dbgs() << ")\n");
2193     }
2194   }
2195 }
2196 
2197 void AMDGPUMachineCFGStructurizer::createEntryPHIs(LinearizedRegion *CurrentRegion) {
2198   LLVM_DEBUG(PHIInfo.dump(MRI));
2199 
2200   for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE;
2201        ++DRI) {
2202 
2203     unsigned DestReg = *DRI;
2204     createEntryPHI(CurrentRegion, DestReg);
2205   }
2206   PHIInfo.clear();
2207 }
2208 
2209 void AMDGPUMachineCFGStructurizer::replaceRegisterWith(
2210     unsigned Register, class Register NewRegister) {
2211   assert(Register != NewRegister && "Cannot replace a reg with itself");
2212 
2213   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Register),
2214                                          E = MRI->reg_end();
2215        I != E;) {
2216     MachineOperand &O = *I;
2217     ++I;
2218     if (NewRegister.isPhysical()) {
2219       LLVM_DEBUG(dbgs() << "Trying to substitute physical register: "
2220                         << printReg(NewRegister, MRI->getTargetRegisterInfo())
2221                         << "\n");
2222       llvm_unreachable("Cannot substitute physical registers");
2223       // We don't handle physical registers, but if we need to
2224       // in the future This is how we do it:
2225       // O.substPhysReg(NewRegister, *TRI);
2226     } else {
2227       LLVM_DEBUG(dbgs() << "Replacing register: "
2228                         << printReg(Register, MRI->getTargetRegisterInfo())
2229                         << " with "
2230                         << printReg(NewRegister, MRI->getTargetRegisterInfo())
2231                         << "\n");
2232       O.setReg(NewRegister);
2233     }
2234   }
2235   PHIInfo.deleteDef(Register);
2236 
2237   getRegionMRT()->replaceLiveOutReg(Register, NewRegister);
2238 
2239   LLVM_DEBUG(PHIInfo.dump(MRI));
2240 }
2241 
2242 void AMDGPUMachineCFGStructurizer::resolvePHIInfos(MachineBasicBlock *FunctionEntry) {
2243   LLVM_DEBUG(dbgs() << "Resolve PHI Infos\n");
2244   LLVM_DEBUG(PHIInfo.dump(MRI));
2245   for (auto DRI = PHIInfo.dests_begin(), DE = PHIInfo.dests_end(); DRI != DE;
2246        ++DRI) {
2247     unsigned DestReg = *DRI;
2248     LLVM_DEBUG(dbgs() << "DestReg: " << printReg(DestReg, TRI) << "\n");
2249     auto SRI = PHIInfo.sources_begin(DestReg);
2250     unsigned SourceReg = (*SRI).first;
2251     LLVM_DEBUG(dbgs() << "DestReg: " << printReg(DestReg, TRI)
2252                       << " SourceReg: " << printReg(SourceReg, TRI) << "\n");
2253 
2254     assert(PHIInfo.sources_end(DestReg) == ++SRI &&
2255            "More than one phi source in entry node");
2256     replaceRegisterWith(DestReg, SourceReg);
2257   }
2258 }
2259 
2260 static bool isFunctionEntryBlock(MachineBasicBlock *MBB) {
2261   return ((&(*(MBB->getParent()->begin()))) == MBB);
2262 }
2263 
2264 MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfRegion(
2265     MachineBasicBlock *MergeBB, MachineBasicBlock *CodeBB,
2266     LinearizedRegion *CurrentRegion, unsigned BBSelectRegIn,
2267     unsigned BBSelectRegOut) {
2268   if (isFunctionEntryBlock(CodeBB) && !CurrentRegion->getHasLoop()) {
2269     // Handle non-loop function entry block.
2270     // We need to allow loops to the entry block and then
2271     rewriteCodeBBTerminator(CodeBB, MergeBB, BBSelectRegOut);
2272     resolvePHIInfos(CodeBB);
2273     removeExternalCFGSuccessors(CodeBB);
2274     CodeBB->addSuccessor(MergeBB);
2275     CurrentRegion->addMBB(CodeBB);
2276     return nullptr;
2277   }
2278   if (CurrentRegion->getEntry() == CodeBB && !CurrentRegion->getHasLoop()) {
2279     // Handle non-loop region entry block.
2280     MachineFunction *MF = MergeBB->getParent();
2281     auto MergeIter = MergeBB->getIterator();
2282     auto CodeBBStartIter = CodeBB->getIterator();
2283     auto CodeBBEndIter = ++(CodeBB->getIterator());
2284     if (CodeBBEndIter != MergeIter) {
2285       MF->splice(MergeIter, CodeBBStartIter, CodeBBEndIter);
2286     }
2287     rewriteCodeBBTerminator(CodeBB, MergeBB, BBSelectRegOut);
2288     prunePHIInfo(CodeBB);
2289     createEntryPHIs(CurrentRegion);
2290     removeExternalCFGSuccessors(CodeBB);
2291     CodeBB->addSuccessor(MergeBB);
2292     CurrentRegion->addMBB(CodeBB);
2293     return nullptr;
2294   } else {
2295     // Handle internal block.
2296     const TargetRegisterClass *RegClass = MRI->getRegClass(BBSelectRegIn);
2297     Register CodeBBSelectReg = MRI->createVirtualRegister(RegClass);
2298     rewriteCodeBBTerminator(CodeBB, MergeBB, CodeBBSelectReg);
2299     bool IsRegionEntryBB = CurrentRegion->getEntry() == CodeBB;
2300     MachineBasicBlock *IfBB = createIfBlock(MergeBB, CodeBB, CodeBB, CodeBB,
2301                                             BBSelectRegIn, IsRegionEntryBB);
2302     CurrentRegion->addMBB(IfBB);
2303     // If this is the entry block we need to make the If block the new
2304     // linearized region entry.
2305     if (IsRegionEntryBB) {
2306       CurrentRegion->setEntry(IfBB);
2307 
2308       if (CurrentRegion->getHasLoop()) {
2309         MachineBasicBlock *RegionExit = CurrentRegion->getExit();
2310         MachineBasicBlock *ETrueBB = nullptr;
2311         MachineBasicBlock *EFalseBB = nullptr;
2312         SmallVector<MachineOperand, 1> ECond;
2313 
2314         const DebugLoc &DL = DebugLoc();
2315         TII->analyzeBranch(*RegionExit, ETrueBB, EFalseBB, ECond);
2316         TII->removeBranch(*RegionExit);
2317 
2318         // We need to create a backedge if there is a loop
2319         Register Reg = TII->insertNE(
2320             RegionExit, RegionExit->instr_end(), DL,
2321             CurrentRegion->getRegionMRT()->getInnerOutputRegister(),
2322             CurrentRegion->getRegionMRT()->getEntry()->getNumber());
2323         MachineOperand RegOp =
2324             MachineOperand::CreateReg(Reg, false, false, true);
2325         ArrayRef<MachineOperand> Cond(RegOp);
2326         LLVM_DEBUG(dbgs() << "RegionExitReg: ");
2327         LLVM_DEBUG(Cond[0].print(dbgs(), TRI));
2328         LLVM_DEBUG(dbgs() << "\n");
2329         TII->insertBranch(*RegionExit, CurrentRegion->getEntry(), RegionExit,
2330                           Cond, DebugLoc());
2331         RegionExit->addSuccessor(CurrentRegion->getEntry());
2332       }
2333     }
2334     CurrentRegion->addMBB(CodeBB);
2335     LinearizedRegion InnerRegion(CodeBB, MRI, TRI, PHIInfo);
2336 
2337     InnerRegion.setParent(CurrentRegion);
2338     LLVM_DEBUG(dbgs() << "Insert BB Select PHI (BB)\n");
2339     insertMergePHI(IfBB, CodeBB, MergeBB, BBSelectRegOut, BBSelectRegIn,
2340                    CodeBBSelectReg);
2341     InnerRegion.addMBB(MergeBB);
2342 
2343     LLVM_DEBUG(InnerRegion.print(dbgs(), TRI));
2344     rewriteLiveOutRegs(IfBB, CodeBB, MergeBB, &InnerRegion, CurrentRegion);
2345     extractKilledPHIs(CodeBB);
2346     if (IsRegionEntryBB) {
2347       createEntryPHIs(CurrentRegion);
2348     }
2349     return IfBB;
2350   }
2351 }
2352 
2353 MachineBasicBlock *AMDGPUMachineCFGStructurizer::createIfRegion(
2354     MachineBasicBlock *MergeBB, LinearizedRegion *InnerRegion,
2355     LinearizedRegion *CurrentRegion, MachineBasicBlock *SelectBB,
2356     unsigned BBSelectRegIn, unsigned BBSelectRegOut) {
2357   unsigned CodeBBSelectReg =
2358       InnerRegion->getRegionMRT()->getInnerOutputRegister();
2359   MachineBasicBlock *CodeEntryBB = InnerRegion->getEntry();
2360   MachineBasicBlock *CodeExitBB = InnerRegion->getExit();
2361   MachineBasicBlock *IfBB = createIfBlock(MergeBB, CodeEntryBB, CodeExitBB,
2362                                           SelectBB, BBSelectRegIn, true);
2363   CurrentRegion->addMBB(IfBB);
2364   bool isEntry = CurrentRegion->getEntry() == InnerRegion->getEntry();
2365   if (isEntry) {
2366 
2367     if (CurrentRegion->getHasLoop()) {
2368       MachineBasicBlock *RegionExit = CurrentRegion->getExit();
2369       MachineBasicBlock *ETrueBB = nullptr;
2370       MachineBasicBlock *EFalseBB = nullptr;
2371       SmallVector<MachineOperand, 1> ECond;
2372 
2373       const DebugLoc &DL = DebugLoc();
2374       TII->analyzeBranch(*RegionExit, ETrueBB, EFalseBB, ECond);
2375       TII->removeBranch(*RegionExit);
2376 
2377       // We need to create a backedge if there is a loop
2378       Register Reg =
2379           TII->insertNE(RegionExit, RegionExit->instr_end(), DL,
2380                         CurrentRegion->getRegionMRT()->getInnerOutputRegister(),
2381                         CurrentRegion->getRegionMRT()->getEntry()->getNumber());
2382       MachineOperand RegOp = MachineOperand::CreateReg(Reg, false, false, true);
2383       ArrayRef<MachineOperand> Cond(RegOp);
2384       LLVM_DEBUG(dbgs() << "RegionExitReg: ");
2385       LLVM_DEBUG(Cond[0].print(dbgs(), TRI));
2386       LLVM_DEBUG(dbgs() << "\n");
2387       TII->insertBranch(*RegionExit, CurrentRegion->getEntry(), RegionExit,
2388                         Cond, DebugLoc());
2389       RegionExit->addSuccessor(IfBB);
2390     }
2391   }
2392   CurrentRegion->addMBBs(InnerRegion);
2393   LLVM_DEBUG(dbgs() << "Insert BB Select PHI (region)\n");
2394   insertMergePHI(IfBB, CodeExitBB, MergeBB, BBSelectRegOut, BBSelectRegIn,
2395                  CodeBBSelectReg);
2396 
2397   rewriteLiveOutRegs(IfBB, /* CodeEntryBB */ CodeExitBB, MergeBB, InnerRegion,
2398                      CurrentRegion);
2399 
2400   rewriteRegionEntryPHIs(InnerRegion, IfBB);
2401 
2402   if (isEntry) {
2403     CurrentRegion->setEntry(IfBB);
2404   }
2405 
2406   if (isEntry) {
2407     createEntryPHIs(CurrentRegion);
2408   }
2409 
2410   return IfBB;
2411 }
2412 
2413 void AMDGPUMachineCFGStructurizer::splitLoopPHI(MachineInstr &PHI,
2414                                           MachineBasicBlock *Entry,
2415                                           MachineBasicBlock *EntrySucc,
2416                                           LinearizedRegion *LRegion) {
2417   SmallVector<unsigned, 2> PHIRegionIndices;
2418   getPHIRegionIndices(LRegion, PHI, PHIRegionIndices);
2419 
2420   assert(PHIRegionIndices.size() == 1);
2421 
2422   unsigned RegionIndex = PHIRegionIndices[0];
2423   unsigned RegionSourceReg = getPHISourceReg(PHI, RegionIndex);
2424   MachineBasicBlock *RegionSourceMBB = getPHIPred(PHI, RegionIndex);
2425   unsigned PHIDest = getPHIDestReg(PHI);
2426   unsigned PHISource = PHIDest;
2427   unsigned ReplaceReg;
2428 
2429   if (shrinkPHI(PHI, PHIRegionIndices, &ReplaceReg)) {
2430     PHISource = ReplaceReg;
2431   }
2432 
2433   const TargetRegisterClass *RegClass = MRI->getRegClass(PHIDest);
2434   Register NewDestReg = MRI->createVirtualRegister(RegClass);
2435   LRegion->replaceRegisterInsideRegion(PHIDest, NewDestReg, false, MRI);
2436   MachineInstrBuilder MIB =
2437       BuildMI(*EntrySucc, EntrySucc->instr_begin(), PHI.getDebugLoc(),
2438               TII->get(TargetOpcode::PHI), NewDestReg);
2439   LLVM_DEBUG(dbgs() << "Split Entry PHI " << printReg(NewDestReg, TRI)
2440                     << " = PHI(");
2441   MIB.addReg(PHISource);
2442   MIB.addMBB(Entry);
2443   LLVM_DEBUG(dbgs() << printReg(PHISource, TRI) << ", "
2444                     << printMBBReference(*Entry));
2445   MIB.addReg(RegionSourceReg);
2446   MIB.addMBB(RegionSourceMBB);
2447   LLVM_DEBUG(dbgs() << " ," << printReg(RegionSourceReg, TRI) << ", "
2448                     << printMBBReference(*RegionSourceMBB) << ")\n");
2449 }
2450 
2451 void AMDGPUMachineCFGStructurizer::splitLoopPHIs(MachineBasicBlock *Entry,
2452                                            MachineBasicBlock *EntrySucc,
2453                                            LinearizedRegion *LRegion) {
2454   SmallVector<MachineInstr *, 2> PHIs;
2455   collectPHIs(Entry, PHIs);
2456 
2457   for (auto PHII : PHIs) {
2458     splitLoopPHI(*PHII, Entry, EntrySucc, LRegion);
2459   }
2460 }
2461 
2462 // Split the exit block so that we can insert a end control flow
2463 MachineBasicBlock *
2464 AMDGPUMachineCFGStructurizer::splitExit(LinearizedRegion *LRegion) {
2465   auto MRTRegion = LRegion->getRegionMRT();
2466   auto Exit = LRegion->getExit();
2467   auto MF = Exit->getParent();
2468   auto Succ = MRTRegion->getSucc();
2469 
2470   auto NewExit = MF->CreateMachineBasicBlock();
2471   auto AfterExitIter = Exit->getIterator();
2472   AfterExitIter++;
2473   MF->insert(AfterExitIter, NewExit);
2474   Exit->removeSuccessor(Succ);
2475   Exit->addSuccessor(NewExit);
2476   NewExit->addSuccessor(Succ);
2477   insertUnconditionalBranch(NewExit, Succ);
2478   LRegion->addMBB(NewExit);
2479   LRegion->setExit(NewExit);
2480 
2481   LLVM_DEBUG(dbgs() << "Created new exit block: " << NewExit->getNumber()
2482                     << "\n");
2483 
2484   // Replace any PHI Predecessors in the successor with NewExit
2485   for (auto &II : *Succ) {
2486     MachineInstr &Instr = II;
2487 
2488     // If we are past the PHI instructions we are done
2489     if (!Instr.isPHI())
2490       break;
2491 
2492     int numPreds = getPHINumInputs(Instr);
2493     for (int i = 0; i < numPreds; ++i) {
2494       auto Pred = getPHIPred(Instr, i);
2495       if (Pred == Exit) {
2496         setPhiPred(Instr, i, NewExit);
2497       }
2498     }
2499   }
2500 
2501   return NewExit;
2502 }
2503 
2504 static MachineBasicBlock *split(MachineBasicBlock::iterator I) {
2505   // Create the fall-through block.
2506   MachineBasicBlock *MBB = (*I).getParent();
2507   MachineFunction *MF = MBB->getParent();
2508   MachineBasicBlock *SuccMBB = MF->CreateMachineBasicBlock();
2509   auto MBBIter = ++(MBB->getIterator());
2510   MF->insert(MBBIter, SuccMBB);
2511   SuccMBB->transferSuccessorsAndUpdatePHIs(MBB);
2512   MBB->addSuccessor(SuccMBB);
2513 
2514   // Splice the code over.
2515   SuccMBB->splice(SuccMBB->end(), MBB, I, MBB->end());
2516 
2517   return SuccMBB;
2518 }
2519 
2520 // Split the entry block separating PHI-nodes and the rest of the code
2521 // This is needed to insert an initializer for the bb select register
2522 // inloop regions.
2523 
2524 MachineBasicBlock *
2525 AMDGPUMachineCFGStructurizer::splitEntry(LinearizedRegion *LRegion) {
2526   MachineBasicBlock *Entry = LRegion->getEntry();
2527   MachineBasicBlock *EntrySucc = split(Entry->getFirstNonPHI());
2528   MachineBasicBlock *Exit = LRegion->getExit();
2529 
2530   LLVM_DEBUG(dbgs() << "Split " << printMBBReference(*Entry) << " to "
2531                     << printMBBReference(*Entry) << " -> "
2532                     << printMBBReference(*EntrySucc) << "\n");
2533   LRegion->addMBB(EntrySucc);
2534 
2535   // Make the backedge go to Entry Succ
2536   if (Exit->isSuccessor(Entry)) {
2537     Exit->removeSuccessor(Entry);
2538   }
2539   Exit->addSuccessor(EntrySucc);
2540   MachineInstr &Branch = *(Exit->instr_rbegin());
2541   for (auto &UI : Branch.uses()) {
2542     if (UI.isMBB() && UI.getMBB() == Entry) {
2543       UI.setMBB(EntrySucc);
2544     }
2545   }
2546 
2547   splitLoopPHIs(Entry, EntrySucc, LRegion);
2548 
2549   return EntrySucc;
2550 }
2551 
2552 LinearizedRegion *
2553 AMDGPUMachineCFGStructurizer::initLinearizedRegion(RegionMRT *Region) {
2554   LinearizedRegion *LRegion = Region->getLinearizedRegion();
2555   LRegion->initLiveOut(Region, MRI, TRI, PHIInfo);
2556   LRegion->setEntry(Region->getEntry());
2557   return LRegion;
2558 }
2559 
2560 static void removeOldExitPreds(RegionMRT *Region) {
2561   MachineBasicBlock *Exit = Region->getSucc();
2562   if (Exit == nullptr) {
2563     return;
2564   }
2565   for (MachineBasicBlock::pred_iterator PI = Exit->pred_begin(),
2566                                         E = Exit->pred_end();
2567        PI != E; ++PI) {
2568     if (Region->contains(*PI)) {
2569       (*PI)->removeSuccessor(Exit);
2570     }
2571   }
2572 }
2573 
2574 static bool mbbHasBackEdge(MachineBasicBlock *MBB,
2575                            SmallPtrSet<MachineBasicBlock *, 8> &MBBs) {
2576   for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) {
2577     if (MBBs.contains(*SI)) {
2578       return true;
2579     }
2580   }
2581   return false;
2582 }
2583 
2584 static bool containsNewBackedge(MRT *Tree,
2585                                 SmallPtrSet<MachineBasicBlock *, 8> &MBBs) {
2586   // Need to traverse this in reverse since it is in post order.
2587   if (Tree == nullptr)
2588     return false;
2589 
2590   if (Tree->isMBB()) {
2591     MachineBasicBlock *MBB = Tree->getMBBMRT()->getMBB();
2592     MBBs.insert(MBB);
2593     if (mbbHasBackEdge(MBB, MBBs)) {
2594       return true;
2595     }
2596   } else {
2597     RegionMRT *Region = Tree->getRegionMRT();
2598     SetVector<MRT *> *Children = Region->getChildren();
2599     for (auto CI = Children->rbegin(), CE = Children->rend(); CI != CE; ++CI) {
2600       if (containsNewBackedge(*CI, MBBs))
2601         return true;
2602     }
2603   }
2604   return false;
2605 }
2606 
2607 static bool containsNewBackedge(RegionMRT *Region) {
2608   SmallPtrSet<MachineBasicBlock *, 8> MBBs;
2609   return containsNewBackedge(Region, MBBs);
2610 }
2611 
2612 bool AMDGPUMachineCFGStructurizer::structurizeComplexRegion(RegionMRT *Region) {
2613   auto *LRegion = initLinearizedRegion(Region);
2614   LRegion->setHasLoop(containsNewBackedge(Region));
2615   MachineBasicBlock *LastMerge = createLinearizedExitBlock(Region);
2616   MachineBasicBlock *CurrentMerge = LastMerge;
2617   LRegion->addMBB(LastMerge);
2618   LRegion->setExit(LastMerge);
2619 
2620   rewriteRegionExitPHIs(Region, LastMerge, LRegion);
2621   removeOldExitPreds(Region);
2622 
2623   LLVM_DEBUG(PHIInfo.dump(MRI));
2624 
2625   SetVector<MRT *> *Children = Region->getChildren();
2626   LLVM_DEBUG(dbgs() << "===========If Region Start===============\n");
2627   if (LRegion->getHasLoop()) {
2628     LLVM_DEBUG(dbgs() << "Has Backedge: Yes\n");
2629   } else {
2630     LLVM_DEBUG(dbgs() << "Has Backedge: No\n");
2631   }
2632 
2633   unsigned BBSelectRegIn;
2634   unsigned BBSelectRegOut;
2635   for (auto CI = Children->begin(), CE = Children->end(); CI != CE; ++CI) {
2636     LLVM_DEBUG(dbgs() << "CurrentRegion: \n");
2637     LLVM_DEBUG(LRegion->print(dbgs(), TRI));
2638 
2639     auto CNI = CI;
2640     ++CNI;
2641 
2642     MRT *Child = (*CI);
2643 
2644     if (Child->isRegion()) {
2645 
2646       LinearizedRegion *InnerLRegion =
2647           Child->getRegionMRT()->getLinearizedRegion();
2648       // We found the block is the exit of an inner region, we need
2649       // to put it in the current linearized region.
2650 
2651       LLVM_DEBUG(dbgs() << "Linearizing region: ");
2652       LLVM_DEBUG(InnerLRegion->print(dbgs(), TRI));
2653       LLVM_DEBUG(dbgs() << "\n");
2654 
2655       MachineBasicBlock *InnerEntry = InnerLRegion->getEntry();
2656       if ((&(*(InnerEntry->getParent()->begin()))) == InnerEntry) {
2657         // Entry has already been linearized, no need to do this region.
2658         unsigned OuterSelect = InnerLRegion->getBBSelectRegOut();
2659         unsigned InnerSelectReg =
2660             InnerLRegion->getRegionMRT()->getInnerOutputRegister();
2661         replaceRegisterWith(InnerSelectReg, OuterSelect),
2662             resolvePHIInfos(InnerEntry);
2663         if (!InnerLRegion->getExit()->isSuccessor(CurrentMerge))
2664           InnerLRegion->getExit()->addSuccessor(CurrentMerge);
2665         continue;
2666       }
2667 
2668       BBSelectRegOut = Child->getBBSelectRegOut();
2669       BBSelectRegIn = Child->getBBSelectRegIn();
2670 
2671       LLVM_DEBUG(dbgs() << "BBSelectRegIn: " << printReg(BBSelectRegIn, TRI)
2672                         << "\n");
2673       LLVM_DEBUG(dbgs() << "BBSelectRegOut: " << printReg(BBSelectRegOut, TRI)
2674                         << "\n");
2675 
2676       MachineBasicBlock *IfEnd = CurrentMerge;
2677       CurrentMerge = createIfRegion(CurrentMerge, InnerLRegion, LRegion,
2678                                     Child->getRegionMRT()->getEntry(),
2679                                     BBSelectRegIn, BBSelectRegOut);
2680       TII->convertNonUniformIfRegion(CurrentMerge, IfEnd);
2681     } else {
2682       MachineBasicBlock *MBB = Child->getMBBMRT()->getMBB();
2683       LLVM_DEBUG(dbgs() << "Linearizing block: " << MBB->getNumber() << "\n");
2684 
2685       if (MBB == getSingleExitNode(*(MBB->getParent()))) {
2686         // If this is the exit block then we need to skip to the next.
2687         // The "in" register will be transferred to "out" in the next
2688         // iteration.
2689         continue;
2690       }
2691 
2692       BBSelectRegOut = Child->getBBSelectRegOut();
2693       BBSelectRegIn = Child->getBBSelectRegIn();
2694 
2695       LLVM_DEBUG(dbgs() << "BBSelectRegIn: " << printReg(BBSelectRegIn, TRI)
2696                         << "\n");
2697       LLVM_DEBUG(dbgs() << "BBSelectRegOut: " << printReg(BBSelectRegOut, TRI)
2698                         << "\n");
2699 
2700       MachineBasicBlock *IfEnd = CurrentMerge;
2701       // This is a basic block that is not part of an inner region, we
2702       // need to put it in the current linearized region.
2703       CurrentMerge = createIfRegion(CurrentMerge, MBB, LRegion, BBSelectRegIn,
2704                                     BBSelectRegOut);
2705       if (CurrentMerge) {
2706         TII->convertNonUniformIfRegion(CurrentMerge, IfEnd);
2707       }
2708 
2709       LLVM_DEBUG(PHIInfo.dump(MRI));
2710     }
2711   }
2712 
2713   LRegion->removeFalseRegisterKills(MRI);
2714 
2715   if (LRegion->getHasLoop()) {
2716     MachineBasicBlock *NewSucc = splitEntry(LRegion);
2717     if (isFunctionEntryBlock(LRegion->getEntry())) {
2718       resolvePHIInfos(LRegion->getEntry());
2719     }
2720     const DebugLoc &DL = NewSucc->findDebugLoc(NewSucc->getFirstNonPHI());
2721     unsigned InReg = LRegion->getBBSelectRegIn();
2722     Register InnerSelectReg =
2723         MRI->createVirtualRegister(MRI->getRegClass(InReg));
2724     Register NewInReg = MRI->createVirtualRegister(MRI->getRegClass(InReg));
2725     TII->materializeImmediate(*(LRegion->getEntry()),
2726                               LRegion->getEntry()->getFirstTerminator(), DL,
2727                               NewInReg, Region->getEntry()->getNumber());
2728     // Need to be careful about updating the registers inside the region.
2729     LRegion->replaceRegisterInsideRegion(InReg, InnerSelectReg, false, MRI);
2730     LLVM_DEBUG(dbgs() << "Loop BBSelect Merge PHI:\n");
2731     insertMergePHI(LRegion->getEntry(), LRegion->getExit(), NewSucc,
2732                    InnerSelectReg, NewInReg,
2733                    LRegion->getRegionMRT()->getInnerOutputRegister());
2734     splitExit(LRegion);
2735     TII->convertNonUniformLoopRegion(NewSucc, LastMerge);
2736   }
2737 
2738   if (Region->isRoot()) {
2739     TII->insertReturn(*LastMerge);
2740   }
2741 
2742   LLVM_DEBUG(Region->getEntry()->getParent()->dump());
2743   LLVM_DEBUG(LRegion->print(dbgs(), TRI));
2744   LLVM_DEBUG(PHIInfo.dump(MRI));
2745 
2746   LLVM_DEBUG(dbgs() << "===========If Region End===============\n");
2747 
2748   Region->setLinearizedRegion(LRegion);
2749   return true;
2750 }
2751 
2752 bool AMDGPUMachineCFGStructurizer::structurizeRegion(RegionMRT *Region) {
2753   if (false && regionIsSimpleIf(Region)) {
2754     transformSimpleIfRegion(Region);
2755     return true;
2756   } else if (regionIsSequence(Region)) {
2757     fixupRegionExits(Region);
2758     return false;
2759   } else {
2760     structurizeComplexRegion(Region);
2761   }
2762   return false;
2763 }
2764 
2765 static int structurize_once = 0;
2766 
2767 bool AMDGPUMachineCFGStructurizer::structurizeRegions(RegionMRT *Region,
2768                                                 bool isTopRegion) {
2769   bool Changed = false;
2770 
2771   auto Children = Region->getChildren();
2772   for (auto CI : *Children) {
2773     if (CI->isRegion()) {
2774       Changed |= structurizeRegions(CI->getRegionMRT(), false);
2775     }
2776   }
2777 
2778   if (structurize_once < 2 || true) {
2779     Changed |= structurizeRegion(Region);
2780     structurize_once++;
2781   }
2782   return Changed;
2783 }
2784 
2785 void AMDGPUMachineCFGStructurizer::initFallthroughMap(MachineFunction &MF) {
2786   LLVM_DEBUG(dbgs() << "Fallthrough Map:\n");
2787   for (auto &MBBI : MF) {
2788     MachineBasicBlock *MBB = MBBI.getFallThrough();
2789     if (MBB != nullptr) {
2790       LLVM_DEBUG(dbgs() << "Fallthrough: " << MBBI.getNumber() << " -> "
2791                         << MBB->getNumber() << "\n");
2792     }
2793     FallthroughMap[&MBBI] = MBB;
2794   }
2795 }
2796 
2797 void AMDGPUMachineCFGStructurizer::createLinearizedRegion(RegionMRT *Region,
2798                                                     unsigned SelectOut) {
2799   LinearizedRegion *LRegion = new LinearizedRegion();
2800   if (SelectOut) {
2801     LRegion->addLiveOut(SelectOut);
2802     LLVM_DEBUG(dbgs() << "Add LiveOut (BBSelect): " << printReg(SelectOut, TRI)
2803                       << "\n");
2804   }
2805   LRegion->setRegionMRT(Region);
2806   Region->setLinearizedRegion(LRegion);
2807   LRegion->setParent(Region->getParent()
2808                          ? Region->getParent()->getLinearizedRegion()
2809                          : nullptr);
2810 }
2811 
2812 unsigned
2813 AMDGPUMachineCFGStructurizer::initializeSelectRegisters(MRT *MRT, unsigned SelectOut,
2814                                                   MachineRegisterInfo *MRI,
2815                                                   const SIInstrInfo *TII) {
2816   if (MRT->isRegion()) {
2817     RegionMRT *Region = MRT->getRegionMRT();
2818     Region->setBBSelectRegOut(SelectOut);
2819     unsigned InnerSelectOut = createBBSelectReg(TII, MRI);
2820 
2821     // Fixme: Move linearization creation to the original spot
2822     createLinearizedRegion(Region, SelectOut);
2823 
2824     for (auto CI = Region->getChildren()->begin(),
2825               CE = Region->getChildren()->end();
2826          CI != CE; ++CI) {
2827       InnerSelectOut =
2828           initializeSelectRegisters((*CI), InnerSelectOut, MRI, TII);
2829     }
2830     MRT->setBBSelectRegIn(InnerSelectOut);
2831     return InnerSelectOut;
2832   } else {
2833     MRT->setBBSelectRegOut(SelectOut);
2834     unsigned NewSelectIn = createBBSelectReg(TII, MRI);
2835     MRT->setBBSelectRegIn(NewSelectIn);
2836     return NewSelectIn;
2837   }
2838 }
2839 
2840 static void checkRegOnlyPHIInputs(MachineFunction &MF) {
2841   for (auto &MBBI : MF) {
2842     for (MachineBasicBlock::instr_iterator I = MBBI.instr_begin(),
2843                                            E = MBBI.instr_end();
2844          I != E; ++I) {
2845       MachineInstr &Instr = *I;
2846       if (Instr.isPHI()) {
2847         int numPreds = getPHINumInputs(Instr);
2848         for (int i = 0; i < numPreds; ++i) {
2849           assert(Instr.getOperand(i * 2 + 1).isReg() &&
2850                  "PHI Operand not a register");
2851         }
2852       }
2853     }
2854   }
2855 }
2856 
2857 bool AMDGPUMachineCFGStructurizer::runOnMachineFunction(MachineFunction &MF) {
2858   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2859   const SIInstrInfo *TII = ST.getInstrInfo();
2860   TRI = ST.getRegisterInfo();
2861   MRI = &(MF.getRegInfo());
2862   initFallthroughMap(MF);
2863 
2864   checkRegOnlyPHIInputs(MF);
2865   LLVM_DEBUG(dbgs() << "----STRUCTURIZER START----\n");
2866   LLVM_DEBUG(MF.dump());
2867 
2868   Regions = &(getAnalysis<MachineRegionInfoPass>().getRegionInfo());
2869   LLVM_DEBUG(Regions->dump());
2870 
2871   RegionMRT *RTree = MRT::buildMRT(MF, Regions, TII, MRI);
2872   setRegionMRT(RTree);
2873   initializeSelectRegisters(RTree, 0, MRI, TII);
2874   LLVM_DEBUG(RTree->dump(TRI));
2875   bool result = structurizeRegions(RTree, true);
2876   delete RTree;
2877   LLVM_DEBUG(dbgs() << "----STRUCTURIZER END----\n");
2878   initFallthroughMap(MF);
2879   return result;
2880 }
2881 
2882 char AMDGPUMachineCFGStructurizerID = AMDGPUMachineCFGStructurizer::ID;
2883 
2884 INITIALIZE_PASS_BEGIN(AMDGPUMachineCFGStructurizer, "amdgpu-machine-cfg-structurizer",
2885                       "AMDGPU Machine CFG Structurizer", false, false)
2886 INITIALIZE_PASS_DEPENDENCY(MachineRegionInfoPass)
2887 INITIALIZE_PASS_END(AMDGPUMachineCFGStructurizer, "amdgpu-machine-cfg-structurizer",
2888                     "AMDGPU Machine CFG Structurizer", false, false)
2889 
2890 FunctionPass *llvm::createAMDGPUMachineCFGStructurizerPass() {
2891   return new AMDGPUMachineCFGStructurizer();
2892 }
2893