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;
78 bool isUniform(BranchInst *T);
80 bool isTopOfStack(BasicBlock *BB);
84 void push(BasicBlock *BB, Value *Saved);
86 bool isElse(PHINode *Phi);
88 void eraseIfUnused(PHINode *Phi);
90 void openIf(BranchInst *Term);
92 void insertElse(BranchInst *Term);
95 handleLoopCondition(Value *Cond, PHINode *Broken, llvm::Loop *L,
98 void handleLoop(BranchInst *Term);
100 void closeControlFlow(BasicBlock *BB);
105 SIAnnotateControlFlow() : FunctionPass(ID) {}
107 bool doInitialization(Module &M) override;
109 bool runOnFunction(Function &F) override;
111 StringRef getPassName() const override { return "SI annotate control flow"; }
113 void getAnalysisUsage(AnalysisUsage &AU) const override {
114 AU.addRequired<LoopInfoWrapperPass>();
115 AU.addRequired<DominatorTreeWrapperPass>();
116 AU.addRequired<LegacyDivergenceAnalysis>();
117 AU.addPreserved<DominatorTreeWrapperPass>();
118 FunctionPass::getAnalysisUsage(AU);
122 } // end anonymous namespace
124 INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE,
125 "Annotate SI Control Flow", false, false)
126 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
127 INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
128 INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE,
129 "Annotate SI Control Flow", false, false)
131 char SIAnnotateControlFlow::ID = 0;
133 /// Initialize all the types and constants used in the pass
134 bool SIAnnotateControlFlow::doInitialization(Module &M) {
135 LLVMContext &Context = M.getContext();
137 Void = Type::getVoidTy(Context);
138 Boolean = Type::getInt1Ty(Context);
139 Int64 = Type::getInt64Ty(Context);
140 ReturnStruct = StructType::get(Boolean, Int64);
142 BoolTrue = ConstantInt::getTrue(Context);
143 BoolFalse = ConstantInt::getFalse(Context);
144 BoolUndef = UndefValue::get(Boolean);
145 Int64Zero = ConstantInt::get(Int64, 0);
147 If = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if);
148 Else = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_else);
149 IfBreak = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_if_break);
150 Loop = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_loop);
151 EndCf = Intrinsic::getDeclaration(&M, Intrinsic::amdgcn_end_cf);
155 /// Is the branch condition uniform or did the StructurizeCFG pass
156 /// consider it as such?
157 bool SIAnnotateControlFlow::isUniform(BranchInst *T) {
158 return DA->isUniform(T) ||
159 T->getMetadata("structurizecfg.uniform") != nullptr;
162 /// Is BB the last block saved on the stack ?
163 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) {
164 return !Stack.empty() && Stack.back().first == BB;
167 /// Pop the last saved value from the control flow stack
168 Value *SIAnnotateControlFlow::popSaved() {
169 return Stack.pop_back_val().second;
172 /// Push a BB and saved value to the control flow stack
173 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) {
174 Stack.push_back(std::make_pair(BB, Saved));
177 /// Can the condition represented by this PHI node treated like
179 bool SIAnnotateControlFlow::isElse(PHINode *Phi) {
180 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock();
181 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
182 if (Phi->getIncomingBlock(i) == IDom) {
184 if (Phi->getIncomingValue(i) != BoolTrue)
188 if (Phi->getIncomingValue(i) != BoolFalse)
196 // Erase "Phi" if it is not used any more
197 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) {
198 if (RecursivelyDeleteDeadPHINode(Phi)) {
199 LLVM_DEBUG(dbgs() << "Erased unused condition phi\n");
203 /// Open a new "If" block
204 void SIAnnotateControlFlow::openIf(BranchInst *Term) {
208 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term);
209 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
210 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
213 /// Close the last "If" block and open a new "Else" block
214 void SIAnnotateControlFlow::insertElse(BranchInst *Term) {
215 if (isUniform(Term)) {
218 Value *Ret = CallInst::Create(Else, popSaved(), "", Term);
219 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term));
220 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term));
223 /// Recursively handle the condition leading to a loop
224 Value *SIAnnotateControlFlow::handleLoopCondition(
225 Value *Cond, PHINode *Broken, llvm::Loop *L, BranchInst *Term) {
226 if (Instruction *Inst = dyn_cast<Instruction>(Cond)) {
227 BasicBlock *Parent = Inst->getParent();
229 if (L->contains(Inst)) {
230 Insert = Parent->getTerminator();
232 Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime();
235 Value *Args[] = { Cond, Broken };
236 return CallInst::Create(IfBreak, Args, "", Insert);
239 // Insert IfBreak in the loop header TERM for constant COND other than true.
240 if (isa<Constant>(Cond)) {
241 Instruction *Insert = Cond == BoolTrue ?
242 Term : L->getHeader()->getTerminator();
244 Value *Args[] = { Cond, Broken };
245 return CallInst::Create(IfBreak, Args, "", Insert);
248 llvm_unreachable("Unhandled loop condition!");
251 /// Handle a back edge (loop)
252 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) {
256 BasicBlock *BB = Term->getParent();
257 llvm::Loop *L = LI->getLoopFor(BB);
261 BasicBlock *Target = Term->getSuccessor(1);
262 PHINode *Broken = PHINode::Create(Int64, 0, "phi.broken", &Target->front());
264 Value *Cond = Term->getCondition();
265 Term->setCondition(BoolTrue);
266 Value *Arg = handleLoopCondition(Cond, Broken, L, Term);
268 for (BasicBlock *Pred : predecessors(Target))
269 Broken->addIncoming(Pred == BB ? Arg : Int64Zero, Pred);
271 Term->setCondition(CallInst::Create(Loop, Arg, "", Term));
273 push(Term->getSuccessor(0), Arg);
276 /// Close the last opened control flow
277 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) {
278 llvm::Loop *L = LI->getLoopFor(BB);
280 assert(Stack.back().first == BB);
282 if (L && L->getHeader() == BB) {
283 // We can't insert an EndCF call into a loop header, because it will
284 // get executed on every iteration of the loop, when it should be
285 // executed only once before the loop.
286 SmallVector <BasicBlock *, 8> Latches;
287 L->getLoopLatches(Latches);
289 SmallVector<BasicBlock *, 2> Preds;
290 for (BasicBlock *Pred : predecessors(BB)) {
291 if (!is_contained(Latches, Pred))
292 Preds.push_back(Pred);
295 BB = SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, nullptr,
299 Value *Exec = popSaved();
300 Instruction *FirstInsertionPt = &*BB->getFirstInsertionPt();
301 if (!isa<UndefValue>(Exec) && !isa<UnreachableInst>(FirstInsertionPt))
302 CallInst::Create(EndCf, Exec, "", FirstInsertionPt);
305 /// Annotate the control flow with intrinsics so the backend can
306 /// recognize if/then/else and loops.
307 bool SIAnnotateControlFlow::runOnFunction(Function &F) {
308 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
309 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
310 DA = &getAnalysis<LegacyDivergenceAnalysis>();
312 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()),
313 E = df_end(&F.getEntryBlock()); I != E; ++I) {
315 BranchInst *Term = dyn_cast<BranchInst>(BB->getTerminator());
317 if (!Term || Term->isUnconditional()) {
318 if (isTopOfStack(BB))
319 closeControlFlow(BB);
324 if (I.nodeVisited(Term->getSuccessor(1))) {
325 if (isTopOfStack(BB))
326 closeControlFlow(BB);
332 if (isTopOfStack(BB)) {
333 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition());
334 if (Phi && Phi->getParent() == BB && isElse(Phi)) {
340 closeControlFlow(BB);
346 if (!Stack.empty()) {
347 // CFG was probably not structured.
348 report_fatal_error("failed to annotate CFG");
354 /// Create the annotation pass
355 FunctionPass *llvm::createSIAnnotateControlFlowPass() {
356 return new SIAnnotateControlFlow();