CodeGeneration.cpp 14 KB

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