blob: 6aa36088e91598c64d1676ca3259b5ea1f3a818a [file] [log] [blame]
Tobias Grosser09d30692015-05-12 07:45:52 +00001//===------ CodeGeneration.cpp - Code generate the Scops using ISL. ----======//
Sebastian Pop082cea82012-05-07 16:20:07 +00002//
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//
Tobias Grosser09d30692015-05-12 07:45:52 +000010// The CodeGeneration pass takes a Scop created by ScopInfo and translates it
Sebastian Pop082cea82012-05-07 16:20:07 +000011// back to LLVM-IR using the ISL code generator.
12//
13// The Scop describes the high level memory behaviour 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
Tobias Grosser54839312015-04-21 11:37:25 +000018// its code in the new execution order defined by the changed schedule.
Sebastian Pop082cea82012-05-07 16:20:07 +000019//
20//===----------------------------------------------------------------------===//
Tobias Grosserf3ba5b52015-04-27 12:17:22 +000021
Tobias Grosser83628182013-05-07 08:11:54 +000022#include "polly/CodeGen/IslAst.h"
Tobias Grosser5624d3c2015-12-21 12:38:56 +000023#include "polly/CodeGen/IslNodeBuilder.h"
Tobias Grosser65371af2017-04-03 14:55:37 +000024#include "polly/CodeGen/PerfMonitor.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/CodeGen/Utils.h"
Johannes Doerfertf6557f92015-03-04 22:43:40 +000026#include "polly/DependenceInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000027#include "polly/LinkAllPasses.h"
Tobias Grosser58e58542016-02-19 11:07:12 +000028#include "polly/Options.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000029#include "polly/ScopInfo.h"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000030#include "polly/Support/ScopHelper.h"
Chandler Carruth66ef16b2015-09-09 22:13:56 +000031#include "llvm/Analysis/AliasAnalysis.h"
32#include "llvm/Analysis/BasicAliasAnalysis.h"
33#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth66ef16b2015-09-09 22:13:56 +000034#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000035#include "llvm/IR/Module.h"
36#include "llvm/IR/Verifier.h"
37#include "llvm/Support/Debug.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000038
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000039using namespace polly;
40using namespace llvm;
41
Tobias Grosser09d30692015-05-12 07:45:52 +000042#define DEBUG_TYPE "polly-codegen"
Chandler Carruth95fef942014-04-22 03:30:19 +000043
Tobias Grosser58e58542016-02-19 11:07:12 +000044static cl::opt<bool> Verify("polly-codegen-verify",
45 cl::desc("Verify the function generated by Polly"),
Tobias Grosserf1372212017-04-28 19:15:28 +000046 cl::Hidden, cl::init(false), cl::ZeroOrMore,
Tobias Grosser58e58542016-02-19 11:07:12 +000047 cl::cat(PollyCategory));
48
Tobias Grosser65371af2017-04-03 14:55:37 +000049static cl::opt<bool>
50 PerfMonitoring("polly-codegen-perf-monitoring",
51 cl::desc("Add run-time performance monitoring"), cl::Hidden,
52 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
53
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000054namespace {
Tobias Grosser09d30692015-05-12 07:45:52 +000055class CodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +000056public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000057 static char ID;
58
Tobias Grosser09d30692015-05-12 07:45:52 +000059 CodeGeneration() : ScopPass(ID) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000060
Tobias Grosserc80d6972016-09-02 06:33:33 +000061 /// The datalayout used
Tobias Grossere3c05582014-11-15 21:32:53 +000062 const DataLayout *DL;
63
Johannes Doerfert38262242014-09-10 14:50:23 +000064 /// @name The analysis passes we need to generate code.
65 ///
66 ///{
67 LoopInfo *LI;
68 IslAstInfo *AI;
69 DominatorTree *DT;
70 ScalarEvolution *SE;
Michael Kruse22370882015-08-11 14:39:21 +000071 RegionInfo *RI;
Johannes Doerfert38262242014-09-10 14:50:23 +000072 ///}
73
Tobias Grosser58e58542016-02-19 11:07:12 +000074 void verifyGeneratedFunction(Scop &S, Function &F) {
Tobias Grosserd4399112017-04-28 19:08:20 +000075 if (!Verify || !verifyFunction(F, &errs()))
Tobias Grosser58e58542016-02-19 11:07:12 +000076 return;
Johannes Doerfert0b169c02015-02-27 17:37:05 +000077
78 DEBUG({
79 errs() << "== ISL Codegen created an invalid function ==\n\n== The "
80 "SCoP ==\n";
81 S.print(errs());
82 errs() << "\n== The isl AST ==\n";
Philip Pfaffe2b852e22017-05-23 10:12:56 +000083 AI->print(errs());
Johannes Doerfert0b169c02015-02-27 17:37:05 +000084 errs() << "\n== The invalid function ==\n";
85 F.print(errs());
Johannes Doerfert0b169c02015-02-27 17:37:05 +000086 });
87
Tobias Grosser58e58542016-02-19 11:07:12 +000088 llvm_unreachable("Polly generated function could not be verified. Add "
89 "-polly-codegen-verify=false to disable this assertion.");
Johannes Doerfert0b169c02015-02-27 17:37:05 +000090 }
91
Michael Kruse9c483c52015-08-11 14:47:37 +000092 // CodeGeneration adds a lot of BBs without updating the RegionInfo
93 // We make all created BBs belong to the scop's parent region without any
94 // nested structure to keep the RegionInfo verifier happy.
95 void fixRegionInfo(Function *F, Region *ParentRegion) {
96 for (BasicBlock &BB : *F) {
97 if (RI->getRegionFor(&BB))
98 continue;
99
100 RI->setRegionFor(&BB, ParentRegion);
101 }
102 }
103
Tobias Grosserc80d6972016-09-02 06:33:33 +0000104 /// Mark a basic block unreachable.
Tobias Grosserbfb6a962016-03-23 06:57:51 +0000105 ///
106 /// Marks the basic block @p Block unreachable by equipping it with an
107 /// UnreachableInst.
108 void markBlockUnreachable(BasicBlock &Block, PollyIRBuilder &Builder) {
109 auto *OrigTerminator = Block.getTerminator();
110 Builder.SetInsertPoint(OrigTerminator);
111 Builder.CreateUnreachable();
112 OrigTerminator->eraseFromParent();
113 }
114
Michael Kruse895f5d82017-04-05 20:09:59 +0000115 /// Remove all lifetime markers (llvm.lifetime.start, llvm.lifetime.end) from
116 /// @R.
117 ///
118 /// CodeGeneration does not copy lifetime markers into the optimized SCoP,
119 /// which would leave the them only in the original path. This can transform
120 /// code such as
121 ///
122 /// llvm.lifetime.start(%p)
123 /// llvm.lifetime.end(%p)
124 ///
125 /// into
126 ///
127 /// if (RTC) {
128 /// // generated code
129 /// } else {
130 /// // original code
131 /// llvm.lifetime.start(%p)
132 /// }
133 /// llvm.lifetime.end(%p)
134 ///
135 /// The current StackColoring algorithm cannot handle if some, but not all,
136 /// paths from the end marker to the entry block cross the start marker. Same
137 /// for start markers that do not always cross the end markers. We avoid any
138 /// issues by removing all lifetime markers, even from the original code.
139 ///
140 /// A better solution could be to hoist all llvm.lifetime.start to the split
141 /// node and all llvm.lifetime.end to the merge node, which should be
142 /// conservatively correct.
143 void removeLifetimeMarkers(Region *R) {
144 for (auto *BB : R->blocks()) {
145 auto InstIt = BB->begin();
146 auto InstEnd = BB->end();
147
148 while (InstIt != InstEnd) {
149 auto NextIt = InstIt;
150 ++NextIt;
151
152 if (auto *IT = dyn_cast<IntrinsicInst>(&*InstIt)) {
153 switch (IT->getIntrinsicID()) {
154 case llvm::Intrinsic::lifetime_start:
155 case llvm::Intrinsic::lifetime_end:
156 BB->getInstList().erase(InstIt);
157 break;
158 default:
159 break;
160 }
161 }
162
163 InstIt = NextIt;
164 }
165 }
166 }
167
Tobias Grosserc80d6972016-09-02 06:33:33 +0000168 /// Generate LLVM-IR for the SCoP @p S.
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000169 bool runOnScop(Scop &S) override {
Philip Pfaffe2b852e22017-05-23 10:12:56 +0000170 AI = &getAnalysis<IslAstInfoWrapperPass>().getAI();
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000171
172 // Check if we created an isl_ast root node, otherwise exit.
173 isl_ast_node *AstRoot = AI->getAst();
174 if (!AstRoot)
175 return false;
176
177 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfert38262242014-09-10 14:50:23 +0000178 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosserc5bcf242015-08-17 10:57:08 +0000179 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert3f52e352016-05-23 12:38:05 +0000180 DL = &S.getFunction().getParent()->getDataLayout();
Michael Kruse22370882015-08-11 14:39:21 +0000181 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
182 Region *R = &S.getRegion();
183 assert(!R->isTopLevelRegion() && "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000184
Tobias Grosserd78616f2015-10-04 11:19:13 +0000185 ScopAnnotator Annotator;
Tobias Grosser6325cd22015-04-27 10:43:10 +0000186 Annotator.buildAliasScopes(S);
Johannes Doerfertecdf2632014-10-02 15:31:24 +0000187
Michael Kruse22370882015-08-11 14:39:21 +0000188 simplifyRegion(R, DT, LI, RI);
189 assert(R->isSimple());
Johannes Doerfertef744432016-05-23 12:42:38 +0000190 BasicBlock *EnteringBB = S.getEnteringBlock();
Michael Kruse22370882015-08-11 14:39:21 +0000191 assert(EnteringBB);
Johannes Doerfert38262242014-09-10 14:50:23 +0000192 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000193
Tobias Grosser67942382015-03-28 09:34:40 +0000194 // Only build the run-time condition and parameters _after_ having
195 // introduced the conditional branch. This is important as the conditional
196 // branch will guard the original scop from new induction variables that
197 // the SCEVExpander may introduce while code generating the parameters and
198 // which may introduce scalar dependences that prevent us from correctly
199 // code generating this scop.
200 BasicBlock *StartBlock =
Philip Pfaffe2d950f32017-04-04 10:01:53 +0000201 executeScopConditionally(S, Builder.getTrue(), *DT, *RI, *LI);
Michael Kruse895f5d82017-04-05 20:09:59 +0000202 removeLifetimeMarkers(R);
Tobias Grosserbfb6a962016-03-23 06:57:51 +0000203 auto *SplitBlock = StartBlock->getSinglePredecessor();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000204
Philip Pfaffe2d950f32017-04-04 10:01:53 +0000205 IslNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, S,
Eli Friedmanacf80062016-11-02 22:32:23 +0000206 StartBlock);
207
Tobias Grosser65371af2017-04-03 14:55:37 +0000208 if (PerfMonitoring) {
209 PerfMonitor P(EnteringBB->getParent()->getParent());
210 P.initialize();
211 P.insertRegionStart(SplitBlock->getTerminator());
212
213 BasicBlock *MergeBlock = SplitBlock->getTerminator()
214 ->getSuccessor(0)
215 ->getUniqueSuccessor()
216 ->getUniqueSuccessor();
217 P.insertRegionEnd(MergeBlock->getTerminator());
218 }
219
Johannes Doerfert09e36972015-10-07 20:17:36 +0000220 // First generate code for the hoisted invariant loads and transitively the
221 // parameters they reference. Afterwards, for the remaining parameters that
222 // might reference the hoisted loads. Finally, build the runtime check
223 // that might reference both hoisted loads as well as parameters.
Johannes Doerfertc4898502015-11-07 19:46:04 +0000224 // If the hoisting fails we have to bail and execute the original code.
Tobias Grosser67942382015-03-28 09:34:40 +0000225 Builder.SetInsertPoint(SplitBlock->getTerminator());
Johannes Doerfertc4898502015-11-07 19:46:04 +0000226 if (!NodeBuilder.preloadInvariantLoads()) {
Johannes Doerfert1dd6e372015-11-08 16:34:17 +0000227
Tobias Grosserbfb6a962016-03-23 06:57:51 +0000228 // Patch the introduced branch condition to ensure that we always execute
229 // the original SCoP.
Johannes Doerfertc4898502015-11-07 19:46:04 +0000230 auto *FalseI1 = Builder.getFalse();
Johannes Doerfert37977072015-11-08 17:57:41 +0000231 auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
232 SplitBBTerm->setOperand(0, FalseI1);
Johannes Doerfert1dd6e372015-11-08 16:34:17 +0000233
Tobias Grosserbfb6a962016-03-23 06:57:51 +0000234 // Since the other branch is hence ignored we mark it as unreachable and
235 // adjust the dominator tree accordingly.
236 auto *ExitingBlock = StartBlock->getUniqueSuccessor();
237 assert(ExitingBlock);
238 auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
239 assert(MergeBlock);
240 markBlockUnreachable(*StartBlock, Builder);
241 markBlockUnreachable(*ExitingBlock, Builder);
Johannes Doerfertef744432016-05-23 12:42:38 +0000242 auto *ExitingBB = S.getExitingBlock();
Tobias Grosserbfb6a962016-03-23 06:57:51 +0000243 assert(ExitingBB);
244 DT->changeImmediateDominator(MergeBlock, ExitingBB);
245 DT->eraseNode(ExitingBlock);
246
247 isl_ast_node_free(AstRoot);
Johannes Doerfert1dd6e372015-11-08 16:34:17 +0000248 } else {
Roman Gareevd7754a12016-07-30 09:25:51 +0000249 NodeBuilder.allocateNewArrays();
Johannes Doerfert1dd6e372015-11-08 16:34:17 +0000250 NodeBuilder.addParameters(S.getContext());
Tobias Grosser0aa29532016-08-08 15:41:52 +0000251 Value *RTC = NodeBuilder.createRTC(AI->getRunCondition());
Johannes Doerfert404a0f82016-05-12 15:12:43 +0000252
Tobias Grosser3717aa52016-06-11 19:17:15 +0000253 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
254 Builder.SetInsertPoint(&StartBlock->front());
255
256 NodeBuilder.create(AstRoot);
Tobias Grosser8ed5e592016-07-25 09:15:57 +0000257 NodeBuilder.finalize();
Johannes Doerfert1dd6e372015-11-08 16:34:17 +0000258 fixRegionInfo(EnteringBB->getParent(), R->getParent());
Johannes Doerfertc4898502015-11-07 19:46:04 +0000259 }
260
Johannes Doerfert6a6a6712016-06-06 12:13:24 +0000261 Function *F = EnteringBB->getParent();
262 verifyGeneratedFunction(S, *F);
Johannes Doerferta9dc5292016-04-08 18:16:02 +0000263 for (auto *SubF : NodeBuilder.getParallelSubfunctions())
264 verifyGeneratedFunction(S, *SubF);
Tobias Grosser652f7802016-02-14 20:56:49 +0000265
Michael Kruse4c86a1d2015-11-26 12:36:25 +0000266 // Mark the function such that we run additional cleanup passes on this
267 // function (e.g. mem2reg to rediscover phi nodes).
Michael Kruse4c86a1d2015-11-26 12:36:25 +0000268 F->addFnAttr("polly-optimized");
269
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000270 return true;
271 }
272
Tobias Grosserc80d6972016-09-02 06:33:33 +0000273 /// Register all analyses and transformation required.
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000274 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tobias Grosser42aff302014-01-13 22:29:56 +0000275 AU.addRequired<DominatorTreeWrapperPass>();
Philip Pfaffe2b852e22017-05-23 10:12:56 +0000276 AU.addRequired<IslAstInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000277 AU.addRequired<RegionInfoPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +0000278 AU.addRequired<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000279 AU.addRequired<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +0000280 AU.addRequired<ScopInfoRegionPass>();
Chandler Carruthf5579872015-01-17 14:16:56 +0000281 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000282
Johannes Doerfertf6557f92015-03-04 22:43:40 +0000283 AU.addPreserved<DependenceInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000284
Chandler Carruth66ef16b2015-09-09 22:13:56 +0000285 AU.addPreserved<AAResultsWrapperPass>();
286 AU.addPreserved<BasicAAWrapperPass>();
Chandler Carruthf5579872015-01-17 14:16:56 +0000287 AU.addPreserved<LoopInfoWrapperPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000288 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +0000289 AU.addPreserved<GlobalsAAWrapperPass>();
Philip Pfaffe2b852e22017-05-23 10:12:56 +0000290 AU.addPreserved<IslAstInfoWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000291 AU.addPreserved<ScopDetectionWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +0000292 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +0000293 AU.addPreserved<SCEVAAWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000294
295 // FIXME: We do not yet add regions for the newly generated code to the
296 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +0000297 AU.addPreserved<RegionInfoPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +0000298 AU.addPreserved<ScopInfoRegionPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000299 }
300};
Tobias Grosser522478d2016-06-23 22:17:27 +0000301} // namespace
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000302
Tobias Grosser09d30692015-05-12 07:45:52 +0000303char CodeGeneration::ID = 1;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000304
Tobias Grosser09d30692015-05-12 07:45:52 +0000305Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000306
Tobias Grosser09d30692015-05-12 07:45:52 +0000307INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
Tobias Grosser7242ad92013-02-22 08:07:06 +0000308 "Polly - Create LLVM-IR from SCoPs", false, false);
Johannes Doerfertf6557f92015-03-04 22:43:40 +0000309INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
Tobias Grosser42aff302014-01-13 22:29:56 +0000310INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +0000311INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +0000312INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +0000313INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000314INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Tobias Grosser09d30692015-05-12 07:45:52 +0000315INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser7242ad92013-02-22 08:07:06 +0000316 "Polly - Create LLVM-IR from SCoPs", false, false)