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