xref: /llvm-project/polly/lib/CodeGen/CodeGeneration.cpp (revision 0e370cf1a767efd8d55c346df995df6d43e3ff7f)
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 whether IslAstInfo uses the same isl_ctx. Since -polly-codegen
186   // reports itself to preserve DependenceInfo and IslAstInfo, we might get
187   // those analysis that were computed by a different ScopInfo for a different
188   // Scop structure. When the ScopInfo/Scop object is freed, there is a high
189   // probability that the new ScopInfo/Scop object will be created at the same
190   // heap position with the same address. Comparing whether the Scop or ScopInfo
191   // address is the expected therefore is unreliable.
192   // Instead, we compare the address of the isl_ctx object. Both, DependenceInfo
193   // and IslAstInfo must hold a reference to the isl_ctx object to ensure it is
194   // not freed before the destruction of those analyses which might happen after
195   // the destruction of the Scop/ScopInfo they refer to.  Hence, the isl_ctx
196   // will not be freed and its space not reused as long there is a
197   // DependenceInfo or IslAstInfo around.
198   IslAst &Ast = AI.getIslAst();
199   if (Ast.getSharedIslCtx() != S.getSharedIslCtx()) {
200     DEBUG(dbgs() << "Got an IstAst for a different Scop/isl_ctx\n");
201     return false;
202   }
203 
204   // Check if we created an isl_ast root node, otherwise exit.
205   isl_ast_node *AstRoot = Ast.getAst();
206   if (!AstRoot)
207     return false;
208 
209   // Collect statistics. Do it before we modify the IR to avoid having it any
210   // influence on the result.
211   auto ScopStats = S.getStatistics();
212   ScopsProcessed++;
213 
214   auto &DL = S.getFunction().getParent()->getDataLayout();
215   Region *R = &S.getRegion();
216   assert(!R->isTopLevelRegion() && "Top level regions are not supported");
217 
218   ScopAnnotator Annotator;
219 
220   simplifyRegion(R, &DT, &LI, &RI);
221   assert(R->isSimple());
222   BasicBlock *EnteringBB = S.getEnteringBlock();
223   assert(EnteringBB);
224   PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
225 
226   // Only build the run-time condition and parameters _after_ having
227   // introduced the conditional branch. This is important as the conditional
228   // branch will guard the original scop from new induction variables that
229   // the SCEVExpander may introduce while code generating the parameters and
230   // which may introduce scalar dependences that prevent us from correctly
231   // code generating this scop.
232   BBPair StartExitBlocks =
233       std::get<0>(executeScopConditionally(S, Builder.getTrue(), DT, RI, LI));
234   BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
235   BasicBlock *ExitBlock = std::get<1>(StartExitBlocks);
236 
237   removeLifetimeMarkers(R);
238   auto *SplitBlock = StartBlock->getSinglePredecessor();
239 
240   IslNodeBuilder NodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock);
241 
242   // All arrays must have their base pointers known before
243   // ScopAnnotator::buildAliasScopes.
244   NodeBuilder.allocateNewArrays(StartExitBlocks);
245   Annotator.buildAliasScopes(S);
246 
247   if (PerfMonitoring) {
248     PerfMonitor P(S, EnteringBB->getParent()->getParent());
249     P.initialize();
250     P.insertRegionStart(SplitBlock->getTerminator());
251 
252     BasicBlock *MergeBlock = ExitBlock->getUniqueSuccessor();
253     P.insertRegionEnd(MergeBlock->getTerminator());
254   }
255 
256   // First generate code for the hoisted invariant loads and transitively the
257   // parameters they reference. Afterwards, for the remaining parameters that
258   // might reference the hoisted loads. Finally, build the runtime check
259   // that might reference both hoisted loads as well as parameters.
260   // If the hoisting fails we have to bail and execute the original code.
261   Builder.SetInsertPoint(SplitBlock->getTerminator());
262   if (!NodeBuilder.preloadInvariantLoads()) {
263     // Patch the introduced branch condition to ensure that we always execute
264     // the original SCoP.
265     auto *FalseI1 = Builder.getFalse();
266     auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
267     SplitBBTerm->setOperand(0, FalseI1);
268 
269     // Since the other branch is hence ignored we mark it as unreachable and
270     // adjust the dominator tree accordingly.
271     auto *ExitingBlock = StartBlock->getUniqueSuccessor();
272     assert(ExitingBlock);
273     auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
274     assert(MergeBlock);
275     markBlockUnreachable(*StartBlock, Builder);
276     markBlockUnreachable(*ExitingBlock, Builder);
277     auto *ExitingBB = S.getExitingBlock();
278     assert(ExitingBB);
279     DT.changeImmediateDominator(MergeBlock, ExitingBB);
280     DT.eraseNode(ExitingBlock);
281 
282     isl_ast_node_free(AstRoot);
283   } else {
284     NodeBuilder.addParameters(S.getContext().release());
285     Value *RTC = NodeBuilder.createRTC(AI.getRunCondition());
286 
287     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
288 
289     // Explicitly set the insert point to the end of the block to avoid that a
290     // split at the builder's current
291     // insert position would move the malloc calls to the wrong BasicBlock.
292     // Ideally we would just split the block during allocation of the new
293     // arrays, but this would break the assumption that there are no blocks
294     // between polly.start and polly.exiting (at this point).
295     Builder.SetInsertPoint(StartBlock->getTerminator());
296 
297     NodeBuilder.create(AstRoot);
298     NodeBuilder.finalize();
299     fixRegionInfo(*EnteringBB->getParent(), *R->getParent(), RI);
300 
301     CodegenedScops++;
302     CodegenedAffineLoops += ScopStats.NumAffineLoops;
303     CodegenedBoxedLoops += ScopStats.NumBoxedLoops;
304   }
305 
306   Function *F = EnteringBB->getParent();
307   verifyGeneratedFunction(S, *F, AI);
308   for (auto *SubF : NodeBuilder.getParallelSubfunctions())
309     verifyGeneratedFunction(S, *SubF, AI);
310 
311   // Mark the function such that we run additional cleanup passes on this
312   // function (e.g. mem2reg to rediscover phi nodes).
313   F->addFnAttr("polly-optimized");
314   return true;
315 }
316 
317 namespace {
318 
319 class CodeGeneration : public ScopPass {
320 public:
321   static char ID;
322 
323   /// The data layout used.
324   const DataLayout *DL;
325 
326   /// @name The analysis passes we need to generate code.
327   ///
328   ///{
329   LoopInfo *LI;
330   IslAstInfo *AI;
331   DominatorTree *DT;
332   ScalarEvolution *SE;
333   RegionInfo *RI;
334   ///}
335 
336   CodeGeneration() : ScopPass(ID) {}
337 
338   /// Generate LLVM-IR for the SCoP @p S.
339   bool runOnScop(Scop &S) override {
340     // Skip SCoPs in case they're already code-generated by PPCGCodeGeneration.
341     if (S.isToBeSkipped())
342       return false;
343 
344     AI = &getAnalysis<IslAstInfoWrapperPass>().getAI();
345     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
346     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
347     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
348     DL = &S.getFunction().getParent()->getDataLayout();
349     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
350     return CodeGen(S, *AI, *LI, *DT, *SE, *RI);
351   }
352 
353   /// Register all analyses and transformation required.
354   void getAnalysisUsage(AnalysisUsage &AU) const override {
355     ScopPass::getAnalysisUsage(AU);
356 
357     AU.addRequired<DominatorTreeWrapperPass>();
358     AU.addRequired<IslAstInfoWrapperPass>();
359     AU.addRequired<RegionInfoPass>();
360     AU.addRequired<ScalarEvolutionWrapperPass>();
361     AU.addRequired<ScopDetectionWrapperPass>();
362     AU.addRequired<ScopInfoRegionPass>();
363     AU.addRequired<LoopInfoWrapperPass>();
364 
365     AU.addPreserved<DependenceInfo>();
366     AU.addPreserved<IslAstInfoWrapperPass>();
367 
368     // FIXME: We do not yet add regions for the newly generated code to the
369     //        region tree.
370   }
371 };
372 
373 } // namespace
374 
375 PreservedAnalyses CodeGenerationPass::run(Scop &S, ScopAnalysisManager &SAM,
376                                           ScopStandardAnalysisResults &AR,
377                                           SPMUpdater &U) {
378   auto &AI = SAM.getResult<IslAstAnalysis>(S, AR);
379   if (CodeGen(S, AI, AR.LI, AR.DT, AR.SE, AR.RI)) {
380     U.invalidateScop(S);
381     return PreservedAnalyses::none();
382   }
383 
384   return PreservedAnalyses::all();
385 }
386 
387 char CodeGeneration::ID = 1;
388 
389 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
390 
391 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
392                       "Polly - Create LLVM-IR from SCoPs", false, false);
393 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
394 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
395 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
396 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
397 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
398 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
399 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
400                     "Polly - Create LLVM-IR from SCoPs", false, false)
401