CodeGeneration.cpp 14 KB

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