blob: 0db762d846f225add2026a9195db667036a2d2c0 [file] [log] [blame]
Eugene Zelenko99241d72017-10-20 21:47:29 +00001//===- StructurizeCFG.cpp -------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Tom Stellardf8794352012-12-19 22:10:31 +00009
Eugene Zelenko99241d72017-10-20 21:47:29 +000010#include "llvm/ADT/DenseMap.h"
Christian Konig90b45122013-03-26 10:24:20 +000011#include "llvm/ADT/MapVector.h"
Tom Stellard071ec902015-02-04 20:49:44 +000012#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000013#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/SmallPtrSet.h"
15#include "llvm/ADT/SmallVector.h"
Nicolai Haehnle08230502018-10-17 15:37:41 +000016#include "llvm/Analysis/InstructionSimplify.h"
Nicolai Haehnle35617ed2018-08-30 14:21:36 +000017#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +000018#include "llvm/Analysis/LoopInfo.h"
Tom Stellardf8794352012-12-19 22:10:31 +000019#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000020#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000021#include "llvm/Analysis/RegionPass.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000022#include "llvm/IR/Argument.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CFG.h"
25#include "llvm/IR/Constant.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000033#include "llvm/IR/PatternMatch.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000034#include "llvm/IR/Type.h"
35#include "llvm/IR/Use.h"
36#include "llvm/IR/User.h"
37#include "llvm/IR/Value.h"
38#include "llvm/Pass.h"
39#include "llvm/Support/Casting.h"
Tom Stellard071ec902015-02-04 20:49:44 +000040#include "llvm/Support/Debug.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000041#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000042#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000043#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000044#include "llvm/Transforms/Utils.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000045#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000046#include <algorithm>
47#include <cassert>
48#include <utility>
Tom Stellardf8794352012-12-19 22:10:31 +000049
50using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000051using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000052
Chandler Carruth964daaa2014-04-22 02:55:47 +000053#define DEBUG_TYPE "structurizecfg"
54
Eugene Zelenko99241d72017-10-20 21:47:29 +000055// The name for newly created blocks.
56static const char *const FlowBlockName = "Flow";
57
Tom Stellardf8794352012-12-19 22:10:31 +000058namespace {
59
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +000060static cl::opt<bool> ForceSkipUniformRegions(
61 "structurizecfg-skip-uniform-regions",
62 cl::Hidden,
63 cl::desc("Force whether the StructurizeCFG pass skips uniform regions"),
64 cl::init(false));
65
Tom Stellardf8794352012-12-19 22:10:31 +000066// Definition of the complex types used in this pass.
67
Eugene Zelenko99241d72017-10-20 21:47:29 +000068using BBValuePair = std::pair<BasicBlock *, Value *>;
Tom Stellardf8794352012-12-19 22:10:31 +000069
Eugene Zelenko99241d72017-10-20 21:47:29 +000070using RNVector = SmallVector<RegionNode *, 8>;
71using BBVector = SmallVector<BasicBlock *, 8>;
72using BranchVector = SmallVector<BranchInst *, 8>;
73using BBValueVector = SmallVector<BBValuePair, 2>;
Tom Stellardf8794352012-12-19 22:10:31 +000074
Eugene Zelenko99241d72017-10-20 21:47:29 +000075using BBSet = SmallPtrSet<BasicBlock *, 8>;
Tom Stellard048f14f2013-02-08 22:24:37 +000076
Eugene Zelenko99241d72017-10-20 21:47:29 +000077using PhiMap = MapVector<PHINode *, BBValueVector>;
78using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;
Christian Konig90b45122013-03-26 10:24:20 +000079
Eugene Zelenko99241d72017-10-20 21:47:29 +000080using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
81using BBPredicates = DenseMap<BasicBlock *, Value *>;
82using PredMap = DenseMap<BasicBlock *, BBPredicates>;
83using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;
Tom Stellardf8794352012-12-19 22:10:31 +000084
Justin Lebar62c20d82016-11-28 18:49:59 +000085/// Finds the nearest common dominator of a set of BasicBlocks.
Christian Konigd08e3d72013-02-16 11:27:29 +000086///
Justin Lebar62c20d82016-11-28 18:49:59 +000087/// For every BB you add to the set, you can specify whether we "remember" the
88/// block. When you get the common dominator, you can also ask whether it's one
89/// of the blocks we remembered.
Christian Konigd08e3d72013-02-16 11:27:29 +000090class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000091 DominatorTree *DT;
Justin Lebar62c20d82016-11-28 18:49:59 +000092 BasicBlock *Result = nullptr;
93 bool ResultIsRemembered = false;
Christian Konigd08e3d72013-02-16 11:27:29 +000094
Justin Lebar62c20d82016-11-28 18:49:59 +000095 /// Add BB to the resulting dominator.
96 void addBlock(BasicBlock *BB, bool Remember) {
Craig Topperf40110f2014-04-25 05:29:35 +000097 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000098 Result = BB;
Justin Lebar62c20d82016-11-28 18:49:59 +000099 ResultIsRemembered = Remember;
Christian Konigd08e3d72013-02-16 11:27:29 +0000100 return;
101 }
102
Justin Lebar62c20d82016-11-28 18:49:59 +0000103 BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
104 if (NewResult != Result)
105 ResultIsRemembered = false;
106 if (NewResult == BB)
107 ResultIsRemembered |= Remember;
108 Result = NewResult;
Christian Konigd08e3d72013-02-16 11:27:29 +0000109 }
110
Justin Lebar62c20d82016-11-28 18:49:59 +0000111public:
112 explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
113
114 void addBlock(BasicBlock *BB) {
115 addBlock(BB, /* Remember = */ false);
Christian Konigd08e3d72013-02-16 11:27:29 +0000116 }
117
Justin Lebar62c20d82016-11-28 18:49:59 +0000118 void addAndRememberBlock(BasicBlock *BB) {
119 addBlock(BB, /* Remember = */ true);
Christian Konigd08e3d72013-02-16 11:27:29 +0000120 }
Justin Lebar62c20d82016-11-28 18:49:59 +0000121
122 /// Get the nearest common dominator of all the BBs added via addBlock() and
123 /// addAndRememberBlock().
124 BasicBlock *result() { return Result; }
125
126 /// Is the BB returned by getResult() one of the blocks we added to the set
127 /// with addAndRememberBlock()?
128 bool resultIsRememberedBlock() { return ResultIsRemembered; }
Christian Konigd08e3d72013-02-16 11:27:29 +0000129};
130
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000131/// Transforms the control flow graph on one single entry/exit region
Tom Stellardf8794352012-12-19 22:10:31 +0000132/// at a time.
133///
134/// After the transform all "If"/"Then"/"Else" style control flow looks like
135/// this:
136///
137/// \verbatim
138/// 1
139/// ||
140/// | |
141/// 2 |
142/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000143/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000144/// 3
145/// || Where:
146/// | | 1 = "If" block, calculates the condition
147/// 4 | 2 = "Then" subregion, runs if the condition is true
148/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
149/// |/ 4 = "Else" optional subregion, runs if the condition is false
150/// 5 5 = "End" block, also rejoins the control flow
151/// \endverbatim
152///
153/// Control flow is expressed as a branch where the true exit goes into the
154/// "Then"/"Else" region, while the false exit skips the region
155/// The condition for the optional "Else" region is expressed as a PHI node.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000156/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000157/// for the "Then" edge.
158///
159/// Additionally to that even complicated loops look like this:
160///
161/// \verbatim
162/// 1
163/// ||
164/// | |
165/// 2 ^ Where:
166/// | / 1 = "Entry" block
167/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
168/// 3 3 = "Flow" block, with back edge to entry block
169/// |
170/// \endverbatim
171///
172/// The back edge of the "Flow" block is always on the false side of the branch
173/// while the true side continues the general flow. So the loop condition
174/// consist of a network of PHI nodes where the true incoming values expresses
175/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000176class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000177 bool SkipUniformRegions;
Tom Stellard755a4e62016-02-10 00:39:37 +0000178
Tom Stellardf8794352012-12-19 22:10:31 +0000179 Type *Boolean;
180 ConstantInt *BoolTrue;
181 ConstantInt *BoolFalse;
182 UndefValue *BoolUndef;
183
184 Function *Func;
185 Region *ParentRegion;
186
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000187 LegacyDivergenceAnalysis *DA;
Tom Stellardf8794352012-12-19 22:10:31 +0000188 DominatorTree *DT;
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000189 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000190
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000191 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000192 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000193
Tom Stellardf8794352012-12-19 22:10:31 +0000194 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000195 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000196
197 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000198 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000199
Christian Konigfc6a9852013-02-16 11:27:45 +0000200 BB2BBMap Loops;
201 PredMap LoopPreds;
202 BranchVector LoopConds;
203
204 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000205
206 void orderNodes();
207
Changpeng Fang5f915462018-05-23 18:34:48 +0000208 Loop *getAdjustedLoop(RegionNode *RN);
209 unsigned getAdjustedLoopDepth(RegionNode *RN);
210
Christian Konigfc6a9852013-02-16 11:27:45 +0000211 void analyzeLoops(RegionNode *N);
212
Christian Konigd8860992013-02-16 11:27:50 +0000213 Value *invert(Value *Condition);
214
Tom Stellard048f14f2013-02-08 22:24:37 +0000215 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000216
Christian Konigfc6a9852013-02-16 11:27:45 +0000217 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000218
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000219 void collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000220
Christian Konigfc6a9852013-02-16 11:27:45 +0000221 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000222
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000223 void delPhiValues(BasicBlock *From, BasicBlock *To);
224
225 void addPhiValues(BasicBlock *From, BasicBlock *To);
226
227 void setPhiValues();
228
Tom Stellardf8794352012-12-19 22:10:31 +0000229 void killTerminator(BasicBlock *BB);
230
Tom Stellard7370ede2013-02-08 22:24:38 +0000231 void changeExit(RegionNode *Node, BasicBlock *NewExit,
232 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000233
Tom Stellard7370ede2013-02-08 22:24:38 +0000234 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000235
Christian Konigfc6a9852013-02-16 11:27:45 +0000236 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000237
Tom Stellard7370ede2013-02-08 22:24:38 +0000238 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
239
Christian Konigfc6a9852013-02-16 11:27:45 +0000240 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000241
242 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
243
Christian Konigfc6a9852013-02-16 11:27:45 +0000244 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000245
Christian Konigfc6a9852013-02-16 11:27:45 +0000246 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
247
248 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000249
250 void createFlow();
251
Tom Stellardf8794352012-12-19 22:10:31 +0000252 void rebuildSSA();
253
254public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000255 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000256
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000257 explicit StructurizeCFG(bool SkipUniformRegions_ = false)
258 : RegionPass(ID),
259 SkipUniformRegions(SkipUniformRegions_) {
260 if (ForceSkipUniformRegions.getNumOccurrences())
261 SkipUniformRegions = ForceSkipUniformRegions.getValue();
Tom Stellard755a4e62016-02-10 00:39:37 +0000262 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
263 }
264
Craig Topper3e4c6972014-03-05 09:10:37 +0000265 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000266
Craig Topper3e4c6972014-03-05 09:10:37 +0000267 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000268
Mehdi Amini117296c2016-10-01 02:56:57 +0000269 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000270
Craig Topper3e4c6972014-03-05 09:10:37 +0000271 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000272 if (SkipUniformRegions)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000273 AU.addRequired<LegacyDivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000274 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000275 AU.addRequired<DominatorTreeWrapperPass>();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000276 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000277
Chandler Carruth73523022014-01-13 13:07:17 +0000278 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000279 RegionPass::getAnalysisUsage(AU);
280 }
Tom Stellardf8794352012-12-19 22:10:31 +0000281};
282
283} // end anonymous namespace
284
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000285char StructurizeCFG::ID = 0;
286
287INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
288 false, false)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000289INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000290INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000291INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000292INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000293INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
294 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296/// Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000297bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000298 LLVMContext &Context = R->getEntry()->getContext();
299
300 Boolean = Type::getInt1Ty(Context);
301 BoolTrue = ConstantInt::getTrue(Context);
302 BoolFalse = ConstantInt::getFalse(Context);
303 BoolUndef = UndefValue::get(Boolean);
304
305 return false;
306}
307
Changpeng Fang5f915462018-05-23 18:34:48 +0000308/// Use the exit block to determine the loop if RN is a SubRegion.
309Loop *StructurizeCFG::getAdjustedLoop(RegionNode *RN) {
310 if (RN->isSubRegion()) {
311 Region *SubRegion = RN->getNodeAs<Region>();
312 return LI->getLoopFor(SubRegion->getExit());
313 }
314
315 return LI->getLoopFor(RN->getEntry());
316}
317
318/// Use the exit block to determine the loop depth if RN is a SubRegion.
319unsigned StructurizeCFG::getAdjustedLoopDepth(RegionNode *RN) {
320 if (RN->isSubRegion()) {
321 Region *SubR = RN->getNodeAs<Region>();
322 return LI->getLoopDepth(SubR->getExit());
323 }
324
325 return LI->getLoopDepth(RN->getEntry());
326}
327
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000328/// Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000329void StructurizeCFG::orderNodes() {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000330 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
331 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000332
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000333 // The reverse post-order traversal of the list gives us an ordering close
334 // to what we want. The only problem with it is that sometimes backedges
335 // for outer loops will be visited before backedges for inner loops.
336 for (RegionNode *RN : RPOT) {
Changpeng Fang5f915462018-05-23 18:34:48 +0000337 Loop *Loop = getAdjustedLoop(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000338 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000339 }
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000340
341 unsigned CurrentLoopDepth = 0;
342 Loop *CurrentLoop = nullptr;
343 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
Changpeng Fang5f915462018-05-23 18:34:48 +0000344 RegionNode *RN = cast<RegionNode>(*I);
345 unsigned LoopDepth = getAdjustedLoopDepth(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000346
347 if (is_contained(Order, *I))
348 continue;
349
350 if (LoopDepth < CurrentLoopDepth) {
351 // Make sure we have visited all blocks in this loop before moving back to
352 // the outer loop.
353
354 auto LoopI = I;
355 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
356 LoopI++;
Changpeng Fang5f915462018-05-23 18:34:48 +0000357 if (getAdjustedLoop(cast<RegionNode>(*LoopI)) == CurrentLoop) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000358 --BlockCount;
359 Order.push_back(*LoopI);
360 }
361 }
362 }
363
Changpeng Fang5f915462018-05-23 18:34:48 +0000364 CurrentLoop = getAdjustedLoop(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000365 if (CurrentLoop)
366 LoopBlocks[CurrentLoop]--;
367
368 CurrentLoopDepth = LoopDepth;
369 Order.push_back(*I);
370 }
371
372 // This pass originally used a post-order traversal and then operated on
373 // the list in reverse. Now that we are using a reverse post-order traversal
374 // rather than re-working the whole pass to operate on the list in order,
375 // we just reverse the list and continue to operate on it in reverse.
376 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000377}
378
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000379/// Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000380void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000381 if (N->isSubRegion()) {
382 // Test for exit as back edge
383 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
384 if (Visited.count(Exit))
385 Loops[Exit] = N->getEntry();
386
387 } else {
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000388 // Test for successors as back edge
Christian Konigfc6a9852013-02-16 11:27:45 +0000389 BasicBlock *BB = N->getNodeAs<BasicBlock>();
390 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
391
Pete Cooperebcd7482015-08-06 20:22:46 +0000392 for (BasicBlock *Succ : Term->successors())
393 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000394 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000395 }
396}
397
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000398/// Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000399Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000400 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000401 if (Constant *C = dyn_cast<Constant>(Condition))
402 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000403
404 // Second: If the condition is already inverted, return the original value
Marek Olsak3c5fd142018-05-15 21:41:55 +0000405 Value *NotCondition;
406 if (match(Condition, m_Not(m_Value(NotCondition))))
407 return NotCondition;
Christian Konigd8860992013-02-16 11:27:50 +0000408
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000409 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
410 // Third: Check all the users for an invert
411 BasicBlock *Parent = Inst->getParent();
Matt Arsenault44746522017-04-24 20:25:01 +0000412 for (User *U : Condition->users())
413 if (Instruction *I = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000414 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
415 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000416
417 // Last option: Create a new instruction
418 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000419 }
420
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000421 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
422 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
423 return BinaryOperator::CreateNot(Condition,
424 Arg->getName() + ".inv",
425 EntryBlock.getTerminator());
426 }
427
428 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000429}
430
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000431/// Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000432Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
433 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000434 Value *Cond = Invert ? BoolFalse : BoolTrue;
435 if (Term->isConditional()) {
436 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000437
Aaron Ballman19978552013-06-04 01:03:03 +0000438 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000439 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000440 }
441 return Cond;
442}
443
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000444/// Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000445void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000446 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000447 BasicBlock *BB = N->getEntry();
448 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000449 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000450
Justin Lebar3aec10c2016-11-28 18:50:03 +0000451 for (BasicBlock *P : predecessors(BB)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000452 // Ignore it if it's a branch from outside into our region entry
Justin Lebar3aec10c2016-11-28 18:50:03 +0000453 if (!ParentRegion->contains(P))
Tom Stellard048f14f2013-02-08 22:24:37 +0000454 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000455
Justin Lebar3aec10c2016-11-28 18:50:03 +0000456 Region *R = RI->getRegionFor(P);
Tom Stellard048f14f2013-02-08 22:24:37 +0000457 if (R == ParentRegion) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000458 // It's a top level block in our region
Justin Lebar3aec10c2016-11-28 18:50:03 +0000459 BranchInst *Term = cast<BranchInst>(P->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000460 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
461 BasicBlock *Succ = Term->getSuccessor(i);
462 if (Succ != BB)
463 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000464
Justin Lebar3aec10c2016-11-28 18:50:03 +0000465 if (Visited.count(P)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000466 // Normal forward edge
467 if (Term->isConditional()) {
468 // Try to treat it like an ELSE block
469 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000470 if (Visited.count(Other) && !Loops.count(Other) &&
Justin Lebar3aec10c2016-11-28 18:50:03 +0000471 !Pred.count(Other) && !Pred.count(P)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000472
Tom Stellard048f14f2013-02-08 22:24:37 +0000473 Pred[Other] = BoolFalse;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000474 Pred[P] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000475 continue;
476 }
477 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000478 Pred[P] = buildCondition(Term, i, false);
Tom Stellard048f14f2013-02-08 22:24:37 +0000479 } else {
480 // Back edge
Justin Lebar3aec10c2016-11-28 18:50:03 +0000481 LPred[P] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000482 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000483 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000484 } else {
Tom Stellard048f14f2013-02-08 22:24:37 +0000485 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000486 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000487 R = R->getParent();
488
489 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000490 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000491 continue;
492
493 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000494 if (Visited.count(Entry))
495 Pred[Entry] = BoolTrue;
496 else
497 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000498 }
499 }
500}
501
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000502/// Collect various loop and predicate infos
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000503void StructurizeCFG::collectInfos() {
504 // Reset predicate
505 Predicates.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000506
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000507 // and loop infos
508 Loops.clear();
509 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000510
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000511 // Reset the visited nodes
512 Visited.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000513
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000514 for (RegionNode *RN : reverse(Order)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000515 LLVM_DEBUG(dbgs() << "Visiting: "
516 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
517 << RN->getEntry()->getName() << " Loop Depth: "
518 << LI->getLoopDepth(RN->getEntry()) << "\n");
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000519
520 // Analyze all the conditions leading to a node
521 gatherPredicates(RN);
522
523 // Remember that we've seen this node
524 Visited.insert(RN->getEntry());
525
526 // Find the last back edges
527 analyzeLoops(RN);
528 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000529}
530
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000531/// Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000532void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000533 BranchVector &Conds = Loops ? LoopConds : Conditions;
534 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000535 SSAUpdater PhiInserter;
536
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000537 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000538 assert(Term->isConditional());
539
Christian Konigfc6a9852013-02-16 11:27:45 +0000540 BasicBlock *Parent = Term->getParent();
541 BasicBlock *SuccTrue = Term->getSuccessor(0);
542 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000543
Christian Konigb5d88662013-02-16 11:27:40 +0000544 PhiInserter.Initialize(Boolean, "");
545 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000546 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000547
Christian Konigfc6a9852013-02-16 11:27:45 +0000548 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000549
550 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000551 Dominator.addBlock(Parent);
Christian Konigb5d88662013-02-16 11:27:40 +0000552
Craig Topperf40110f2014-04-25 05:29:35 +0000553 Value *ParentValue = nullptr;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000554 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
555 BasicBlock *BB = BBAndPred.first;
556 Value *Pred = BBAndPred.second;
Tom Stellard048f14f2013-02-08 22:24:37 +0000557
Justin Lebar3aec10c2016-11-28 18:50:03 +0000558 if (BB == Parent) {
559 ParentValue = Pred;
Christian Konigb5d88662013-02-16 11:27:40 +0000560 break;
561 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000562 PhiInserter.AddAvailableValue(BB, Pred);
563 Dominator.addAndRememberBlock(BB);
Tom Stellard048f14f2013-02-08 22:24:37 +0000564 }
565
Christian Konigb5d88662013-02-16 11:27:40 +0000566 if (ParentValue) {
567 Term->setCondition(ParentValue);
568 } else {
Justin Lebar62c20d82016-11-28 18:49:59 +0000569 if (!Dominator.resultIsRememberedBlock())
570 PhiInserter.AddAvailableValue(Dominator.result(), Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000571
Tom Stellard048f14f2013-02-08 22:24:37 +0000572 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000573 }
Tom Stellardf8794352012-12-19 22:10:31 +0000574 }
575}
576
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000577/// Remove all PHI values coming from "From" into "To" and remember
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000578/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000579void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000580 PhiMap &Map = DeletedPhis[To];
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000581 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000582 while (Phi.getBasicBlockIndex(From) != -1) {
583 Value *Deleted = Phi.removeIncomingValue(From, false);
584 Map[&Phi].push_back(std::make_pair(From, Deleted));
585 }
586 }
587}
588
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000589/// Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000590void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000591 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000592 Value *Undef = UndefValue::get(Phi.getType());
593 Phi.addIncoming(Undef, From);
594 }
595 AddedPhis[To].push_back(From);
596}
597
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000598/// Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000599void StructurizeCFG::setPhiValues() {
Nicolai Haehnle08230502018-10-17 15:37:41 +0000600 SmallVector<PHINode *, 8> InsertedPhis;
601 SSAUpdater Updater(&InsertedPhis);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000602 for (const auto &AddedPhi : AddedPhis) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000603 BasicBlock *To = AddedPhi.first;
604 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000605
606 if (!DeletedPhis.count(To))
607 continue;
608
609 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000610 for (const auto &PI : Map) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000611 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000612 Value *Undef = UndefValue::get(Phi->getType());
613 Updater.Initialize(Phi->getType(), "");
614 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
615 Updater.AddAvailableValue(To, Undef);
616
Christian Konig0bccf9d2013-02-16 11:27:35 +0000617 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000618 Dominator.addBlock(To);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000619 for (const auto &VI : PI.second) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000620 Updater.AddAvailableValue(VI.first, VI.second);
Justin Lebar62c20d82016-11-28 18:49:59 +0000621 Dominator.addAndRememberBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000622 }
623
Justin Lebar62c20d82016-11-28 18:49:59 +0000624 if (!Dominator.resultIsRememberedBlock())
625 Updater.AddAvailableValue(Dominator.result(), Undef);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000626
Benjamin Kramer135f7352016-06-26 12:28:59 +0000627 for (BasicBlock *FI : From) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000628 int Idx = Phi->getBasicBlockIndex(FI);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000629 assert(Idx != -1);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000630 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000631 }
632 }
633
634 DeletedPhis.erase(To);
635 }
636 assert(DeletedPhis.empty());
Nicolai Haehnle08230502018-10-17 15:37:41 +0000637
638 // Simplify any phis inserted by the SSAUpdater if possible
639 bool Changed;
640 do {
641 Changed = false;
642
643 SimplifyQuery Q(Func->getParent()->getDataLayout());
644 Q.DT = DT;
645 for (size_t i = 0; i < InsertedPhis.size(); ++i) {
646 PHINode *Phi = InsertedPhis[i];
647 if (Value *V = SimplifyInstruction(Phi, Q)) {
648 Phi->replaceAllUsesWith(V);
649 Phi->eraseFromParent();
650 InsertedPhis[i] = InsertedPhis.back();
651 InsertedPhis.pop_back();
652 i--;
653 Changed = true;
654 }
655 }
656 } while (Changed);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000657}
658
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000659/// Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000660void StructurizeCFG::killTerminator(BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000661 Instruction *Term = BB->getTerminator();
Tom Stellardf8794352012-12-19 22:10:31 +0000662 if (!Term)
663 return;
664
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000665 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000666 SI != SE; ++SI)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000667 delPhiValues(BB, *SI);
Tom Stellardf8794352012-12-19 22:10:31 +0000668
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000669 if (DA)
670 DA->removeValue(Term);
Tom Stellardf8794352012-12-19 22:10:31 +0000671 Term->eraseFromParent();
672}
673
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000674/// Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000675void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
676 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000677 if (Node->isSubRegion()) {
678 Region *SubRegion = Node->getNodeAs<Region>();
679 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000680 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000681
Tom Stellard7370ede2013-02-08 22:24:38 +0000682 // Find all the edges from the sub region to the exit
Justin Lebar3aec10c2016-11-28 18:50:03 +0000683 for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
684 // Incrememt BBI before mucking with BB's terminator.
685 BasicBlock *BB = *BBI++;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000686
Tom Stellard7370ede2013-02-08 22:24:38 +0000687 if (!SubRegion->contains(BB))
688 continue;
689
690 // Modify the edges to point to the new exit
691 delPhiValues(BB, OldExit);
692 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
693 addPhiValues(BB, NewExit);
694
695 // Find the new dominator (if requested)
696 if (IncludeDominator) {
697 if (!Dominator)
698 Dominator = BB;
699 else
700 Dominator = DT->findNearestCommonDominator(Dominator, BB);
701 }
Tom Stellardf8794352012-12-19 22:10:31 +0000702 }
703
Tom Stellard7370ede2013-02-08 22:24:38 +0000704 // Change the dominator (if requested)
705 if (Dominator)
706 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000707
Tom Stellard7370ede2013-02-08 22:24:38 +0000708 // Update the region info
709 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000710 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000711 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
712 killTerminator(BB);
713 BranchInst::Create(NewExit, BB);
714 addPhiValues(BB, NewExit);
715 if (IncludeDominator)
716 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000717 }
Tom Stellardf8794352012-12-19 22:10:31 +0000718}
719
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000720/// Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000721BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000722 LLVMContext &Context = Func->getContext();
723 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000724 Order.back()->getEntry();
Tom Stellardf8794352012-12-19 22:10:31 +0000725 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
726 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000727 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000728 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000729 return Flow;
730}
731
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000732/// Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000733BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000734 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000735
Christian Konigfc6a9852013-02-16 11:27:45 +0000736 if (!PrevNode->isSubRegion()) {
737 killTerminator(Entry);
738 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
739 return Entry;
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000740 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000741
Christian Konigfc6a9852013-02-16 11:27:45 +0000742 // create a new flow node
743 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000744
Christian Konigfc6a9852013-02-16 11:27:45 +0000745 // and wire it up
746 changeExit(PrevNode, Flow, true);
747 PrevNode = ParentRegion->getBBNode(Flow);
748 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000749}
750
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000751/// Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000752BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
753 bool ExitUseAllowed) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000754 if (!Order.empty() || !ExitUseAllowed)
755 return getNextFlow(Flow);
756
757 BasicBlock *Exit = ParentRegion->getExit();
758 DT->changeImmediateDominator(Exit, Flow);
759 addPhiValues(Flow, Exit);
760 return Exit;
Tom Stellard7370ede2013-02-08 22:24:38 +0000761}
762
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000763/// Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000764void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000765 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
766 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000767}
768
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000769/// Does BB dominate all the predicates of Node?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000770bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000771 BBPredicates &Preds = Predicates[Node->getEntry()];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000772 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
773 return DT->dominates(BB, Pred.first);
774 });
Tom Stellard7370ede2013-02-08 22:24:38 +0000775}
776
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000777/// Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000778bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000779 BBPredicates &Preds = Predicates[Node->getEntry()];
780 bool Dominated = false;
781
782 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000783 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000784 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000785
Justin Lebar3aec10c2016-11-28 18:50:03 +0000786 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
787 BasicBlock *BB = Pred.first;
788 Value *V = Pred.second;
Tom Stellardf8794352012-12-19 22:10:31 +0000789
Justin Lebar3aec10c2016-11-28 18:50:03 +0000790 if (V != BoolTrue)
Tom Stellardf8794352012-12-19 22:10:31 +0000791 return false;
792
Justin Lebar3aec10c2016-11-28 18:50:03 +0000793 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000794 Dominated = true;
795 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000796
797 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000798 return Dominated;
799}
800
Tom Stellard7370ede2013-02-08 22:24:38 +0000801/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000802void StructurizeCFG::wireFlow(bool ExitUseAllowed,
803 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000804 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000805 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000806
Christian Konigfc6a9852013-02-16 11:27:45 +0000807 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000808 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000809 if (PrevNode) {
810 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000811 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000812 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000813 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000814 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000815 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000816
Tom Stellard7370ede2013-02-08 22:24:38 +0000817 // Insert extra postfix node (or use exit instead)
818 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000819 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000820
821 // let it point to entry and next block
822 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
823 addPhiValues(Flow, Entry);
824 DT->changeImmediateDominator(Entry, Flow);
825
Christian Konigfc6a9852013-02-16 11:27:45 +0000826 PrevNode = Node;
827 while (!Order.empty() && !Visited.count(LoopEnd) &&
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000828 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000829 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000830 }
831
Christian Konigfc6a9852013-02-16 11:27:45 +0000832 changeExit(PrevNode, Next, false);
833 setPrevNode(Next);
834 }
835}
836
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000837void StructurizeCFG::handleLoops(bool ExitUseAllowed,
838 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000839 RegionNode *Node = Order.back();
Christian Konigfc6a9852013-02-16 11:27:45 +0000840 BasicBlock *LoopStart = Node->getEntry();
841
842 if (!Loops.count(LoopStart)) {
843 wireFlow(ExitUseAllowed, LoopEnd);
844 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000845 }
846
Christian Konigfc6a9852013-02-16 11:27:45 +0000847 if (!isPredictableTrue(Node))
848 LoopStart = needPrefix(true);
849
850 LoopEnd = Loops[Node->getEntry()];
851 wireFlow(false, LoopEnd);
852 while (!Visited.count(LoopEnd)) {
853 handleLoops(false, LoopEnd);
854 }
855
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000856 // If the start of the loop is the entry block, we can't branch to it so
857 // insert a new dummy entry block.
858 Function *LoopFunc = LoopStart->getParent();
859 if (LoopStart == &LoopFunc->getEntryBlock()) {
860 LoopStart->setName("entry.orig");
861
862 BasicBlock *NewEntry =
863 BasicBlock::Create(LoopStart->getContext(),
864 "entry",
865 LoopFunc,
866 LoopStart);
867 BranchInst::Create(LoopStart, NewEntry);
Serge Pavlov0668cd22017-01-10 02:50:47 +0000868 DT->setNewRoot(NewEntry);
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000869 }
870
Christian Konigfc6a9852013-02-16 11:27:45 +0000871 // Create an extra loop end node
872 LoopEnd = needPrefix(false);
873 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
874 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
875 BoolUndef, LoopEnd));
876 addPhiValues(LoopEnd, LoopStart);
877 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000878}
879
Tom Stellardf8794352012-12-19 22:10:31 +0000880/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000881/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000882void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000883 BasicBlock *Exit = ParentRegion->getExit();
884 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
885
Tom Stellardf8794352012-12-19 22:10:31 +0000886 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000887 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000888 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000889 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000890
Craig Topperf40110f2014-04-25 05:29:35 +0000891 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000892 Visited.clear();
893
Tom Stellardf8794352012-12-19 22:10:31 +0000894 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000895 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000896 }
897
Christian Konigfc6a9852013-02-16 11:27:45 +0000898 if (PrevNode)
899 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000900 else
901 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000902}
903
Tom Stellardf8794352012-12-19 22:10:31 +0000904/// Handle a rare case where the disintegrated nodes instructions
Hiroshi Inouef2096492018-06-14 05:41:49 +0000905/// no longer dominate all their uses. Not sure if this is really necessary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000906void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000907 SSAUpdater Updater;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000908 for (BasicBlock *BB : ParentRegion->blocks())
909 for (Instruction &I : *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000910 bool Initialized = false;
Justin Lebar96e29152016-11-29 21:49:02 +0000911 // We may modify the use list as we iterate over it, so be careful to
912 // compute the next element in the use list at the top of the loop.
913 for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
914 Use &U = *UI++;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000915 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000916 if (User->getParent() == BB) {
917 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000918 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000919 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000920 continue;
921 }
922
Justin Lebar3aec10c2016-11-28 18:50:03 +0000923 if (DT->dominates(&I, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000924 continue;
925
926 if (!Initialized) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000927 Value *Undef = UndefValue::get(I.getType());
928 Updater.Initialize(I.getType(), "");
Tom Stellardf8794352012-12-19 22:10:31 +0000929 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000930 Updater.AddAvailableValue(BB, &I);
Tom Stellardf8794352012-12-19 22:10:31 +0000931 Initialized = true;
932 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000933 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000934 }
935 }
Tom Stellardf8794352012-12-19 22:10:31 +0000936}
937
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000938static bool hasOnlyUniformBranches(Region *R, unsigned UniformMDKindID,
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000939 const LegacyDivergenceAnalysis &DA) {
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000940 for (auto E : R->elements()) {
941 if (!E->isSubRegion()) {
942 auto Br = dyn_cast<BranchInst>(E->getEntry()->getTerminator());
943 if (!Br || !Br->isConditional())
944 continue;
Tom Stellard755a4e62016-02-10 00:39:37 +0000945
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000946 if (!DA.isUniform(Br))
947 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000948 LLVM_DEBUG(dbgs() << "BB: " << Br->getParent()->getName()
949 << " has uniform terminator\n");
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000950 } else {
951 // Explicitly refuse to treat regions as uniform if they have non-uniform
952 // subregions. We cannot rely on DivergenceAnalysis for branches in
953 // subregions because those branches may have been removed and re-created,
954 // so we look for our metadata instead.
955 //
956 // Warning: It would be nice to treat regions as uniform based only on
957 // their direct child basic blocks' terminators, regardless of whether
958 // subregions are uniform or not. However, this requires a very careful
959 // look at SIAnnotateControlFlow to make sure nothing breaks there.
960 for (auto BB : E->getNodeAs<Region>()->blocks()) {
961 auto Br = dyn_cast<BranchInst>(BB->getTerminator());
962 if (!Br || !Br->isConditional())
963 continue;
964
965 if (!Br->getMetadata(UniformMDKindID))
966 return false;
967 }
968 }
Tom Stellard755a4e62016-02-10 00:39:37 +0000969 }
970 return true;
971}
972
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000973/// Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000974bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000975 if (R->isTopLevelRegion())
976 return false;
977
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000978 DA = nullptr;
979
Tom Stellard755a4e62016-02-10 00:39:37 +0000980 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000981 // TODO: We could probably be smarter here with how we handle sub-regions.
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000982 // We currently rely on the fact that metadata is set by earlier invocations
983 // of the pass on sub-regions, and that this metadata doesn't get lost --
984 // but we shouldn't rely on metadata for correctness!
985 unsigned UniformMDKindID =
986 R->getEntry()->getContext().getMDKindID("structurizecfg.uniform");
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000987 DA = &getAnalysis<LegacyDivergenceAnalysis>();
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000988
989 if (hasOnlyUniformBranches(R, UniformMDKindID, *DA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000990 LLVM_DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R
991 << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000992
993 // Mark all direct child block terminators as having been treated as
994 // uniform. To account for a possible future in which non-uniform
995 // sub-regions are treated more cleverly, indirect children are not
996 // marked as uniform.
997 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +0000998 for (RegionNode *E : R->elements()) {
999 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +00001000 continue;
1001
Justin Lebar1b60d702016-11-22 23:13:37 +00001002 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +00001003 Term->setMetadata(UniformMDKindID, MD);
Nicolai Haehnle05b127d2016-04-14 17:42:35 +00001004 }
1005
Tom Stellard755a4e62016-02-10 00:39:37 +00001006 return false;
1007 }
1008 }
1009
Tom Stellardf8794352012-12-19 22:10:31 +00001010 Func = R->getEntry()->getParent();
1011 ParentRegion = R;
1012
Chandler Carruth73523022014-01-13 13:07:17 +00001013 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +00001014 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +00001015
1016 orderNodes();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +00001017 collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +00001018 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +00001019 insertConditions(false);
1020 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +00001021 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +00001022 rebuildSSA();
1023
Tom Stellard048f14f2013-02-08 22:24:37 +00001024 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +00001025 Order.clear();
1026 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +00001027 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +00001028 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +00001029 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +00001030 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +00001031 Loops.clear();
1032 LoopPreds.clear();
1033 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +00001034
1035 return true;
1036}
1037
Tom Stellard755a4e62016-02-10 00:39:37 +00001038Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
1039 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +00001040}