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