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