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/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Transforms/Utils/Local.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/DerivedTypes.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #define DEBUG_TYPE "si-annotate-control-flow"
50 // Complex types used in this pass
51 using StackEntry
= std::pair
<BasicBlock
*, Value
*>;
52 using StackVector
= SmallVector
<StackEntry
, 16>;
54 class SIAnnotateControlFlow
: public FunctionPass
{
55 LegacyDivergenceAnalysis
*DA
;
62 ConstantInt
*BoolTrue
;
63 ConstantInt
*BoolFalse
;
64 UndefValue
*BoolUndef
;
80 bool isUniform(BranchInst
*T
);
82 bool isTopOfStack(BasicBlock
*BB
);
86 void push(BasicBlock
*BB
, Value
*Saved
);
88 bool isElse(PHINode
*Phi
);
90 void eraseIfUnused(PHINode
*Phi
);
92 void openIf(BranchInst
*Term
);
94 void insertElse(BranchInst
*Term
);
97 handleLoopCondition(Value
*Cond
, PHINode
*Broken
, llvm::Loop
*L
,
99 SmallVectorImpl
<WeakTrackingVH
> &LoopPhiConditions
);
101 void handleLoop(BranchInst
*Term
);
103 void closeControlFlow(BasicBlock
*BB
);
108 SIAnnotateControlFlow() : FunctionPass(ID
) {}
110 bool doInitialization(Module
&M
) override
;
112 bool runOnFunction(Function
&F
) override
;
114 StringRef
getPassName() const override
{ return "SI annotate control flow"; }
116 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
117 AU
.addRequired
<LoopInfoWrapperPass
>();
118 AU
.addRequired
<DominatorTreeWrapperPass
>();
119 AU
.addRequired
<LegacyDivergenceAnalysis
>();
120 AU
.addPreserved
<DominatorTreeWrapperPass
>();
121 FunctionPass::getAnalysisUsage(AU
);
125 } // end anonymous namespace
127 INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow
, DEBUG_TYPE
,
128 "Annotate SI Control Flow", false, false)
129 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
130 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis
)
131 INITIALIZE_PASS_END(SIAnnotateControlFlow
, DEBUG_TYPE
,
132 "Annotate SI Control Flow", false, false)
134 char SIAnnotateControlFlow::ID
= 0;
136 /// Initialize all the types and constants used in the pass
137 bool SIAnnotateControlFlow::doInitialization(Module
&M
) {
138 LLVMContext
&Context
= M
.getContext();
140 Void
= Type::getVoidTy(Context
);
141 Boolean
= Type::getInt1Ty(Context
);
142 Int64
= Type::getInt64Ty(Context
);
143 ReturnStruct
= StructType::get(Boolean
, Int64
);
145 BoolTrue
= ConstantInt::getTrue(Context
);
146 BoolFalse
= ConstantInt::getFalse(Context
);
147 BoolUndef
= UndefValue::get(Boolean
);
148 Int64Zero
= ConstantInt::get(Int64
, 0);
150 If
= Intrinsic::getDeclaration(&M
, Intrinsic::amdgcn_if
);
151 Else
= Intrinsic::getDeclaration(&M
, Intrinsic::amdgcn_else
);
152 Break
= Intrinsic::getDeclaration(&M
, Intrinsic::amdgcn_break
);
153 IfBreak
= Intrinsic::getDeclaration(&M
, Intrinsic::amdgcn_if_break
);
154 ElseBreak
= Intrinsic::getDeclaration(&M
, Intrinsic::amdgcn_else_break
);
155 Loop
= Intrinsic::getDeclaration(&M
, Intrinsic::amdgcn_loop
);
156 EndCf
= Intrinsic::getDeclaration(&M
, Intrinsic::amdgcn_end_cf
);
160 /// Is the branch condition uniform or did the StructurizeCFG pass
161 /// consider it as such?
162 bool SIAnnotateControlFlow::isUniform(BranchInst
*T
) {
163 return DA
->isUniform(T
->getCondition()) ||
164 T
->getMetadata("structurizecfg.uniform") != nullptr;
167 /// Is BB the last block saved on the stack ?
168 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock
*BB
) {
169 return !Stack
.empty() && Stack
.back().first
== BB
;
172 /// Pop the last saved value from the control flow stack
173 Value
*SIAnnotateControlFlow::popSaved() {
174 return Stack
.pop_back_val().second
;
177 /// Push a BB and saved value to the control flow stack
178 void SIAnnotateControlFlow::push(BasicBlock
*BB
, Value
*Saved
) {
179 Stack
.push_back(std::make_pair(BB
, Saved
));
182 /// Can the condition represented by this PHI node treated like
184 bool SIAnnotateControlFlow::isElse(PHINode
*Phi
) {
185 BasicBlock
*IDom
= DT
->getNode(Phi
->getParent())->getIDom()->getBlock();
186 for (unsigned i
= 0, e
= Phi
->getNumIncomingValues(); i
!= e
; ++i
) {
187 if (Phi
->getIncomingBlock(i
) == IDom
) {
189 if (Phi
->getIncomingValue(i
) != BoolTrue
)
193 if (Phi
->getIncomingValue(i
) != BoolFalse
)
201 // Erase "Phi" if it is not used any more
202 void SIAnnotateControlFlow::eraseIfUnused(PHINode
*Phi
) {
203 if (RecursivelyDeleteDeadPHINode(Phi
)) {
204 LLVM_DEBUG(dbgs() << "Erased unused condition phi\n");
208 /// Open a new "If" block
209 void SIAnnotateControlFlow::openIf(BranchInst
*Term
) {
213 Value
*Ret
= CallInst::Create(If
, Term
->getCondition(), "", Term
);
214 Term
->setCondition(ExtractValueInst::Create(Ret
, 0, "", Term
));
215 push(Term
->getSuccessor(1), ExtractValueInst::Create(Ret
, 1, "", Term
));
218 /// Close the last "If" block and open a new "Else" block
219 void SIAnnotateControlFlow::insertElse(BranchInst
*Term
) {
220 if (isUniform(Term
)) {
223 Value
*Ret
= CallInst::Create(Else
, popSaved(), "", Term
);
224 Term
->setCondition(ExtractValueInst::Create(Ret
, 0, "", Term
));
225 push(Term
->getSuccessor(1), ExtractValueInst::Create(Ret
, 1, "", Term
));
228 /// Recursively handle the condition leading to a loop
229 Value
*SIAnnotateControlFlow::handleLoopCondition(
230 Value
*Cond
, PHINode
*Broken
, llvm::Loop
*L
, BranchInst
*Term
,
231 SmallVectorImpl
<WeakTrackingVH
> &LoopPhiConditions
) {
232 // Only search through PHI nodes which are inside the loop. If we try this
233 // with PHI nodes that are outside of the loop, we end up inserting new PHI
234 // nodes outside of the loop which depend on values defined inside the loop.
235 // This will break the module with
236 // 'Instruction does not dominate all users!' errors.
237 PHINode
*Phi
= nullptr;
238 if ((Phi
= dyn_cast
<PHINode
>(Cond
)) && L
->contains(Phi
)) {
239 BasicBlock
*Parent
= Phi
->getParent();
240 PHINode
*NewPhi
= PHINode::Create(Int64
, 0, "loop.phi", &Parent
->front());
243 // Handle all non-constant incoming values first
244 for (unsigned i
= 0, e
= Phi
->getNumIncomingValues(); i
!= e
; ++i
) {
245 Value
*Incoming
= Phi
->getIncomingValue(i
);
246 BasicBlock
*From
= Phi
->getIncomingBlock(i
);
247 if (isa
<ConstantInt
>(Incoming
)) {
248 NewPhi
->addIncoming(Broken
, From
);
252 Phi
->setIncomingValue(i
, BoolFalse
);
253 Value
*PhiArg
= handleLoopCondition(Incoming
, Broken
, L
,
254 Term
, LoopPhiConditions
);
255 NewPhi
->addIncoming(PhiArg
, From
);
258 BasicBlock
*IDom
= DT
->getNode(Parent
)->getIDom()->getBlock();
260 for (unsigned i
= 0, e
= Phi
->getNumIncomingValues(); i
!= e
; ++i
) {
261 Value
*Incoming
= Phi
->getIncomingValue(i
);
262 if (Incoming
!= BoolTrue
)
265 BasicBlock
*From
= Phi
->getIncomingBlock(i
);
267 // We're in the following situation:
273 // where we want to break out of the loop if the If-block is not taken.
274 // Due to the depth-first traversal, there should be an end.cf
275 // intrinsic in Parent, and we insert an else.break before it.
277 // Note that the end.cf need not be the first non-phi instruction
278 // of parent, particularly when we're dealing with a multi-level
279 // break, but it should occur within a group of intrinsic calls
280 // at the beginning of the block.
281 CallInst
*OldEnd
= dyn_cast
<CallInst
>(Parent
->getFirstInsertionPt());
282 while (OldEnd
&& OldEnd
->getCalledFunction() != EndCf
)
283 OldEnd
= dyn_cast
<CallInst
>(OldEnd
->getNextNode());
284 if (OldEnd
&& OldEnd
->getCalledFunction() == EndCf
) {
285 Value
*Args
[] = { OldEnd
->getArgOperand(0), NewPhi
};
286 Ret
= CallInst::Create(ElseBreak
, Args
, "", OldEnd
);
291 TerminatorInst
*Insert
= From
->getTerminator();
292 Value
*PhiArg
= CallInst::Create(Break
, Broken
, "", Insert
);
293 NewPhi
->setIncomingValue(i
, PhiArg
);
296 LoopPhiConditions
.push_back(WeakTrackingVH(Phi
));
300 if (Instruction
*Inst
= dyn_cast
<Instruction
>(Cond
)) {
301 BasicBlock
*Parent
= Inst
->getParent();
303 if (L
->contains(Inst
)) {
304 Insert
= Parent
->getTerminator();
306 Insert
= L
->getHeader()->getFirstNonPHIOrDbgOrLifetime();
309 Value
*Args
[] = { Cond
, Broken
};
310 return CallInst::Create(IfBreak
, Args
, "", Insert
);
313 // Insert IfBreak in the loop header TERM for constant COND other than true.
314 if (isa
<Constant
>(Cond
)) {
315 Instruction
*Insert
= Cond
== BoolTrue
?
316 Term
: L
->getHeader()->getTerminator();
318 Value
*Args
[] = { Cond
, Broken
};
319 return CallInst::Create(IfBreak
, Args
, "", Insert
);
322 llvm_unreachable("Unhandled loop condition!");
325 /// Handle a back edge (loop)
326 void SIAnnotateControlFlow::handleLoop(BranchInst
*Term
) {
330 BasicBlock
*BB
= Term
->getParent();
331 llvm::Loop
*L
= LI
->getLoopFor(BB
);
335 BasicBlock
*Target
= Term
->getSuccessor(1);
336 PHINode
*Broken
= PHINode::Create(Int64
, 0, "phi.broken", &Target
->front());
338 SmallVector
<WeakTrackingVH
, 8> LoopPhiConditions
;
339 Value
*Cond
= Term
->getCondition();
340 Term
->setCondition(BoolTrue
);
341 Value
*Arg
= handleLoopCondition(Cond
, Broken
, L
, Term
, LoopPhiConditions
);
343 for (BasicBlock
*Pred
: predecessors(Target
))
344 Broken
->addIncoming(Pred
== BB
? Arg
: Int64Zero
, Pred
);
346 Term
->setCondition(CallInst::Create(Loop
, Arg
, "", Term
));
348 for (WeakTrackingVH Val
: llvm::reverse(LoopPhiConditions
)) {
349 if (PHINode
*Cond
= cast_or_null
<PHINode
>(Val
))
353 push(Term
->getSuccessor(0), Arg
);
356 /// Close the last opened control flow
357 void SIAnnotateControlFlow::closeControlFlow(BasicBlock
*BB
) {
358 llvm::Loop
*L
= LI
->getLoopFor(BB
);
360 assert(Stack
.back().first
== BB
);
362 if (L
&& L
->getHeader() == BB
) {
363 // We can't insert an EndCF call into a loop header, because it will
364 // get executed on every iteration of the loop, when it should be
365 // executed only once before the loop.
366 SmallVector
<BasicBlock
*, 8> Latches
;
367 L
->getLoopLatches(Latches
);
369 SmallVector
<BasicBlock
*, 2> Preds
;
370 for (BasicBlock
*Pred
: predecessors(BB
)) {
371 if (!is_contained(Latches
, Pred
))
372 Preds
.push_back(Pred
);
375 BB
= SplitBlockPredecessors(BB
, Preds
, "endcf.split", DT
, LI
, nullptr,
379 Value
*Exec
= popSaved();
380 Instruction
*FirstInsertionPt
= &*BB
->getFirstInsertionPt();
381 if (!isa
<UndefValue
>(Exec
) && !isa
<UnreachableInst
>(FirstInsertionPt
))
382 CallInst::Create(EndCf
, Exec
, "", FirstInsertionPt
);
385 /// Annotate the control flow with intrinsics so the backend can
386 /// recognize if/then/else and loops.
387 bool SIAnnotateControlFlow::runOnFunction(Function
&F
) {
388 DT
= &getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
389 LI
= &getAnalysis
<LoopInfoWrapperPass
>().getLoopInfo();
390 DA
= &getAnalysis
<LegacyDivergenceAnalysis
>();
392 for (df_iterator
<BasicBlock
*> I
= df_begin(&F
.getEntryBlock()),
393 E
= df_end(&F
.getEntryBlock()); I
!= E
; ++I
) {
395 BranchInst
*Term
= dyn_cast
<BranchInst
>(BB
->getTerminator());
397 if (!Term
|| Term
->isUnconditional()) {
398 if (isTopOfStack(BB
))
399 closeControlFlow(BB
);
404 if (I
.nodeVisited(Term
->getSuccessor(1))) {
405 if (isTopOfStack(BB
))
406 closeControlFlow(BB
);
412 if (isTopOfStack(BB
)) {
413 PHINode
*Phi
= dyn_cast
<PHINode
>(Term
->getCondition());
414 if (Phi
&& Phi
->getParent() == BB
&& isElse(Phi
)) {
420 closeControlFlow(BB
);
426 if (!Stack
.empty()) {
427 // CFG was probably not structured.
428 report_fatal_error("failed to annotate CFG");
434 /// Create the annotation pass
435 FunctionPass
*llvm::createSIAnnotateControlFlowPass() {
436 return new SIAnnotateControlFlow();