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 behavior 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/CodeGeneration.h"
23 #include "polly/CodeGen/IslAst.h"
24 #include "polly/CodeGen/IslNodeBuilder.h"
25 #include "polly/CodeGen/PerfMonitor.h"
26 #include "polly/CodeGen/Utils.h"
27 #include "polly/DependenceInfo.h"
28 #include "polly/LinkAllPasses.h"
29 #include "polly/Options.h"
30 #include "polly/ScopInfo.h"
31 #include "polly/Support/ScopHelper.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/BasicAliasAnalysis.h"
34 #include "llvm/Analysis/GlobalsModRef.h"
35 #include "llvm/Analysis/LoopInfo.h"
36 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/PassManager.h"
39 #include "llvm/IR/Verifier.h"
40 #include "llvm/Support/Debug.h"
41 
42 using namespace polly;
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "polly-codegen"
46 
47 static cl::opt<bool> Verify("polly-codegen-verify",
48                             cl::desc("Verify the function generated by Polly"),
49                             cl::Hidden, cl::init(false), cl::ZeroOrMore,
50                             cl::cat(PollyCategory));
51 
52 static cl::opt<bool>
53     PerfMonitoring("polly-codegen-perf-monitoring",
54                    cl::desc("Add run-time performance monitoring"), cl::Hidden,
55                    cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
56 
57 namespace polly {
58 /// Mark a basic block unreachable.
59 ///
60 /// Marks the basic block @p Block unreachable by equipping it with an
61 /// UnreachableInst.
62 void markBlockUnreachable(BasicBlock &Block, PollyIRBuilder &Builder) {
63   auto *OrigTerminator = Block.getTerminator();
64   Builder.SetInsertPoint(OrigTerminator);
65   Builder.CreateUnreachable();
66   OrigTerminator->eraseFromParent();
67 }
68 
69 } // namespace polly
70 
71 namespace {
72 
73 static void verifyGeneratedFunction(Scop &S, Function &F, IslAstInfo &AI) {
74   if (!Verify || !verifyFunction(F, &errs()))
75     return;
76 
77   DEBUG({
78     errs() << "== ISL Codegen created an invalid function ==\n\n== The "
79               "SCoP ==\n";
80     errs() << S;
81     errs() << "\n== The isl AST ==\n";
82     AI.print(errs());
83     errs() << "\n== The invalid function ==\n";
84     F.print(errs());
85   });
86 
87   llvm_unreachable("Polly generated function could not be verified. Add "
88                    "-polly-codegen-verify=false to disable this assertion.");
89 }
90 
91 // CodeGeneration adds a lot of BBs without updating the RegionInfo
92 // We make all created BBs belong to the scop's parent region without any
93 // nested structure to keep the RegionInfo verifier happy.
94 static void fixRegionInfo(Function &F, Region &ParentRegion, RegionInfo &RI) {
95   for (BasicBlock &BB : F) {
96     if (RI.getRegionFor(&BB))
97       continue;
98 
99     RI.setRegionFor(&BB, &ParentRegion);
100   }
101 }
102 
103 /// Remove all lifetime markers (llvm.lifetime.start, llvm.lifetime.end) from
104 /// @R.
105 ///
106 /// CodeGeneration does not copy lifetime markers into the optimized SCoP,
107 /// which would leave the them only in the original path. This can transform
108 /// code such as
109 ///
110 ///     llvm.lifetime.start(%p)
111 ///     llvm.lifetime.end(%p)
112 ///
113 /// into
114 ///
115 ///     if (RTC) {
116 ///       // generated code
117 ///     } else {
118 ///       // original code
119 ///       llvm.lifetime.start(%p)
120 ///     }
121 ///     llvm.lifetime.end(%p)
122 ///
123 /// The current StackColoring algorithm cannot handle if some, but not all,
124 /// paths from the end marker to the entry block cross the start marker. Same
125 /// for start markers that do not always cross the end markers. We avoid any
126 /// issues by removing all lifetime markers, even from the original code.
127 ///
128 /// A better solution could be to hoist all llvm.lifetime.start to the split
129 /// node and all llvm.lifetime.end to the merge node, which should be
130 /// conservatively correct.
131 static void removeLifetimeMarkers(Region *R) {
132   for (auto *BB : R->blocks()) {
133     auto InstIt = BB->begin();
134     auto InstEnd = BB->end();
135 
136     while (InstIt != InstEnd) {
137       auto NextIt = InstIt;
138       ++NextIt;
139 
140       if (auto *IT = dyn_cast<IntrinsicInst>(&*InstIt)) {
141         switch (IT->getIntrinsicID()) {
142         case llvm::Intrinsic::lifetime_start:
143         case llvm::Intrinsic::lifetime_end:
144           BB->getInstList().erase(InstIt);
145           break;
146         default:
147           break;
148         }
149       }
150 
151       InstIt = NextIt;
152     }
153   }
154 }
155 
156 static bool CodeGen(Scop &S, IslAstInfo &AI, LoopInfo &LI, DominatorTree &DT,
157                     ScalarEvolution &SE, RegionInfo &RI) {
158   // Check if we created an isl_ast root node, otherwise exit.
159   isl_ast_node *AstRoot = AI.getAst();
160   if (!AstRoot)
161     return false;
162 
163   auto &DL = S.getFunction().getParent()->getDataLayout();
164   Region *R = &S.getRegion();
165   assert(!R->isTopLevelRegion() && "Top level regions are not supported");
166 
167   ScopAnnotator Annotator;
168 
169   simplifyRegion(R, &DT, &LI, &RI);
170   assert(R->isSimple());
171   BasicBlock *EnteringBB = S.getEnteringBlock();
172   assert(EnteringBB);
173   PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
174 
175   // Only build the run-time condition and parameters _after_ having
176   // introduced the conditional branch. This is important as the conditional
177   // branch will guard the original scop from new induction variables that
178   // the SCEVExpander may introduce while code generating the parameters and
179   // which may introduce scalar dependences that prevent us from correctly
180   // code generating this scop.
181   BBPair StartExitBlocks =
182       std::get<0>(executeScopConditionally(S, Builder.getTrue(), DT, RI, LI));
183   BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
184   BasicBlock *ExitBlock = std::get<1>(StartExitBlocks);
185 
186   removeLifetimeMarkers(R);
187   auto *SplitBlock = StartBlock->getSinglePredecessor();
188 
189   IslNodeBuilder NodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock);
190 
191   // All arrays must have their base pointers known before
192   // ScopAnnotator::buildAliasScopes.
193   NodeBuilder.allocateNewArrays(StartExitBlocks);
194   Annotator.buildAliasScopes(S);
195 
196   if (PerfMonitoring) {
197     PerfMonitor P(S, EnteringBB->getParent()->getParent());
198     P.initialize();
199     P.insertRegionStart(SplitBlock->getTerminator());
200 
201     BasicBlock *MergeBlock = ExitBlock->getUniqueSuccessor();
202     P.insertRegionEnd(MergeBlock->getTerminator());
203   }
204 
205   // First generate code for the hoisted invariant loads and transitively the
206   // parameters they reference. Afterwards, for the remaining parameters that
207   // might reference the hoisted loads. Finally, build the runtime check
208   // that might reference both hoisted loads as well as parameters.
209   // If the hoisting fails we have to bail and execute the original code.
210   Builder.SetInsertPoint(SplitBlock->getTerminator());
211   if (!NodeBuilder.preloadInvariantLoads()) {
212 
213     // Patch the introduced branch condition to ensure that we always execute
214     // the original SCoP.
215     auto *FalseI1 = Builder.getFalse();
216     auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
217     SplitBBTerm->setOperand(0, FalseI1);
218 
219     // Since the other branch is hence ignored we mark it as unreachable and
220     // adjust the dominator tree accordingly.
221     auto *ExitingBlock = StartBlock->getUniqueSuccessor();
222     assert(ExitingBlock);
223     auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
224     assert(MergeBlock);
225     markBlockUnreachable(*StartBlock, Builder);
226     markBlockUnreachable(*ExitingBlock, Builder);
227     auto *ExitingBB = S.getExitingBlock();
228     assert(ExitingBB);
229     DT.changeImmediateDominator(MergeBlock, ExitingBB);
230     DT.eraseNode(ExitingBlock);
231 
232     isl_ast_node_free(AstRoot);
233   } else {
234     NodeBuilder.addParameters(S.getContext().release());
235     Value *RTC = NodeBuilder.createRTC(AI.getRunCondition());
236 
237     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
238 
239     // Explicitly set the insert point to the end of the block to avoid that a
240     // split at the builder's current
241     // insert position would move the malloc calls to the wrong BasicBlock.
242     // Ideally we would just split the block during allocation of the new
243     // arrays, but this would break the assumption that there are no blocks
244     // between polly.start and polly.exiting (at this point).
245     Builder.SetInsertPoint(StartBlock->getTerminator());
246 
247     NodeBuilder.create(AstRoot);
248     NodeBuilder.finalize();
249     fixRegionInfo(*EnteringBB->getParent(), *R->getParent(), RI);
250   }
251 
252   Function *F = EnteringBB->getParent();
253   verifyGeneratedFunction(S, *F, AI);
254   for (auto *SubF : NodeBuilder.getParallelSubfunctions())
255     verifyGeneratedFunction(S, *SubF, AI);
256 
257   // Mark the function such that we run additional cleanup passes on this
258   // function (e.g. mem2reg to rediscover phi nodes).
259   F->addFnAttr("polly-optimized");
260   return true;
261 }
262 
263 class CodeGeneration : public ScopPass {
264 public:
265   static char ID;
266 
267   CodeGeneration() : ScopPass(ID) {}
268 
269   /// The data layout used.
270   const DataLayout *DL;
271 
272   /// @name The analysis passes we need to generate code.
273   ///
274   ///{
275   LoopInfo *LI;
276   IslAstInfo *AI;
277   DominatorTree *DT;
278   ScalarEvolution *SE;
279   RegionInfo *RI;
280   ///}
281 
282   /// Generate LLVM-IR for the SCoP @p S.
283   bool runOnScop(Scop &S) override {
284     // Skip SCoPs in case they're already code-generated by PPCGCodeGeneration.
285     if (S.isToBeSkipped())
286       return false;
287 
288     AI = &getAnalysis<IslAstInfoWrapperPass>().getAI();
289     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
290     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
291     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
292     DL = &S.getFunction().getParent()->getDataLayout();
293     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
294     return CodeGen(S, *AI, *LI, *DT, *SE, *RI);
295   }
296 
297   /// Register all analyses and transformation required.
298   void getAnalysisUsage(AnalysisUsage &AU) const override {
299     AU.addRequired<DominatorTreeWrapperPass>();
300     AU.addRequired<IslAstInfoWrapperPass>();
301     AU.addRequired<RegionInfoPass>();
302     AU.addRequired<ScalarEvolutionWrapperPass>();
303     AU.addRequired<ScopDetectionWrapperPass>();
304     AU.addRequired<ScopInfoRegionPass>();
305     AU.addRequired<LoopInfoWrapperPass>();
306 
307     AU.addPreserved<DependenceInfo>();
308 
309     AU.addPreserved<AAResultsWrapperPass>();
310     AU.addPreserved<BasicAAWrapperPass>();
311     AU.addPreserved<LoopInfoWrapperPass>();
312     AU.addPreserved<DominatorTreeWrapperPass>();
313     AU.addPreserved<GlobalsAAWrapperPass>();
314     AU.addPreserved<IslAstInfoWrapperPass>();
315     AU.addPreserved<ScopDetectionWrapperPass>();
316     AU.addPreserved<ScalarEvolutionWrapperPass>();
317     AU.addPreserved<SCEVAAWrapperPass>();
318 
319     // FIXME: We do not yet add regions for the newly generated code to the
320     //        region tree.
321     AU.addPreserved<RegionInfoPass>();
322     AU.addPreserved<ScopInfoRegionPass>();
323   }
324 };
325 } // namespace
326 
327 PreservedAnalyses
328 polly::CodeGenerationPass::run(Scop &S, ScopAnalysisManager &SAM,
329                                ScopStandardAnalysisResults &AR, SPMUpdater &U) {
330   auto &AI = SAM.getResult<IslAstAnalysis>(S, AR);
331   if (CodeGen(S, AI, AR.LI, AR.DT, AR.SE, AR.RI))
332     return PreservedAnalyses::none();
333 
334   return PreservedAnalyses::all();
335 }
336 
337 char CodeGeneration::ID = 1;
338 
339 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
340 
341 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
342                       "Polly - Create LLVM-IR from SCoPs", false, false);
343 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
344 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
345 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
346 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
347 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
348 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
349 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
350                     "Polly - Create LLVM-IR from SCoPs", false, false)
351