blob: f58f79f8b1448709b71604abc1bb2cacb43e7e7d [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 Haehnle35617ed2018-08-30 14:21:36 +000016#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +000017#include "llvm/Analysis/LoopInfo.h"
Tom Stellardf8794352012-12-19 22:10:31 +000018#include "llvm/Analysis/RegionInfo.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000019#include "llvm/Analysis/RegionIterator.h"
Tom Stellardf8794352012-12-19 22:10:31 +000020#include "llvm/Analysis/RegionPass.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000021#include "llvm/IR/Argument.h"
22#include "llvm/IR/BasicBlock.h"
23#include "llvm/IR/CFG.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000033#include "llvm/IR/Type.h"
34#include "llvm/IR/Use.h"
35#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
37#include "llvm/Pass.h"
38#include "llvm/Support/Casting.h"
Tom Stellard071ec902015-02-04 20:49:44 +000039#include "llvm/Support/Debug.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000040#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000041#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include "llvm/Transforms/Scalar.h"
David Blaikiea373d182018-03-28 17:44:36 +000043#include "llvm/Transforms/Utils.h"
Benjamin Kramerd78bb462013-05-23 17:10:37 +000044#include "llvm/Transforms/Utils/SSAUpdater.h"
Eugene Zelenko99241d72017-10-20 21:47:29 +000045#include <algorithm>
46#include <cassert>
47#include <utility>
Tom Stellardf8794352012-12-19 22:10:31 +000048
49using namespace llvm;
Christian Konigd8860992013-02-16 11:27:50 +000050using namespace llvm::PatternMatch;
Tom Stellardf8794352012-12-19 22:10:31 +000051
Chandler Carruth964daaa2014-04-22 02:55:47 +000052#define DEBUG_TYPE "structurizecfg"
53
Eugene Zelenko99241d72017-10-20 21:47:29 +000054// The name for newly created blocks.
55static const char *const FlowBlockName = "Flow";
56
Tom Stellardf8794352012-12-19 22:10:31 +000057namespace {
58
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +000059static cl::opt<bool> ForceSkipUniformRegions(
60 "structurizecfg-skip-uniform-regions",
61 cl::Hidden,
62 cl::desc("Force whether the StructurizeCFG pass skips uniform regions"),
63 cl::init(false));
64
Tom Stellardf8794352012-12-19 22:10:31 +000065// Definition of the complex types used in this pass.
66
Eugene Zelenko99241d72017-10-20 21:47:29 +000067using BBValuePair = std::pair<BasicBlock *, Value *>;
Tom Stellardf8794352012-12-19 22:10:31 +000068
Eugene Zelenko99241d72017-10-20 21:47:29 +000069using RNVector = SmallVector<RegionNode *, 8>;
70using BBVector = SmallVector<BasicBlock *, 8>;
71using BranchVector = SmallVector<BranchInst *, 8>;
72using BBValueVector = SmallVector<BBValuePair, 2>;
Tom Stellardf8794352012-12-19 22:10:31 +000073
Eugene Zelenko99241d72017-10-20 21:47:29 +000074using BBSet = SmallPtrSet<BasicBlock *, 8>;
Tom Stellard048f14f2013-02-08 22:24:37 +000075
Eugene Zelenko99241d72017-10-20 21:47:29 +000076using PhiMap = MapVector<PHINode *, BBValueVector>;
77using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;
Christian Konig90b45122013-03-26 10:24:20 +000078
Eugene Zelenko99241d72017-10-20 21:47:29 +000079using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
80using BBPredicates = DenseMap<BasicBlock *, Value *>;
81using PredMap = DenseMap<BasicBlock *, BBPredicates>;
82using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;
Tom Stellardf8794352012-12-19 22:10:31 +000083
Justin Lebar62c20d82016-11-28 18:49:59 +000084/// Finds the nearest common dominator of a set of BasicBlocks.
Christian Konigd08e3d72013-02-16 11:27:29 +000085///
Justin Lebar62c20d82016-11-28 18:49:59 +000086/// For every BB you add to the set, you can specify whether we "remember" the
87/// block. When you get the common dominator, you can also ask whether it's one
88/// of the blocks we remembered.
Christian Konigd08e3d72013-02-16 11:27:29 +000089class NearestCommonDominator {
Christian Konigd08e3d72013-02-16 11:27:29 +000090 DominatorTree *DT;
Justin Lebar62c20d82016-11-28 18:49:59 +000091 BasicBlock *Result = nullptr;
92 bool ResultIsRemembered = false;
Christian Konigd08e3d72013-02-16 11:27:29 +000093
Justin Lebar62c20d82016-11-28 18:49:59 +000094 /// Add BB to the resulting dominator.
95 void addBlock(BasicBlock *BB, bool Remember) {
Craig Topperf40110f2014-04-25 05:29:35 +000096 if (!Result) {
Christian Konigd08e3d72013-02-16 11:27:29 +000097 Result = BB;
Justin Lebar62c20d82016-11-28 18:49:59 +000098 ResultIsRemembered = Remember;
Christian Konigd08e3d72013-02-16 11:27:29 +000099 return;
100 }
101
Justin Lebar62c20d82016-11-28 18:49:59 +0000102 BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
103 if (NewResult != Result)
104 ResultIsRemembered = false;
105 if (NewResult == BB)
106 ResultIsRemembered |= Remember;
107 Result = NewResult;
Christian Konigd08e3d72013-02-16 11:27:29 +0000108 }
109
Justin Lebar62c20d82016-11-28 18:49:59 +0000110public:
111 explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}
112
113 void addBlock(BasicBlock *BB) {
114 addBlock(BB, /* Remember = */ false);
Christian Konigd08e3d72013-02-16 11:27:29 +0000115 }
116
Justin Lebar62c20d82016-11-28 18:49:59 +0000117 void addAndRememberBlock(BasicBlock *BB) {
118 addBlock(BB, /* Remember = */ true);
Christian Konigd08e3d72013-02-16 11:27:29 +0000119 }
Justin Lebar62c20d82016-11-28 18:49:59 +0000120
121 /// Get the nearest common dominator of all the BBs added via addBlock() and
122 /// addAndRememberBlock().
123 BasicBlock *result() { return Result; }
124
125 /// Is the BB returned by getResult() one of the blocks we added to the set
126 /// with addAndRememberBlock()?
127 bool resultIsRememberedBlock() { return ResultIsRemembered; }
Christian Konigd08e3d72013-02-16 11:27:29 +0000128};
129
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000130/// Transforms the control flow graph on one single entry/exit region
Tom Stellardf8794352012-12-19 22:10:31 +0000131/// at a time.
132///
133/// After the transform all "If"/"Then"/"Else" style control flow looks like
134/// this:
135///
136/// \verbatim
137/// 1
138/// ||
139/// | |
140/// 2 |
141/// | /
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000142/// |/
Tom Stellardf8794352012-12-19 22:10:31 +0000143/// 3
144/// || Where:
145/// | | 1 = "If" block, calculates the condition
146/// 4 | 2 = "Then" subregion, runs if the condition is true
147/// | / 3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
148/// |/ 4 = "Else" optional subregion, runs if the condition is false
149/// 5 5 = "End" block, also rejoins the control flow
150/// \endverbatim
151///
152/// Control flow is expressed as a branch where the true exit goes into the
153/// "Then"/"Else" region, while the false exit skips the region
154/// The condition for the optional "Else" region is expressed as a PHI node.
Simon Pilgrim7d18a702016-11-20 13:19:49 +0000155/// The incoming values of the PHI node are true for the "If" edge and false
Tom Stellardf8794352012-12-19 22:10:31 +0000156/// for the "Then" edge.
157///
158/// Additionally to that even complicated loops look like this:
159///
160/// \verbatim
161/// 1
162/// ||
163/// | |
164/// 2 ^ Where:
165/// | / 1 = "Entry" block
166/// |/ 2 = "Loop" optional subregion, with all exits at "Flow" block
167/// 3 3 = "Flow" block, with back edge to entry block
168/// |
169/// \endverbatim
170///
171/// The back edge of the "Flow" block is always on the false side of the branch
172/// while the true side continues the general flow. So the loop condition
173/// consist of a network of PHI nodes where the true incoming values expresses
174/// breaks and the false values expresses continue states.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000175class StructurizeCFG : public RegionPass {
Tom Stellard755a4e62016-02-10 00:39:37 +0000176 bool SkipUniformRegions;
Tom Stellard755a4e62016-02-10 00:39:37 +0000177
Tom Stellardf8794352012-12-19 22:10:31 +0000178 Type *Boolean;
179 ConstantInt *BoolTrue;
180 ConstantInt *BoolFalse;
181 UndefValue *BoolUndef;
182
183 Function *Func;
184 Region *ParentRegion;
185
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000186 LegacyDivergenceAnalysis *DA;
Tom Stellardf8794352012-12-19 22:10:31 +0000187 DominatorTree *DT;
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000188 LoopInfo *LI;
Tom Stellardf8794352012-12-19 22:10:31 +0000189
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000190 SmallVector<RegionNode *, 8> Order;
Tom Stellard7370ede2013-02-08 22:24:38 +0000191 BBSet Visited;
Christian Konigfc6a9852013-02-16 11:27:45 +0000192
Tom Stellardf8794352012-12-19 22:10:31 +0000193 BBPhiMap DeletedPhis;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000194 BB2BBVecMap AddedPhis;
Christian Konigfc6a9852013-02-16 11:27:45 +0000195
196 PredMap Predicates;
Tom Stellard048f14f2013-02-08 22:24:37 +0000197 BranchVector Conditions;
Tom Stellardf8794352012-12-19 22:10:31 +0000198
Christian Konigfc6a9852013-02-16 11:27:45 +0000199 BB2BBMap Loops;
200 PredMap LoopPreds;
201 BranchVector LoopConds;
202
203 RegionNode *PrevNode;
Tom Stellardf8794352012-12-19 22:10:31 +0000204
205 void orderNodes();
206
Changpeng Fang5f915462018-05-23 18:34:48 +0000207 Loop *getAdjustedLoop(RegionNode *RN);
208 unsigned getAdjustedLoopDepth(RegionNode *RN);
209
Christian Konigfc6a9852013-02-16 11:27:45 +0000210 void analyzeLoops(RegionNode *N);
211
Christian Konigd8860992013-02-16 11:27:50 +0000212 Value *invert(Value *Condition);
213
Tom Stellard048f14f2013-02-08 22:24:37 +0000214 Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);
Tom Stellardf8794352012-12-19 22:10:31 +0000215
Christian Konigfc6a9852013-02-16 11:27:45 +0000216 void gatherPredicates(RegionNode *N);
Tom Stellardf8794352012-12-19 22:10:31 +0000217
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000218 void collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000219
Christian Konigfc6a9852013-02-16 11:27:45 +0000220 void insertConditions(bool Loops);
Tom Stellard048f14f2013-02-08 22:24:37 +0000221
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000222 void delPhiValues(BasicBlock *From, BasicBlock *To);
223
224 void addPhiValues(BasicBlock *From, BasicBlock *To);
225
226 void setPhiValues();
227
Tom Stellardf8794352012-12-19 22:10:31 +0000228 void killTerminator(BasicBlock *BB);
229
Tom Stellard7370ede2013-02-08 22:24:38 +0000230 void changeExit(RegionNode *Node, BasicBlock *NewExit,
231 bool IncludeDominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000232
Tom Stellard7370ede2013-02-08 22:24:38 +0000233 BasicBlock *getNextFlow(BasicBlock *Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000234
Christian Konigfc6a9852013-02-16 11:27:45 +0000235 BasicBlock *needPrefix(bool NeedEmpty);
Tom Stellardf8794352012-12-19 22:10:31 +0000236
Tom Stellard7370ede2013-02-08 22:24:38 +0000237 BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);
238
Christian Konigfc6a9852013-02-16 11:27:45 +0000239 void setPrevNode(BasicBlock *BB);
Tom Stellard7370ede2013-02-08 22:24:38 +0000240
241 bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);
242
Christian Konigfc6a9852013-02-16 11:27:45 +0000243 bool isPredictableTrue(RegionNode *Node);
Tom Stellard7370ede2013-02-08 22:24:38 +0000244
Christian Konigfc6a9852013-02-16 11:27:45 +0000245 void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);
246
247 void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);
Tom Stellardf8794352012-12-19 22:10:31 +0000248
249 void createFlow();
250
Tom Stellardf8794352012-12-19 22:10:31 +0000251 void rebuildSSA();
252
253public:
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000254 static char ID;
Tom Stellardf8794352012-12-19 22:10:31 +0000255
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000256 explicit StructurizeCFG(bool SkipUniformRegions_ = false)
257 : RegionPass(ID),
258 SkipUniformRegions(SkipUniformRegions_) {
259 if (ForceSkipUniformRegions.getNumOccurrences())
260 SkipUniformRegions = ForceSkipUniformRegions.getValue();
Tom Stellard755a4e62016-02-10 00:39:37 +0000261 initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
262 }
263
Craig Topper3e4c6972014-03-05 09:10:37 +0000264 bool doInitialization(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000265
Craig Topper3e4c6972014-03-05 09:10:37 +0000266 bool runOnRegion(Region *R, RGPassManager &RGM) override;
Tom Stellardf8794352012-12-19 22:10:31 +0000267
Mehdi Amini117296c2016-10-01 02:56:57 +0000268 StringRef getPassName() const override { return "Structurize control flow"; }
Tom Stellardf8794352012-12-19 22:10:31 +0000269
Craig Topper3e4c6972014-03-05 09:10:37 +0000270 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tom Stellard755a4e62016-02-10 00:39:37 +0000271 if (SkipUniformRegions)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000272 AU.addRequired<LegacyDivergenceAnalysis>();
Tom Stellardd3e916e2013-10-02 17:04:59 +0000273 AU.addRequiredID(LowerSwitchID);
Chandler Carruth73523022014-01-13 13:07:17 +0000274 AU.addRequired<DominatorTreeWrapperPass>();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000275 AU.addRequired<LoopInfoWrapperPass>();
Justin Lebar23aaf602016-11-22 23:14:07 +0000276
Chandler Carruth73523022014-01-13 13:07:17 +0000277 AU.addPreserved<DominatorTreeWrapperPass>();
Tom Stellardf8794352012-12-19 22:10:31 +0000278 RegionPass::getAnalysisUsage(AU);
279 }
Tom Stellardf8794352012-12-19 22:10:31 +0000280};
281
282} // end anonymous namespace
283
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000284char StructurizeCFG::ID = 0;
285
286INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
287 false, false)
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000288INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
Tom Stellardd3e916e2013-10-02 17:04:59 +0000289INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
Chandler Carruth73523022014-01-13 13:07:17 +0000290INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000291INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000292INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
293 false, false)
Tom Stellardf8794352012-12-19 22:10:31 +0000294
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295/// Initialize the types and constants used in the pass
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000296bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000297 LLVMContext &Context = R->getEntry()->getContext();
298
299 Boolean = Type::getInt1Ty(Context);
300 BoolTrue = ConstantInt::getTrue(Context);
301 BoolFalse = ConstantInt::getFalse(Context);
302 BoolUndef = UndefValue::get(Boolean);
303
304 return false;
305}
306
Changpeng Fang5f915462018-05-23 18:34:48 +0000307/// Use the exit block to determine the loop if RN is a SubRegion.
308Loop *StructurizeCFG::getAdjustedLoop(RegionNode *RN) {
309 if (RN->isSubRegion()) {
310 Region *SubRegion = RN->getNodeAs<Region>();
311 return LI->getLoopFor(SubRegion->getExit());
312 }
313
314 return LI->getLoopFor(RN->getEntry());
315}
316
317/// Use the exit block to determine the loop depth if RN is a SubRegion.
318unsigned StructurizeCFG::getAdjustedLoopDepth(RegionNode *RN) {
319 if (RN->isSubRegion()) {
320 Region *SubR = RN->getNodeAs<Region>();
321 return LI->getLoopDepth(SubR->getExit());
322 }
323
324 return LI->getLoopDepth(RN->getEntry());
325}
326
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000327/// Build up the general order of nodes
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000328void StructurizeCFG::orderNodes() {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000329 ReversePostOrderTraversal<Region*> RPOT(ParentRegion);
330 SmallDenseMap<Loop*, unsigned, 8> LoopBlocks;
Tom Stellard071ec902015-02-04 20:49:44 +0000331
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000332 // The reverse post-order traversal of the list gives us an ordering close
333 // to what we want. The only problem with it is that sometimes backedges
334 // for outer loops will be visited before backedges for inner loops.
335 for (RegionNode *RN : RPOT) {
Changpeng Fang5f915462018-05-23 18:34:48 +0000336 Loop *Loop = getAdjustedLoop(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000337 ++LoopBlocks[Loop];
Tom Stellardf8794352012-12-19 22:10:31 +0000338 }
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000339
340 unsigned CurrentLoopDepth = 0;
341 Loop *CurrentLoop = nullptr;
342 for (auto I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
Changpeng Fang5f915462018-05-23 18:34:48 +0000343 RegionNode *RN = cast<RegionNode>(*I);
344 unsigned LoopDepth = getAdjustedLoopDepth(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000345
346 if (is_contained(Order, *I))
347 continue;
348
349 if (LoopDepth < CurrentLoopDepth) {
350 // Make sure we have visited all blocks in this loop before moving back to
351 // the outer loop.
352
353 auto LoopI = I;
354 while (unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
355 LoopI++;
Changpeng Fang5f915462018-05-23 18:34:48 +0000356 if (getAdjustedLoop(cast<RegionNode>(*LoopI)) == CurrentLoop) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000357 --BlockCount;
358 Order.push_back(*LoopI);
359 }
360 }
361 }
362
Changpeng Fang5f915462018-05-23 18:34:48 +0000363 CurrentLoop = getAdjustedLoop(RN);
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000364 if (CurrentLoop)
365 LoopBlocks[CurrentLoop]--;
366
367 CurrentLoopDepth = LoopDepth;
368 Order.push_back(*I);
369 }
370
371 // This pass originally used a post-order traversal and then operated on
372 // the list in reverse. Now that we are using a reverse post-order traversal
373 // rather than re-working the whole pass to operate on the list in order,
374 // we just reverse the list and continue to operate on it in reverse.
375 std::reverse(Order.begin(), Order.end());
Tom Stellardf8794352012-12-19 22:10:31 +0000376}
377
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000378/// Determine the end of the loops
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000379void StructurizeCFG::analyzeLoops(RegionNode *N) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000380 if (N->isSubRegion()) {
381 // Test for exit as back edge
382 BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
383 if (Visited.count(Exit))
384 Loops[Exit] = N->getEntry();
385
386 } else {
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000387 // Test for successors as back edge
Christian Konigfc6a9852013-02-16 11:27:45 +0000388 BasicBlock *BB = N->getNodeAs<BasicBlock>();
389 BranchInst *Term = cast<BranchInst>(BB->getTerminator());
390
Pete Cooperebcd7482015-08-06 20:22:46 +0000391 for (BasicBlock *Succ : Term->successors())
392 if (Visited.count(Succ))
Christian Konigfc6a9852013-02-16 11:27:45 +0000393 Loops[Succ] = BB;
Christian Konigfc6a9852013-02-16 11:27:45 +0000394 }
395}
396
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000397/// Invert the given condition
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000398Value *StructurizeCFG::invert(Value *Condition) {
Christian Konigd8860992013-02-16 11:27:50 +0000399 // First: Check if it's a constant
Matt Arsenault93be6e82016-07-15 22:13:16 +0000400 if (Constant *C = dyn_cast<Constant>(Condition))
401 return ConstantExpr::getNot(C);
Christian Konigd8860992013-02-16 11:27:50 +0000402
403 // Second: If the condition is already inverted, return the original value
Marek Olsak3c5fd142018-05-15 21:41:55 +0000404 Value *NotCondition;
405 if (match(Condition, m_Not(m_Value(NotCondition))))
406 return NotCondition;
Christian Konigd8860992013-02-16 11:27:50 +0000407
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000408 if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
409 // Third: Check all the users for an invert
410 BasicBlock *Parent = Inst->getParent();
Matt Arsenault44746522017-04-24 20:25:01 +0000411 for (User *U : Condition->users())
412 if (Instruction *I = dyn_cast<Instruction>(U))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000413 if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
414 return I;
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000415
416 // Last option: Create a new instruction
417 return BinaryOperator::CreateNot(Condition, "", Parent->getTerminator());
Christian Konigd8860992013-02-16 11:27:50 +0000418 }
419
Matt Arsenault9fb6e0b2013-11-22 19:24:37 +0000420 if (Argument *Arg = dyn_cast<Argument>(Condition)) {
421 BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
422 return BinaryOperator::CreateNot(Condition,
423 Arg->getName() + ".inv",
424 EntryBlock.getTerminator());
425 }
426
427 llvm_unreachable("Unhandled condition to invert");
Christian Konigd8860992013-02-16 11:27:50 +0000428}
429
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000430/// Build the condition for one edge
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000431Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
432 bool Invert) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000433 Value *Cond = Invert ? BoolFalse : BoolTrue;
434 if (Term->isConditional()) {
435 Cond = Term->getCondition();
Tom Stellardf8794352012-12-19 22:10:31 +0000436
Aaron Ballman19978552013-06-04 01:03:03 +0000437 if (Idx != (unsigned)Invert)
Christian Konigd8860992013-02-16 11:27:50 +0000438 Cond = invert(Cond);
Tom Stellard048f14f2013-02-08 22:24:37 +0000439 }
440 return Cond;
441}
442
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000443/// Analyze the predecessors of each block and build up predicates
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000444void StructurizeCFG::gatherPredicates(RegionNode *N) {
Tom Stellardf8794352012-12-19 22:10:31 +0000445 RegionInfo *RI = ParentRegion->getRegionInfo();
Tom Stellard048f14f2013-02-08 22:24:37 +0000446 BasicBlock *BB = N->getEntry();
447 BBPredicates &Pred = Predicates[BB];
Christian Konigfc6a9852013-02-16 11:27:45 +0000448 BBPredicates &LPred = LoopPreds[BB];
Tom Stellardf8794352012-12-19 22:10:31 +0000449
Justin Lebar3aec10c2016-11-28 18:50:03 +0000450 for (BasicBlock *P : predecessors(BB)) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000451 // Ignore it if it's a branch from outside into our region entry
Justin Lebar3aec10c2016-11-28 18:50:03 +0000452 if (!ParentRegion->contains(P))
Tom Stellard048f14f2013-02-08 22:24:37 +0000453 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000454
Justin Lebar3aec10c2016-11-28 18:50:03 +0000455 Region *R = RI->getRegionFor(P);
Tom Stellard048f14f2013-02-08 22:24:37 +0000456 if (R == ParentRegion) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000457 // It's a top level block in our region
Justin Lebar3aec10c2016-11-28 18:50:03 +0000458 BranchInst *Term = cast<BranchInst>(P->getTerminator());
Tom Stellard048f14f2013-02-08 22:24:37 +0000459 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
460 BasicBlock *Succ = Term->getSuccessor(i);
461 if (Succ != BB)
462 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000463
Justin Lebar3aec10c2016-11-28 18:50:03 +0000464 if (Visited.count(P)) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000465 // Normal forward edge
466 if (Term->isConditional()) {
467 // Try to treat it like an ELSE block
468 BasicBlock *Other = Term->getSuccessor(!i);
Christian Konigfc6a9852013-02-16 11:27:45 +0000469 if (Visited.count(Other) && !Loops.count(Other) &&
Justin Lebar3aec10c2016-11-28 18:50:03 +0000470 !Pred.count(Other) && !Pred.count(P)) {
Tom Stellardf8794352012-12-19 22:10:31 +0000471
Tom Stellard048f14f2013-02-08 22:24:37 +0000472 Pred[Other] = BoolFalse;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000473 Pred[P] = BoolTrue;
Tom Stellard048f14f2013-02-08 22:24:37 +0000474 continue;
475 }
476 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000477 Pred[P] = buildCondition(Term, i, false);
Tom Stellard048f14f2013-02-08 22:24:37 +0000478 } else {
479 // Back edge
Justin Lebar3aec10c2016-11-28 18:50:03 +0000480 LPred[P] = buildCondition(Term, i, true);
Tom Stellard048f14f2013-02-08 22:24:37 +0000481 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000482 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000483 } else {
Tom Stellard048f14f2013-02-08 22:24:37 +0000484 // It's an exit from a sub region
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000485 while (R->getParent() != ParentRegion)
Tom Stellard048f14f2013-02-08 22:24:37 +0000486 R = R->getParent();
487
488 // Edge from inside a subregion to its entry, ignore it
Matt Arsenault1b8d8372014-07-19 18:29:29 +0000489 if (*R == *N)
Tom Stellard048f14f2013-02-08 22:24:37 +0000490 continue;
491
492 BasicBlock *Entry = R->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000493 if (Visited.count(Entry))
494 Pred[Entry] = BoolTrue;
495 else
496 LPred[Entry] = BoolFalse;
Tom Stellardf8794352012-12-19 22:10:31 +0000497 }
498 }
499}
500
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000501/// Collect various loop and predicate infos
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000502void StructurizeCFG::collectInfos() {
503 // Reset predicate
504 Predicates.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000505
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000506 // and loop infos
507 Loops.clear();
508 LoopPreds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000509
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000510 // Reset the visited nodes
511 Visited.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +0000512
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000513 for (RegionNode *RN : reverse(Order)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000514 LLVM_DEBUG(dbgs() << "Visiting: "
515 << (RN->isSubRegion() ? "SubRegion with entry: " : "")
516 << RN->getEntry()->getName() << " Loop Depth: "
517 << LI->getLoopDepth(RN->getEntry()) << "\n");
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000518
519 // Analyze all the conditions leading to a node
520 gatherPredicates(RN);
521
522 // Remember that we've seen this node
523 Visited.insert(RN->getEntry());
524
525 // Find the last back edges
526 analyzeLoops(RN);
527 }
Tom Stellard048f14f2013-02-08 22:24:37 +0000528}
529
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000530/// Insert the missing branch conditions
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000531void StructurizeCFG::insertConditions(bool Loops) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000532 BranchVector &Conds = Loops ? LoopConds : Conditions;
533 Value *Default = Loops ? BoolTrue : BoolFalse;
Tom Stellard048f14f2013-02-08 22:24:37 +0000534 SSAUpdater PhiInserter;
535
Matt Arsenault04b67ce2014-05-19 17:52:48 +0000536 for (BranchInst *Term : Conds) {
Tom Stellard048f14f2013-02-08 22:24:37 +0000537 assert(Term->isConditional());
538
Christian Konigfc6a9852013-02-16 11:27:45 +0000539 BasicBlock *Parent = Term->getParent();
540 BasicBlock *SuccTrue = Term->getSuccessor(0);
541 BasicBlock *SuccFalse = Term->getSuccessor(1);
Tom Stellard048f14f2013-02-08 22:24:37 +0000542
Christian Konigb5d88662013-02-16 11:27:40 +0000543 PhiInserter.Initialize(Boolean, "");
544 PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
Christian Konigfc6a9852013-02-16 11:27:45 +0000545 PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000546
Christian Konigfc6a9852013-02-16 11:27:45 +0000547 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
Christian Konigb5d88662013-02-16 11:27:40 +0000548
549 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000550 Dominator.addBlock(Parent);
Christian Konigb5d88662013-02-16 11:27:40 +0000551
Craig Topperf40110f2014-04-25 05:29:35 +0000552 Value *ParentValue = nullptr;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000553 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
554 BasicBlock *BB = BBAndPred.first;
555 Value *Pred = BBAndPred.second;
Tom Stellard048f14f2013-02-08 22:24:37 +0000556
Justin Lebar3aec10c2016-11-28 18:50:03 +0000557 if (BB == Parent) {
558 ParentValue = Pred;
Christian Konigb5d88662013-02-16 11:27:40 +0000559 break;
560 }
Justin Lebar3aec10c2016-11-28 18:50:03 +0000561 PhiInserter.AddAvailableValue(BB, Pred);
562 Dominator.addAndRememberBlock(BB);
Tom Stellard048f14f2013-02-08 22:24:37 +0000563 }
564
Christian Konigb5d88662013-02-16 11:27:40 +0000565 if (ParentValue) {
566 Term->setCondition(ParentValue);
567 } else {
Justin Lebar62c20d82016-11-28 18:49:59 +0000568 if (!Dominator.resultIsRememberedBlock())
569 PhiInserter.AddAvailableValue(Dominator.result(), Default);
Christian Konigb5d88662013-02-16 11:27:40 +0000570
Tom Stellard048f14f2013-02-08 22:24:37 +0000571 Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
Christian Konigb5d88662013-02-16 11:27:40 +0000572 }
Tom Stellardf8794352012-12-19 22:10:31 +0000573 }
574}
575
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000576/// Remove all PHI values coming from "From" into "To" and remember
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000577/// them in DeletedPhis
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000578void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000579 PhiMap &Map = DeletedPhis[To];
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000580 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000581 while (Phi.getBasicBlockIndex(From) != -1) {
582 Value *Deleted = Phi.removeIncomingValue(From, false);
583 Map[&Phi].push_back(std::make_pair(From, Deleted));
584 }
585 }
586}
587
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000588/// Add a dummy PHI value as soon as we knew the new predecessor
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000589void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
Matt Arsenault8dcfa132017-12-29 19:25:57 +0000590 for (PHINode &Phi : To->phis()) {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000591 Value *Undef = UndefValue::get(Phi.getType());
592 Phi.addIncoming(Undef, From);
593 }
594 AddedPhis[To].push_back(From);
595}
596
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000597/// Add the real PHI value as soon as everything is set up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000598void StructurizeCFG::setPhiValues() {
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000599 SSAUpdater Updater;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000600 for (const auto &AddedPhi : AddedPhis) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000601 BasicBlock *To = AddedPhi.first;
602 const BBVector &From = AddedPhi.second;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000603
604 if (!DeletedPhis.count(To))
605 continue;
606
607 PhiMap &Map = DeletedPhis[To];
Benjamin Kramer135f7352016-06-26 12:28:59 +0000608 for (const auto &PI : Map) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000609 PHINode *Phi = PI.first;
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000610 Value *Undef = UndefValue::get(Phi->getType());
611 Updater.Initialize(Phi->getType(), "");
612 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
613 Updater.AddAvailableValue(To, Undef);
614
Christian Konig0bccf9d2013-02-16 11:27:35 +0000615 NearestCommonDominator Dominator(DT);
Justin Lebar62c20d82016-11-28 18:49:59 +0000616 Dominator.addBlock(To);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000617 for (const auto &VI : PI.second) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000618 Updater.AddAvailableValue(VI.first, VI.second);
Justin Lebar62c20d82016-11-28 18:49:59 +0000619 Dominator.addAndRememberBlock(VI.first);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000620 }
621
Justin Lebar62c20d82016-11-28 18:49:59 +0000622 if (!Dominator.resultIsRememberedBlock())
623 Updater.AddAvailableValue(Dominator.result(), Undef);
Christian Konig0bccf9d2013-02-16 11:27:35 +0000624
Benjamin Kramer135f7352016-06-26 12:28:59 +0000625 for (BasicBlock *FI : From) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000626 int Idx = Phi->getBasicBlockIndex(FI);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000627 assert(Idx != -1);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000628 Phi->setIncomingValue(Idx, Updater.GetValueAtEndOfBlock(FI));
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000629 }
630 }
631
632 DeletedPhis.erase(To);
633 }
634 assert(DeletedPhis.empty());
635}
636
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000637/// Remove phi values from all successors and then remove the terminator.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000638void StructurizeCFG::killTerminator(BasicBlock *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000639 TerminatorInst *Term = BB->getTerminator();
640 if (!Term)
641 return;
642
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000643 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000644 SI != SE; ++SI)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000645 delPhiValues(BB, *SI);
Tom Stellardf8794352012-12-19 22:10:31 +0000646
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000647 if (DA)
648 DA->removeValue(Term);
Tom Stellardf8794352012-12-19 22:10:31 +0000649 Term->eraseFromParent();
650}
651
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000652/// Let node exit(s) point to NewExit
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000653void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
654 bool IncludeDominator) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000655 if (Node->isSubRegion()) {
656 Region *SubRegion = Node->getNodeAs<Region>();
657 BasicBlock *OldExit = SubRegion->getExit();
Craig Topperf40110f2014-04-25 05:29:35 +0000658 BasicBlock *Dominator = nullptr;
Tom Stellardf8794352012-12-19 22:10:31 +0000659
Tom Stellard7370ede2013-02-08 22:24:38 +0000660 // Find all the edges from the sub region to the exit
Justin Lebar3aec10c2016-11-28 18:50:03 +0000661 for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
662 // Incrememt BBI before mucking with BB's terminator.
663 BasicBlock *BB = *BBI++;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000664
Tom Stellard7370ede2013-02-08 22:24:38 +0000665 if (!SubRegion->contains(BB))
666 continue;
667
668 // Modify the edges to point to the new exit
669 delPhiValues(BB, OldExit);
670 BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
671 addPhiValues(BB, NewExit);
672
673 // Find the new dominator (if requested)
674 if (IncludeDominator) {
675 if (!Dominator)
676 Dominator = BB;
677 else
678 Dominator = DT->findNearestCommonDominator(Dominator, BB);
679 }
Tom Stellardf8794352012-12-19 22:10:31 +0000680 }
681
Tom Stellard7370ede2013-02-08 22:24:38 +0000682 // Change the dominator (if requested)
683 if (Dominator)
684 DT->changeImmediateDominator(NewExit, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000685
Tom Stellard7370ede2013-02-08 22:24:38 +0000686 // Update the region info
687 SubRegion->replaceExit(NewExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000688 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000689 BasicBlock *BB = Node->getNodeAs<BasicBlock>();
690 killTerminator(BB);
691 BranchInst::Create(NewExit, BB);
692 addPhiValues(BB, NewExit);
693 if (IncludeDominator)
694 DT->changeImmediateDominator(NewExit, BB);
Tom Stellardf8794352012-12-19 22:10:31 +0000695 }
Tom Stellardf8794352012-12-19 22:10:31 +0000696}
697
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000698/// Create a new flow node and update dominator tree and region info
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000699BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
Tom Stellardf8794352012-12-19 22:10:31 +0000700 LLVMContext &Context = Func->getContext();
701 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000702 Order.back()->getEntry();
Tom Stellardf8794352012-12-19 22:10:31 +0000703 BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
704 Func, Insert);
Tom Stellard7370ede2013-02-08 22:24:38 +0000705 DT->addNewBlock(Flow, Dominator);
Tom Stellardf8794352012-12-19 22:10:31 +0000706 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
Tom Stellardf8794352012-12-19 22:10:31 +0000707 return Flow;
708}
709
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000710/// Create a new or reuse the previous node as flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000711BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000712 BasicBlock *Entry = PrevNode->getEntry();
Tom Stellard7370ede2013-02-08 22:24:38 +0000713
Christian Konigfc6a9852013-02-16 11:27:45 +0000714 if (!PrevNode->isSubRegion()) {
715 killTerminator(Entry);
716 if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
717 return Entry;
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000718 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000719
Christian Konigfc6a9852013-02-16 11:27:45 +0000720 // create a new flow node
721 BasicBlock *Flow = getNextFlow(Entry);
Tom Stellard7370ede2013-02-08 22:24:38 +0000722
Christian Konigfc6a9852013-02-16 11:27:45 +0000723 // and wire it up
724 changeExit(PrevNode, Flow, true);
725 PrevNode = ParentRegion->getBBNode(Flow);
726 return Flow;
Tom Stellard7370ede2013-02-08 22:24:38 +0000727}
728
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000729/// Returns the region exit if possible, otherwise just a new flow node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000730BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
731 bool ExitUseAllowed) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000732 if (!Order.empty() || !ExitUseAllowed)
733 return getNextFlow(Flow);
734
735 BasicBlock *Exit = ParentRegion->getExit();
736 DT->changeImmediateDominator(Exit, Flow);
737 addPhiValues(Flow, Exit);
738 return Exit;
Tom Stellard7370ede2013-02-08 22:24:38 +0000739}
740
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000741/// Set the previous node
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000742void StructurizeCFG::setPrevNode(BasicBlock *BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000743 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
744 : nullptr;
Tom Stellard7370ede2013-02-08 22:24:38 +0000745}
746
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000747/// Does BB dominate all the predicates of Node?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000748bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000749 BBPredicates &Preds = Predicates[Node->getEntry()];
Justin Lebar3aec10c2016-11-28 18:50:03 +0000750 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
751 return DT->dominates(BB, Pred.first);
752 });
Tom Stellard7370ede2013-02-08 22:24:38 +0000753}
754
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000755/// Can we predict that this node will always be called?
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000756bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000757 BBPredicates &Preds = Predicates[Node->getEntry()];
758 bool Dominated = false;
759
760 // Regionentry is always true
Craig Topperf40110f2014-04-25 05:29:35 +0000761 if (!PrevNode)
Christian Konigfc6a9852013-02-16 11:27:45 +0000762 return true;
Tom Stellardf8794352012-12-19 22:10:31 +0000763
Justin Lebar3aec10c2016-11-28 18:50:03 +0000764 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
765 BasicBlock *BB = Pred.first;
766 Value *V = Pred.second;
Tom Stellardf8794352012-12-19 22:10:31 +0000767
Justin Lebar3aec10c2016-11-28 18:50:03 +0000768 if (V != BoolTrue)
Tom Stellardf8794352012-12-19 22:10:31 +0000769 return false;
770
Justin Lebar3aec10c2016-11-28 18:50:03 +0000771 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
Tom Stellardf8794352012-12-19 22:10:31 +0000772 Dominated = true;
773 }
Tom Stellard7370ede2013-02-08 22:24:38 +0000774
775 // TODO: The dominator check is too strict
Tom Stellardf8794352012-12-19 22:10:31 +0000776 return Dominated;
777}
778
Tom Stellard7370ede2013-02-08 22:24:38 +0000779/// Take one node from the order vector and wire it up
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000780void StructurizeCFG::wireFlow(bool ExitUseAllowed,
781 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000782 RegionNode *Node = Order.pop_back_val();
Christian Konigfc6a9852013-02-16 11:27:45 +0000783 Visited.insert(Node->getEntry());
Tom Stellardf8794352012-12-19 22:10:31 +0000784
Christian Konigfc6a9852013-02-16 11:27:45 +0000785 if (isPredictableTrue(Node)) {
Tom Stellard7370ede2013-02-08 22:24:38 +0000786 // Just a linear flow
Christian Konigfc6a9852013-02-16 11:27:45 +0000787 if (PrevNode) {
788 changeExit(PrevNode, Node->getEntry(), true);
Tom Stellardf8794352012-12-19 22:10:31 +0000789 }
Christian Konigfc6a9852013-02-16 11:27:45 +0000790 PrevNode = Node;
Tom Stellardf8794352012-12-19 22:10:31 +0000791 } else {
Tom Stellard7370ede2013-02-08 22:24:38 +0000792 // Insert extra prefix node (or reuse last one)
Christian Konigfc6a9852013-02-16 11:27:45 +0000793 BasicBlock *Flow = needPrefix(false);
Tom Stellardf8794352012-12-19 22:10:31 +0000794
Tom Stellard7370ede2013-02-08 22:24:38 +0000795 // Insert extra postfix node (or use exit instead)
796 BasicBlock *Entry = Node->getEntry();
Christian Konigfc6a9852013-02-16 11:27:45 +0000797 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
Tom Stellard7370ede2013-02-08 22:24:38 +0000798
799 // let it point to entry and next block
800 Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
801 addPhiValues(Flow, Entry);
802 DT->changeImmediateDominator(Entry, Flow);
803
Christian Konigfc6a9852013-02-16 11:27:45 +0000804 PrevNode = Node;
805 while (!Order.empty() && !Visited.count(LoopEnd) &&
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000806 dominatesPredicates(Entry, Order.back())) {
Christian Konigfc6a9852013-02-16 11:27:45 +0000807 handleLoops(false, LoopEnd);
Tom Stellard7370ede2013-02-08 22:24:38 +0000808 }
809
Christian Konigfc6a9852013-02-16 11:27:45 +0000810 changeExit(PrevNode, Next, false);
811 setPrevNode(Next);
812 }
813}
814
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000815void StructurizeCFG::handleLoops(bool ExitUseAllowed,
816 BasicBlock *LoopEnd) {
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000817 RegionNode *Node = Order.back();
Christian Konigfc6a9852013-02-16 11:27:45 +0000818 BasicBlock *LoopStart = Node->getEntry();
819
820 if (!Loops.count(LoopStart)) {
821 wireFlow(ExitUseAllowed, LoopEnd);
822 return;
Tom Stellardf8794352012-12-19 22:10:31 +0000823 }
824
Christian Konigfc6a9852013-02-16 11:27:45 +0000825 if (!isPredictableTrue(Node))
826 LoopStart = needPrefix(true);
827
828 LoopEnd = Loops[Node->getEntry()];
829 wireFlow(false, LoopEnd);
830 while (!Visited.count(LoopEnd)) {
831 handleLoops(false, LoopEnd);
832 }
833
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000834 // If the start of the loop is the entry block, we can't branch to it so
835 // insert a new dummy entry block.
836 Function *LoopFunc = LoopStart->getParent();
837 if (LoopStart == &LoopFunc->getEntryBlock()) {
838 LoopStart->setName("entry.orig");
839
840 BasicBlock *NewEntry =
841 BasicBlock::Create(LoopStart->getContext(),
842 "entry",
843 LoopFunc,
844 LoopStart);
845 BranchInst::Create(LoopStart, NewEntry);
Serge Pavlov0668cd22017-01-10 02:50:47 +0000846 DT->setNewRoot(NewEntry);
Matt Arsenault6ea0aad2013-11-22 19:24:39 +0000847 }
848
Christian Konigfc6a9852013-02-16 11:27:45 +0000849 // Create an extra loop end node
850 LoopEnd = needPrefix(false);
851 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
852 LoopConds.push_back(BranchInst::Create(Next, LoopStart,
853 BoolUndef, LoopEnd));
854 addPhiValues(LoopEnd, LoopStart);
855 setPrevNode(Next);
Tom Stellardf8794352012-12-19 22:10:31 +0000856}
857
Tom Stellardf8794352012-12-19 22:10:31 +0000858/// After this function control flow looks like it should be, but
Tom Stellard7370ede2013-02-08 22:24:38 +0000859/// branches and PHI nodes only have undefined conditions.
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000860void StructurizeCFG::createFlow() {
Tom Stellard7370ede2013-02-08 22:24:38 +0000861 BasicBlock *Exit = ParentRegion->getExit();
862 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
863
Tom Stellardf8794352012-12-19 22:10:31 +0000864 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000865 AddedPhis.clear();
Tom Stellard7370ede2013-02-08 22:24:38 +0000866 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +0000867 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +0000868
Craig Topperf40110f2014-04-25 05:29:35 +0000869 PrevNode = nullptr;
Christian Konigfc6a9852013-02-16 11:27:45 +0000870 Visited.clear();
871
Tom Stellardf8794352012-12-19 22:10:31 +0000872 while (!Order.empty()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000873 handleLoops(EntryDominatesExit, nullptr);
Tom Stellardf8794352012-12-19 22:10:31 +0000874 }
875
Christian Konigfc6a9852013-02-16 11:27:45 +0000876 if (PrevNode)
877 changeExit(PrevNode, Exit, EntryDominatesExit);
Tom Stellard7370ede2013-02-08 22:24:38 +0000878 else
879 assert(EntryDominatesExit);
Tom Stellardf8794352012-12-19 22:10:31 +0000880}
881
Tom Stellardf8794352012-12-19 22:10:31 +0000882/// Handle a rare case where the disintegrated nodes instructions
Hiroshi Inouef2096492018-06-14 05:41:49 +0000883/// no longer dominate all their uses. Not sure if this is really necessary
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000884void StructurizeCFG::rebuildSSA() {
Tom Stellardf8794352012-12-19 22:10:31 +0000885 SSAUpdater Updater;
Justin Lebar3aec10c2016-11-28 18:50:03 +0000886 for (BasicBlock *BB : ParentRegion->blocks())
887 for (Instruction &I : *BB) {
Tom Stellardf8794352012-12-19 22:10:31 +0000888 bool Initialized = false;
Justin Lebar96e29152016-11-29 21:49:02 +0000889 // We may modify the use list as we iterate over it, so be careful to
890 // compute the next element in the use list at the top of the loop.
891 for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
892 Use &U = *UI++;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000893 Instruction *User = cast<Instruction>(U.getUser());
Tom Stellardf8794352012-12-19 22:10:31 +0000894 if (User->getParent() == BB) {
895 continue;
Tom Stellardf8794352012-12-19 22:10:31 +0000896 } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000897 if (UserPN->getIncomingBlock(U) == BB)
Tom Stellardf8794352012-12-19 22:10:31 +0000898 continue;
899 }
900
Justin Lebar3aec10c2016-11-28 18:50:03 +0000901 if (DT->dominates(&I, User))
Tom Stellardf8794352012-12-19 22:10:31 +0000902 continue;
903
904 if (!Initialized) {
Justin Lebar3aec10c2016-11-28 18:50:03 +0000905 Value *Undef = UndefValue::get(I.getType());
906 Updater.Initialize(I.getType(), "");
Tom Stellardf8794352012-12-19 22:10:31 +0000907 Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
Justin Lebar3aec10c2016-11-28 18:50:03 +0000908 Updater.AddAvailableValue(BB, &I);
Tom Stellardf8794352012-12-19 22:10:31 +0000909 Initialized = true;
910 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000911 Updater.RewriteUseAfterInsertions(U);
Tom Stellardf8794352012-12-19 22:10:31 +0000912 }
913 }
Tom Stellardf8794352012-12-19 22:10:31 +0000914}
915
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000916static bool hasOnlyUniformBranches(Region *R, unsigned UniformMDKindID,
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000917 const LegacyDivergenceAnalysis &DA) {
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000918 for (auto E : R->elements()) {
919 if (!E->isSubRegion()) {
920 auto Br = dyn_cast<BranchInst>(E->getEntry()->getTerminator());
921 if (!Br || !Br->isConditional())
922 continue;
Tom Stellard755a4e62016-02-10 00:39:37 +0000923
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000924 if (!DA.isUniform(Br))
925 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000926 LLVM_DEBUG(dbgs() << "BB: " << Br->getParent()->getName()
927 << " has uniform terminator\n");
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000928 } else {
929 // Explicitly refuse to treat regions as uniform if they have non-uniform
930 // subregions. We cannot rely on DivergenceAnalysis for branches in
931 // subregions because those branches may have been removed and re-created,
932 // so we look for our metadata instead.
933 //
934 // Warning: It would be nice to treat regions as uniform based only on
935 // their direct child basic blocks' terminators, regardless of whether
936 // subregions are uniform or not. However, this requires a very careful
937 // look at SIAnnotateControlFlow to make sure nothing breaks there.
938 for (auto BB : E->getNodeAs<Region>()->blocks()) {
939 auto Br = dyn_cast<BranchInst>(BB->getTerminator());
940 if (!Br || !Br->isConditional())
941 continue;
942
943 if (!Br->getMetadata(UniformMDKindID))
944 return false;
945 }
946 }
Tom Stellard755a4e62016-02-10 00:39:37 +0000947 }
948 return true;
949}
950
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000951/// Run the transformation for each region found
Matt Arsenaultd46fce12013-06-19 20:18:24 +0000952bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
Tom Stellardf8794352012-12-19 22:10:31 +0000953 if (R->isTopLevelRegion())
954 return false;
955
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000956 DA = nullptr;
957
Tom Stellard755a4e62016-02-10 00:39:37 +0000958 if (SkipUniformRegions) {
Tom Stellard755a4e62016-02-10 00:39:37 +0000959 // TODO: We could probably be smarter here with how we handle sub-regions.
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000960 // We currently rely on the fact that metadata is set by earlier invocations
961 // of the pass on sub-regions, and that this metadata doesn't get lost --
962 // but we shouldn't rely on metadata for correctness!
963 unsigned UniformMDKindID =
964 R->getEntry()->getContext().getMDKindID("structurizecfg.uniform");
Nicolai Haehnle35617ed2018-08-30 14:21:36 +0000965 DA = &getAnalysis<LegacyDivergenceAnalysis>();
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000966
967 if (hasOnlyUniformBranches(R, UniformMDKindID, *DA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000968 LLVM_DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R
969 << '\n');
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000970
971 // Mark all direct child block terminators as having been treated as
972 // uniform. To account for a possible future in which non-uniform
973 // sub-regions are treated more cleverly, indirect children are not
974 // marked as uniform.
975 MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
Justin Lebar1b60d702016-11-22 23:13:37 +0000976 for (RegionNode *E : R->elements()) {
977 if (E->isSubRegion())
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000978 continue;
979
Justin Lebar1b60d702016-11-22 23:13:37 +0000980 if (Instruction *Term = E->getEntry()->getTerminator())
Nicolai Haehnleeb7311f2018-04-04 10:58:15 +0000981 Term->setMetadata(UniformMDKindID, MD);
Nicolai Haehnle05b127d2016-04-14 17:42:35 +0000982 }
983
Tom Stellard755a4e62016-02-10 00:39:37 +0000984 return false;
985 }
986 }
987
Tom Stellardf8794352012-12-19 22:10:31 +0000988 Func = R->getEntry()->getParent();
989 ParentRegion = R;
990
Chandler Carruth73523022014-01-13 13:07:17 +0000991 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000992 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Tom Stellardf8794352012-12-19 22:10:31 +0000993
994 orderNodes();
Nicolai Haehnle4afb64e2018-01-24 18:02:05 +0000995 collectInfos();
Tom Stellardf8794352012-12-19 22:10:31 +0000996 createFlow();
Christian Konigfc6a9852013-02-16 11:27:45 +0000997 insertConditions(false);
998 insertConditions(true);
Tom Stellard7ec0e4f2013-02-08 22:24:35 +0000999 setPhiValues();
Tom Stellardf8794352012-12-19 22:10:31 +00001000 rebuildSSA();
1001
Tom Stellard048f14f2013-02-08 22:24:37 +00001002 // Cleanup
Tom Stellardf8794352012-12-19 22:10:31 +00001003 Order.clear();
1004 Visited.clear();
Tom Stellardf8794352012-12-19 22:10:31 +00001005 DeletedPhis.clear();
Tom Stellard7ec0e4f2013-02-08 22:24:35 +00001006 AddedPhis.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +00001007 Predicates.clear();
Tom Stellard048f14f2013-02-08 22:24:37 +00001008 Conditions.clear();
Christian Konigfc6a9852013-02-16 11:27:45 +00001009 Loops.clear();
1010 LoopPreds.clear();
1011 LoopConds.clear();
Tom Stellardf8794352012-12-19 22:10:31 +00001012
1013 return true;
1014}
1015
Tom Stellard755a4e62016-02-10 00:39:37 +00001016Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
1017 return new StructurizeCFG(SkipUniformRegions);
Tom Stellardf8794352012-12-19 22:10:31 +00001018}