1 //===------ CodeGeneration.cpp - Code generate the Scops using ISL. ----======//
2 //
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 //===----------------------------------------------------------------------===//
9 //
10 // The CodeGeneration pass takes a Scop created by ScopInfo and translates it
11 // back to LLVM-IR using the ISL code generator.
12 //
13 // The Scop describes the high level memory behaviour of a control flow region.
14 // Transformation passes can update the schedule (execution order) of statements
15 // in the Scop. ISL is used to generate an abstract syntax tree that reflects
16 // the updated execution order. This clast is used to create new LLVM-IR that is
17 // computationally equivalent to the original control flow region, but executes
18 // its code in the new execution order defined by the changed schedule.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "polly/CodeGen/IslAst.h"
23 #include "polly/CodeGen/IslNodeBuilder.h"
24 #include "polly/CodeGen/Utils.h"
25 #include "polly/DependenceInfo.h"
26 #include "polly/LinkAllPasses.h"
27 #include "polly/Options.h"
28 #include "polly/ScopInfo.h"
29 #include "polly/Support/ScopHelper.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/BasicAliasAnalysis.h"
32 #include "llvm/Analysis/GlobalsModRef.h"
33 #include "llvm/Analysis/PostDominators.h"
34 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/Support/Debug.h"
38 
39 using namespace polly;
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "polly-codegen"
43 
44 static cl::opt<bool> Verify("polly-codegen-verify",
45                             cl::desc("Verify the function generated by Polly"),
46                             cl::Hidden, cl::init(true), cl::ZeroOrMore,
47                             cl::cat(PollyCategory));
48 
49 namespace {
50 class CodeGeneration : public ScopPass {
51 public:
52   static char ID;
53 
54   CodeGeneration() : ScopPass(ID) {}
55 
56   /// The datalayout used
57   const DataLayout *DL;
58 
59   /// @name The analysis passes we need to generate code.
60   ///
61   ///{
62   LoopInfo *LI;
63   IslAstInfo *AI;
64   DominatorTree *DT;
65   ScalarEvolution *SE;
66   RegionInfo *RI;
67   ///}
68 
69   void verifyGeneratedFunction(Scop &S, Function &F) {
70     if (!verifyFunction(F, &errs()) || !Verify)
71       return;
72 
73     DEBUG({
74       errs() << "== ISL Codegen created an invalid function ==\n\n== The "
75                 "SCoP ==\n";
76       S.print(errs());
77       errs() << "\n== The isl AST ==\n";
78       AI->printScop(errs(), S);
79       errs() << "\n== The invalid function ==\n";
80       F.print(errs());
81     });
82 
83     llvm_unreachable("Polly generated function could not be verified. Add "
84                      "-polly-codegen-verify=false to disable this assertion.");
85   }
86 
87   // CodeGeneration adds a lot of BBs without updating the RegionInfo
88   // We make all created BBs belong to the scop's parent region without any
89   // nested structure to keep the RegionInfo verifier happy.
90   void fixRegionInfo(Function *F, Region *ParentRegion) {
91     for (BasicBlock &BB : *F) {
92       if (RI->getRegionFor(&BB))
93         continue;
94 
95       RI->setRegionFor(&BB, ParentRegion);
96     }
97   }
98 
99   /// Mark a basic block unreachable.
100   ///
101   /// Marks the basic block @p Block unreachable by equipping it with an
102   /// UnreachableInst.
103   void markBlockUnreachable(BasicBlock &Block, PollyIRBuilder &Builder) {
104     auto *OrigTerminator = Block.getTerminator();
105     Builder.SetInsertPoint(OrigTerminator);
106     Builder.CreateUnreachable();
107     OrigTerminator->eraseFromParent();
108   }
109 
110   /// Generate LLVM-IR for the SCoP @p S.
111   bool runOnScop(Scop &S) override {
112     AI = &getAnalysis<IslAstInfo>();
113 
114     // Check if we created an isl_ast root node, otherwise exit.
115     isl_ast_node *AstRoot = AI->getAst();
116     if (!AstRoot)
117       return false;
118 
119     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
120     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
121     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
122     DL = &S.getFunction().getParent()->getDataLayout();
123     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
124     Region *R = &S.getRegion();
125     assert(!R->isTopLevelRegion() && "Top level regions are not supported");
126 
127     ScopAnnotator Annotator;
128     Annotator.buildAliasScopes(S);
129 
130     simplifyRegion(R, DT, LI, RI);
131     assert(R->isSimple());
132     BasicBlock *EnteringBB = S.getEnteringBlock();
133     assert(EnteringBB);
134     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
135 
136     // Only build the run-time condition and parameters _after_ having
137     // introduced the conditional branch. This is important as the conditional
138     // branch will guard the original scop from new induction variables that
139     // the SCEVExpander may introduce while code generating the parameters and
140     // which may introduce scalar dependences that prevent us from correctly
141     // code generating this scop.
142     BasicBlock *StartBlock =
143         executeScopConditionally(S, this, Builder.getTrue());
144     auto *SplitBlock = StartBlock->getSinglePredecessor();
145 
146     IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S,
147                                StartBlock);
148 
149     // First generate code for the hoisted invariant loads and transitively the
150     // parameters they reference. Afterwards, for the remaining parameters that
151     // might reference the hoisted loads. Finally, build the runtime check
152     // that might reference both hoisted loads as well as parameters.
153     // If the hoisting fails we have to bail and execute the original code.
154     Builder.SetInsertPoint(SplitBlock->getTerminator());
155     if (!NodeBuilder.preloadInvariantLoads()) {
156 
157       // Patch the introduced branch condition to ensure that we always execute
158       // the original SCoP.
159       auto *FalseI1 = Builder.getFalse();
160       auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
161       SplitBBTerm->setOperand(0, FalseI1);
162 
163       // Since the other branch is hence ignored we mark it as unreachable and
164       // adjust the dominator tree accordingly.
165       auto *ExitingBlock = StartBlock->getUniqueSuccessor();
166       assert(ExitingBlock);
167       auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
168       assert(MergeBlock);
169       markBlockUnreachable(*StartBlock, Builder);
170       markBlockUnreachable(*ExitingBlock, Builder);
171       auto *ExitingBB = S.getExitingBlock();
172       assert(ExitingBB);
173       DT->changeImmediateDominator(MergeBlock, ExitingBB);
174       DT->eraseNode(ExitingBlock);
175 
176       isl_ast_node_free(AstRoot);
177     } else {
178       NodeBuilder.allocateNewArrays();
179       NodeBuilder.addParameters(S.getContext());
180       Value *RTC = NodeBuilder.createRTC(AI->getRunCondition());
181 
182       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
183       Builder.SetInsertPoint(&StartBlock->front());
184 
185       NodeBuilder.create(AstRoot);
186       NodeBuilder.finalize();
187       fixRegionInfo(EnteringBB->getParent(), R->getParent());
188     }
189 
190     Function *F = EnteringBB->getParent();
191     verifyGeneratedFunction(S, *F);
192     for (auto *SubF : NodeBuilder.getParallelSubfunctions())
193       verifyGeneratedFunction(S, *SubF);
194 
195     // Mark the function such that we run additional cleanup passes on this
196     // function (e.g. mem2reg to rediscover phi nodes).
197     F->addFnAttr("polly-optimized");
198 
199     return true;
200   }
201 
202   /// Register all analyses and transformation required.
203   void getAnalysisUsage(AnalysisUsage &AU) const override {
204     AU.addRequired<DominatorTreeWrapperPass>();
205     AU.addRequired<IslAstInfo>();
206     AU.addRequired<RegionInfoPass>();
207     AU.addRequired<ScalarEvolutionWrapperPass>();
208     AU.addRequired<ScopDetection>();
209     AU.addRequired<ScopInfoRegionPass>();
210     AU.addRequired<LoopInfoWrapperPass>();
211 
212     AU.addPreserved<DependenceInfo>();
213 
214     AU.addPreserved<AAResultsWrapperPass>();
215     AU.addPreserved<BasicAAWrapperPass>();
216     AU.addPreserved<LoopInfoWrapperPass>();
217     AU.addPreserved<DominatorTreeWrapperPass>();
218     AU.addPreserved<GlobalsAAWrapperPass>();
219     AU.addPreserved<PostDominatorTreeWrapperPass>();
220     AU.addPreserved<IslAstInfo>();
221     AU.addPreserved<ScopDetection>();
222     AU.addPreserved<ScalarEvolutionWrapperPass>();
223     AU.addPreserved<SCEVAAWrapperPass>();
224 
225     // FIXME: We do not yet add regions for the newly generated code to the
226     //        region tree.
227     AU.addPreserved<RegionInfoPass>();
228     AU.addPreserved<ScopInfoRegionPass>();
229   }
230 };
231 } // namespace
232 
233 char CodeGeneration::ID = 1;
234 
235 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
236 
237 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
238                       "Polly - Create LLVM-IR from SCoPs", false, false);
239 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
240 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
241 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
242 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
243 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
244 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
245 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
246                     "Polly - Create LLVM-IR from SCoPs", false, false)
247