1 //===-- SIAnnotateControlFlow.cpp - ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Annotates the control flow with hardware specific intrinsics.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/Analysis/DivergenceAnalysis.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/Transforms/Utils/SSAUpdater.h"
30 #define DEBUG_TYPE "si-annotate-control-flow"
34 // Complex types used in this pass
35 typedef std::pair<BasicBlock *, Value *> StackEntry;
36 typedef SmallVector<StackEntry, 16> StackVector;
38 class SIAnnotateControlFlow : public FunctionPass {
39 DivergenceAnalysis *DA;
46 ConstantInt *BoolTrue;
47 ConstantInt *BoolFalse;
48 UndefValue *BoolUndef;
64 bool isUniform(BranchInst *T);
66 bool isTopOfStack(BasicBlock *BB);
70 void push(BasicBlock *BB, Value *Saved);
72 bool isElse(PHINode *Phi);
74 void eraseIfUnused(PHINode *Phi);
76 void openIf(BranchInst *Term);
78 void insertElse(BranchInst *Term);
81 handleLoopCondition(Value *Cond, PHINode *Broken, llvm::Loop *L,
83 SmallVectorImpl<WeakTrackingVH> &LoopPhiConditions);
85 void handleLoop(BranchInst *Term);
87 void closeControlFlow(BasicBlock *BB);
92 SIAnnotateControlFlow():
95 bool doInitialization(Module &M) override;
97 bool runOnFunction(Function &F) override;
99 StringRef getPassName() const override { return "SI annotate control flow"; }
101 void getAnalysisUsage(AnalysisUsage &AU) const override {
102 AU.addRequired<LoopInfoWrapperPass>();
103 AU.addRequired<DominatorTreeWrapperPass>();
104 AU.addRequired<DivergenceAnalysis>();
105 AU.addPreserved<DominatorTreeWrapperPass>();
106 FunctionPass::getAnalysisUsage(AU);
111 } // end anonymous namespace
113 INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,
114 "Annotate SI Control Flow", false, false)
115 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
116 INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis)
117 INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE,
118 "Annotate SI Control Flow", false, false)
120 char SIAnnotateControlFlow::ID = 0;
122 /// \brief Initialize all the types and constants used in the pass
123 bool SIAnnotateControlFlow::doInitialization(Module &M) {
124 LLVMContext &Context = M.getContext();
126 Void = Type::getVoidTy(Context);
127 Boolean = Type::getInt1Ty(Context);
128 Int64 = Type::getInt64Ty(Context);
129 ReturnStruct = StructType::get(Boolean, Int64);
131 BoolTrue = ConstantInt::getTrue(Context);
132 BoolFalse = ConstantInt::getFalse(Context);
133 BoolUndef = UndefValue::get(Boolean);
134 Int64Zero = ConstantInt::get(Int64, 0);
136 If = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if);
137 Else = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_else);
138 Break = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_break);
139 IfBreak = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if_break);
140 ElseBreak = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_else_break);
141 Loop = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_loop);
142 EndCf = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_end_cf);
146 /// \brief Is the branch condition uniform or did the StructurizeCFG pass
147 /// consider it as such?
148 bool SIAnnotateControlFlow::isUniform(BranchInst *T) {
149 return DA->isUniform(T->getCondition()) ||
150 T->getMetadata("structurizecfg.uniform") != nullptr;
153 /// \brief Is BB the last block saved on the stack ?
154 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
155 return !Stack.empty() && Stack.back().first == BB;
158 /// \brief Pop the last saved value from the control flow stack
159 Value *SIAnnotateControlFlow::popSaved() {
160 return Stack.pop_back_val().second;
163 /// \brief Push a BB and saved value to the control flow stack
164 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
165 Stack.push_back(std::make_pair(BB, Saved));
168 /// \brief Can the condition represented by this PHI node treated like
170 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
171 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
172 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
173 if (Phi->getIncomingBlock(i) == IDom) {
175 if (Phi->getIncomingValue(i) != BoolTrue)
179 if (Phi->getIncomingValue(i) != BoolFalse)
187 // \brief Erase "Phi" if it is not used any more
188 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
189 if (llvm::RecursivelyDeleteDeadPHINode(Phi)) {
190 DEBUG(dbgs() << "Erased unused condition phi\n");
194 /// \brief Open a new "If" block
195 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
199 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
200 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
201 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
204 /// \brief Close the last "If" block and open a new "Else" block
205 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
206 if (isUniform(Term)) {
209 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
210 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
211 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
214 /// \brief Recursively handle the condition leading to a loop
215 Value *SIAnnotateControlFlow::handleLoopCondition(
216 Value *Cond, PHINode *Broken, llvm::Loop *L, BranchInst *Term,
217 SmallVectorImpl<WeakTrackingVH> &LoopPhiConditions) {
219 // Only search through PHI nodes which are inside the loop. If we try this
220 // with PHI nodes that are outside of the loop, we end up inserting new PHI
221 // nodes outside of the loop which depend on values defined inside the loop.
222 // This will break the module with
223 // 'Instruction does not dominate all users!' errors.
224 PHINode *Phi = nullptr;
225 if ((Phi = dyn_cast<PHINode>(Cond)) && L->contains(Phi)) {
227 BasicBlock *Parent = Phi->getParent();
228 PHINode *NewPhi = PHINode::Create(Int64, 0, "loop.phi", &Parent->front());
231 // Handle all non-constant incoming values first
232 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
233 Value *Incoming = Phi->getIncomingValue(i);
234 BasicBlock *From = Phi->getIncomingBlock(i);
235 if (isa<ConstantInt>(Incoming)) {
236 NewPhi->addIncoming(Broken, From);
240 Phi->setIncomingValue(i, BoolFalse);
241 Value *PhiArg = handleLoopCondition(Incoming, Broken, L,
242 Term, LoopPhiConditions);
243 NewPhi->addIncoming(PhiArg, From);
246 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock();
248 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
249 Value *Incoming = Phi->getIncomingValue(i);
250 if (Incoming != BoolTrue)
253 BasicBlock *From = Phi->getIncomingBlock(i);
255 // We're in the following situation:
261 // where we want to break out of the loop if the If-block is not taken.
262 // Due to the depth-first traversal, there should be an end.cf
263 // intrinsic in Parent, and we insert an else.break before it.
265 // Note that the end.cf need not be the first non-phi instruction
266 // of parent, particularly when we're dealing with a multi-level
267 // break, but it should occur within a group of intrinsic calls
268 // at the beginning of the block.
269 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt());
270 while (OldEnd && OldEnd->getCalledFunction() != EndCf)
271 OldEnd = dyn_cast<CallInst>(OldEnd->getNextNode());
272 if (OldEnd && OldEnd->getCalledFunction() == EndCf) {
273 Value *Args[] = { OldEnd->getArgOperand(0), NewPhi };
274 Ret = CallInst::Create(ElseBreak, Args, "", OldEnd);
279 TerminatorInst *Insert = From->getTerminator();
280 Value *PhiArg = CallInst::Create(Break, Broken, "", Insert);
281 NewPhi->setIncomingValue(i, PhiArg);
284 LoopPhiConditions.push_back(WeakTrackingVH(Phi));
288 if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
289 BasicBlock *Parent = Inst->getParent();
291 if (L->contains(Inst)) {
292 Insert = Parent->getTerminator();
294 Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime();
297 Value *Args[] = { Cond, Broken };
298 return CallInst::Create(IfBreak, Args, "", Insert);
301 // Insert IfBreak in the loop header TERM for constant COND other than true.
302 if (isa<Constant>(Cond)) {
303 Instruction *Insert = Cond == BoolTrue ?
304 Term : L->getHeader()->getTerminator();
306 Value *Args[] = { Cond, Broken };
307 return CallInst::Create(IfBreak, Args, "", Insert);
310 llvm_unreachable("Unhandled loop condition!");
313 /// \brief Handle a back edge (loop)
314 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
318 BasicBlock *BB = Term->getParent();
319 llvm::Loop *L = LI->getLoopFor(BB);
323 BasicBlock *Target = Term->getSuccessor(1);
324 PHINode *Broken = PHINode::Create(Int64, 0, "phi.broken", &Target->front());
326 SmallVector<WeakTrackingVH, 8> LoopPhiConditions;
327 Value *Cond = Term->getCondition();
328 Term->setCondition(BoolTrue);
329 Value *Arg = handleLoopCondition(Cond, Broken, L, Term, LoopPhiConditions);
331 for (BasicBlock *Pred : predecessors(Target))
332 Broken->addIncoming(Pred == BB ? Arg : Int64Zero, Pred);
334 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
336 for (WeakTrackingVH Val : reverse(LoopPhiConditions)) {
337 if (PHINode *Cond = cast_or_null<PHINode>(Val))
341 push(Term->getSuccessor(0), Arg);
344 /// \brief Close the last opened control flow
345 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
346 llvm::Loop *L = LI->getLoopFor(BB);
348 assert(Stack.back().first == BB);
350 if (L && L->getHeader() == BB) {
351 // We can't insert an EndCF call into a loop header, because it will
352 // get executed on every iteration of the loop, when it should be
353 // executed only once before the loop.
354 SmallVector <BasicBlock *, 8> Latches;
355 L->getLoopLatches(Latches);
357 SmallVector<BasicBlock *, 2> Preds;
358 for (BasicBlock *Pred : predecessors(BB)) {
359 if (!is_contained(Latches, Pred))
360 Preds.push_back(Pred);
363 BB = llvm::SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, false);
366 Value *Exec = popSaved();
367 Instruction *FirstInsertionPt = &*BB->getFirstInsertionPt();
368 if (!isa<UndefValue>(Exec) && !isa<UnreachableInst>(FirstInsertionPt))
369 CallInst::Create(EndCf, Exec, "", FirstInsertionPt);
372 /// \brief Annotate the control flow with intrinsics so the backend can
373 /// recognize if/then/else and loops.
374 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
375 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
376 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
377 DA = &getAnalysis<DivergenceAnalysis>();
379 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
380 E = df_end(&F.getEntryBlock()); I != E; ++I) {
382 BranchInst *Term = dyn_cast<BranchInst>(BB->getTerminator());
384 if (!Term || Term->isUnconditional()) {
385 if (isTopOfStack(BB))
386 closeControlFlow(BB);
391 if (I.nodeVisited(Term->getSuccessor(1))) {
392 if (isTopOfStack(BB))
393 closeControlFlow(BB);
399 if (isTopOfStack(BB)) {
400 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
401 if (Phi && Phi->getParent() == BB && isElse(Phi)) {
407 closeControlFlow(BB);
413 assert(Stack.empty());
417 /// \brief Create the annotation pass
418 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
419 return new SIAnnotateControlFlow();