blob: 401c005dc7464f2421f2228b58a06f2ddb704f3d [file] [log] [blame]
Sebastian Pop082cea82012-05-07 16:20:07 +00001//===------ IslCodeGeneration.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 IslCodeGeneration 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 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
18// its code in the new execution order defined by the changed scattering.
19//
20//===----------------------------------------------------------------------===//
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000021#include "polly/Config/config.h"
Johannes Doerferta63b2572014-08-03 01:51:59 +000022#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser83628182013-05-07 08:11:54 +000023#include "polly/CodeGen/BlockGenerators.h"
24#include "polly/CodeGen/CodeGeneration.h"
25#include "polly/CodeGen/IslAst.h"
26#include "polly/CodeGen/LoopGenerators.h"
27#include "polly/CodeGen/Utils.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000028#include "polly/Dependences.h"
29#include "polly/LinkAllPasses.h"
30#include "polly/ScopInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000031#include "polly/Support/GICHelper.h"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000032#include "polly/Support/ScopHelper.h"
Tobias Grossere3c05582014-11-15 21:32:53 +000033#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000034#include "polly/TempScopInfo.h"
Tobias Grossere3c05582014-11-15 21:32:53 +000035
36#include "llvm/ADT/PostOrderIterator.h"
37#include "llvm/ADT/SmallPtrSet.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000038#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000039#include "llvm/Analysis/PostDominators.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000040#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser83628182013-05-07 08:11:54 +000041#include "llvm/IR/Module.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000044#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46
47#include "isl/union_map.h"
48#include "isl/list.h"
49#include "isl/ast.h"
50#include "isl/ast_build.h"
51#include "isl/set.h"
52#include "isl/map.h"
53#include "isl/aff.h"
54
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000055using namespace polly;
56using namespace llvm;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-codegen-isl"
59
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000060class IslNodeBuilder {
61public:
Johannes Doerfert51d1c742014-10-02 15:32:17 +000062 IslNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
Tobias Grossere3c05582014-11-15 21:32:53 +000063 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
64 DominatorTree &DT, Scop &S)
65 : S(S), Builder(Builder), Annotator(Annotator),
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000066 Rewriter(new SCEVExpander(SE, "polly")),
Tobias Grossere3c05582014-11-15 21:32:53 +000067 ExprBuilder(Builder, IDToValue, *Rewriter), P(P), DL(DL), LI(LI),
68 SE(SE), DT(DT) {}
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000069
70 ~IslNodeBuilder() { delete Rewriter; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000071
72 void addParameters(__isl_take isl_set *Context);
73 void create(__isl_take isl_ast_node *Node);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +000074 IslExprBuilder &getExprBuilder() { return ExprBuilder; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000075
76private:
Tobias Grossere3c05582014-11-15 21:32:53 +000077 Scop &S;
Tobias Grosser5103ba72014-03-04 14:58:49 +000078 PollyIRBuilder &Builder;
Johannes Doerfert51d1c742014-10-02 15:32:17 +000079 ScopAnnotator &Annotator;
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000080
81 /// @brief A SCEVExpander to create llvm values from SCEVs.
82 SCEVExpander *Rewriter;
83
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000084 IslExprBuilder ExprBuilder;
85 Pass *P;
Tobias Grossere3c05582014-11-15 21:32:53 +000086 const DataLayout &DL;
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +000087 LoopInfo &LI;
88 ScalarEvolution &SE;
89 DominatorTree &DT;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000090
Tobias Grossere3c05582014-11-15 21:32:53 +000091 /// @brief The current iteration of out-of-scop loops
92 ///
93 /// This map provides for a given loop a llvm::Value that contains the current
94 /// loop iteration.
95 LoopToScevMapT OutsideLoopIterations;
96
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000097 // This maps an isl_id* to the Value* it has in the generated program. For now
98 // on, the only isl_ids that are stored here are the newly calculated loop
99 // ivs.
Tobias Grosser566ad582014-08-31 16:21:12 +0000100 IslExprBuilder::IDToValueTy IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000101
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000102 /// Generate code for a given SCEV*
103 ///
104 /// This function generates code for a given SCEV expression. It generated
105 /// code is emmitted at the end of the basic block our Builder currently
106 /// points to and the resulting value is returned.
107 ///
108 /// @param Expr The expression to code generate.
109 Value *generateSCEV(const SCEV *Expr);
110
Tobias Grossere3c05582014-11-15 21:32:53 +0000111 /// A set of Value -> Value remappings to apply when generating new code.
112 ///
113 /// When generating new code for a ScopStmt this map is used to map certain
114 /// llvm::Values to new llvm::Values.
115 ValueMapT ValueMap;
116
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000117 // Extract the upper bound of this loop
118 //
119 // The isl code generation can generate arbitrary expressions to check if the
120 // upper bound of a loop is reached, but it provides an option to enforce
121 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
122 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
123 //
124 // This function extracts 'atomic' upper bounds. Polly, in general, requires
125 // atomic upper bounds for the following reasons:
126 //
127 // 1. An atomic upper bound is loop invariant
128 //
129 // It must not be calculated at each loop iteration and can often even be
130 // hoisted out further by the loop invariant code motion.
131 //
132 // 2. OpenMP needs a loop invarient upper bound to calculate the number
133 // of loop iterations.
134 //
135 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grossere602a072013-05-07 07:30:56 +0000136 __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
137 CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000138
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000139 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
140
Tobias Grossere3c05582014-11-15 21:32:53 +0000141 /// Compute the values and loops referenced in this subtree.
142 ///
143 /// This function looks at all ScopStmts scheduled below the provided For node
144 /// and finds the llvm::Value[s] and llvm::Loops[s] which are referenced but
145 /// not locally defined.
146 ///
147 /// Values that can be synthesized or that are available as globals are
148 /// considered locally defined.
149 ///
150 /// Loops that contain the scop or that are part of the scop are considered
151 /// locally defined. Loops that are before the scop, but do not contain the
152 /// scop itself are considered not locally defined.
153 ///
154 /// @param For The node defining the subtree.
155 /// @param Values A vector that will be filled with the Values referenced in
156 /// this subtree.
157 /// @param Loops A vector that will be filled with the Loops referenced in
158 /// this subtree.
159 void getReferencesInSubtree(__isl_keep isl_ast_node *For,
160 SetVector<Value *> &Values,
161 SetVector<const Loop *> &Loops);
162
163 /// Change the llvm::Value(s) used for code generation.
164 ///
165 /// When generating code certain values (e.g., references to induction
166 /// variables or array base pointers) in the original code may be replaced by
167 /// new values. This function allows to (partially) update the set of values
168 /// used. A typical use case for this function is the case when we continue
169 /// code generation in a subfunction/kernel function and need to explicitly
170 /// pass down certain values.
171 ///
172 /// @param NewValues A map that maps certain llvm::Values to new llvm::Values.
173 void updateValues(ParallelLoopGenerator::ValueToValueMapTy &NewValues);
174
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000175 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000176 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
177 void createForSequential(__isl_take isl_ast_node *For);
Tobias Grosserce67a042014-07-02 16:26:47 +0000178
Tobias Grossere3c05582014-11-15 21:32:53 +0000179 /// Create LLVM-IR that executes a for node thread parallel.
180 ///
181 /// @param For The FOR isl_ast_node for which code is generated.
182 void createForParallel(__isl_take isl_ast_node *For);
183
Tobias Grosserce67a042014-07-02 16:26:47 +0000184 /// Generate LLVM-IR that computes the values of the original induction
185 /// variables in function of the newly generated loop induction variables.
186 ///
187 /// Example:
188 ///
189 /// // Original
190 /// for i
191 /// for j
192 /// S(i)
193 ///
194 /// Schedule: [i,j] -> [i+j, j]
195 ///
196 /// // New
197 /// for c0
198 /// for c1
199 /// S(c0 - c1, c1)
200 ///
201 /// Assuming the original code consists of two loops which are
202 /// transformed according to a schedule [i,j] -> [c0=i+j,c1=j]. The resulting
203 /// ast models the original statement as a call expression where each argument
204 /// is an expression that computes the old induction variables from the new
205 /// ones, ordered such that the first argument computes the value of induction
206 /// variable that was outermost in the original code.
207 ///
208 /// @param Expr The call expression that represents the statement.
209 /// @param Stmt The statement that is called.
210 /// @param VMap The value map into which the mapping from the old induction
211 /// variable to the new one is inserted. This mapping is used
212 /// for the classical code generation (not scev-based) and
213 /// gives an explicit mapping from an original, materialized
214 /// induction variable. It consequently can only be expressed
215 /// if there was an explicit induction variable.
216 /// @param LTS The loop to SCEV map in which the mapping from the original
217 /// loop to a SCEV representing the new loop iv is added. This
218 /// mapping does not require an explicit induction variable.
219 /// Instead, we think in terms of an implicit induction variable
220 /// that counts the number of times a loop is executed. For each
221 /// original loop this count, expressed in function of the new
222 /// induction variables, is added to the LTS map.
223 void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000224 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grosserce67a042014-07-02 16:26:47 +0000225 void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
226 VectorValueMapT &VMap,
Tobias Grossere602a072013-05-07 07:30:56 +0000227 std::vector<LoopToScevMapT> &VLTS,
228 std::vector<Value *> &IVS,
229 __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000230 void createIf(__isl_take isl_ast_node *If);
Tobias Grossere602a072013-05-07 07:30:56 +0000231 void createUserVector(__isl_take isl_ast_node *User,
232 std::vector<Value *> &IVS,
233 __isl_take isl_id *IteratorID,
234 __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000235 void createUser(__isl_take isl_ast_node *User);
236 void createBlock(__isl_take isl_ast_node *Block);
237};
238
Tobias Grossere602a072013-05-07 07:30:56 +0000239__isl_give isl_ast_expr *
240IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
241 ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000242 isl_id *UBID, *IteratorID;
243 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000244 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000245
246 Cond = isl_ast_node_for_get_cond(For);
247 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosser2784b082015-01-10 07:40:39 +0000248 isl_ast_expr_get_type(Cond);
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000249 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
250 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000251
Tobias Grosser2784b082015-01-10 07:40:39 +0000252 Type = isl_ast_expr_get_op_type(Cond);
253
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000254 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000255 case isl_ast_op_le:
256 Predicate = ICmpInst::ICMP_SLE;
257 break;
258 case isl_ast_op_lt:
259 Predicate = ICmpInst::ICMP_SLT;
260 break;
261 default:
262 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000263 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000264
265 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
266
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000267 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
268 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000269
270 UBID = isl_ast_expr_get_id(Arg0);
271
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000272 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
273 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000274
275 IteratorID = isl_ast_expr_get_id(Iterator);
276
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000277 assert(UBID == IteratorID &&
278 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000279
280 UB = isl_ast_expr_get_op_arg(Cond, 1);
281
282 isl_ast_expr_free(Cond);
283 isl_ast_expr_free(Iterator);
284 isl_ast_expr_free(Arg0);
285 isl_id_free(IteratorID);
286 isl_id_free(UBID);
287
288 return UB;
289}
290
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000291unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
Johannes Doerfert94d90822014-07-23 20:26:25 +0000292 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000293 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000294 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
295 if (NumberOfIterations == -1)
296 return -1;
297 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000298}
299
Tobias Grossere3c05582014-11-15 21:32:53 +0000300struct FindValuesUser {
301 LoopInfo &LI;
302 ScalarEvolution &SE;
303 Region &R;
304 SetVector<Value *> &Values;
305 SetVector<const SCEV *> &SCEVs;
306};
307
308/// Extract the values and SCEVs needed to generate code for a ScopStmt.
309///
310/// This function extracts a ScopStmt from a given isl_set and computes the
311/// Values this statement depends on as well as a set of SCEV expressions that
312/// need to be synthesized when generating code for this statment.
313static int findValuesInStmt(isl_set *Set, void *UserPtr) {
314 isl_id *Id = isl_set_get_tuple_id(Set);
315 struct FindValuesUser &User = *static_cast<struct FindValuesUser *>(UserPtr);
316 const ScopStmt *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id));
317 const BasicBlock *BB = Stmt->getBasicBlock();
318
319 // Check all the operands of instructions in the basic block.
320 for (const Instruction &Inst : *BB) {
321 for (Value *SrcVal : Inst.operands()) {
322 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
323 if (canSynthesize(OpInst, &User.LI, &User.SE, &User.R)) {
324 User.SCEVs.insert(
325 User.SE.getSCEVAtScope(OpInst, User.LI.getLoopFor(BB)));
326 continue;
327 }
328 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
329 if (Stmt->getParent()->getRegion().contains(OpInst))
330 continue;
331
332 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
333 User.Values.insert(SrcVal);
334 }
335 }
336 isl_id_free(Id);
337 isl_set_free(Set);
338 return 0;
339}
340
341void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For,
342 SetVector<Value *> &Values,
343 SetVector<const Loop *> &Loops) {
344
345 SetVector<const SCEV *> SCEVs;
346 struct FindValuesUser FindValues = {LI, SE, S.getRegion(), Values, SCEVs};
347
348 for (const auto &I : IDToValue)
349 Values.insert(I.second);
350
351 for (const auto &I : OutsideLoopIterations)
352 Values.insert(cast<SCEVUnknown>(I.second)->getValue());
353
354 isl_union_set *Schedule = isl_union_map_domain(IslAstInfo::getSchedule(For));
355
356 isl_union_set_foreach_set(Schedule, findValuesInStmt, &FindValues);
357 isl_union_set_free(Schedule);
358
359 for (const SCEV *Expr : SCEVs) {
360 findValues(Expr, Values);
361 findLoops(Expr, Loops);
362 }
363
364 Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
365
366 /// Remove loops that contain the scop or that are part of the scop, as they
367 /// are considered local. This leaves only loops that are before the scop, but
368 /// do not contain the scop itself.
369 Loops.remove_if([this](const Loop *L) {
370 return this->S.getRegion().contains(L) ||
371 L->contains(S.getRegion().getEntry());
372 });
373}
374
375void IslNodeBuilder::updateValues(
376 ParallelLoopGenerator::ValueToValueMapTy &NewValues) {
377 SmallPtrSet<Value *, 5> Inserted;
378
379 for (const auto &I : IDToValue) {
380 IDToValue[I.first] = NewValues[I.second];
381 Inserted.insert(I.second);
382 }
383
384 for (const auto &I : NewValues) {
385 if (Inserted.count(I.first))
386 continue;
387
388 ValueMap[I.first] = I.second;
389 }
390}
391
Tobias Grossere602a072013-05-07 07:30:56 +0000392void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
393 std::vector<Value *> &IVS,
394 __isl_take isl_id *IteratorID,
395 __isl_take isl_union_map *Schedule) {
Tobias Grosserce67a042014-07-02 16:26:47 +0000396 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
397 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
398 isl_id *Id = isl_ast_expr_get_id(StmtExpr);
399 isl_ast_expr_free(StmtExpr);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000400 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000401 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000402 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000403
404 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
405 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
406 isl_map *S = isl_map_from_union_map(Schedule);
407
Tobias Grosserce67a042014-07-02 16:26:47 +0000408 createSubstitutionsVector(Expr, Stmt, VectorMap, VLTS, IVS, IteratorID);
Johannes Doerfert731685e2014-10-08 17:25:30 +0000409 VectorBlockGenerator::generate(Builder, *Stmt, VectorMap, VLTS, S, P, LI, SE,
410 IslAstInfo::getBuild(User), &ExprBuilder);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000411
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000412 isl_map_free(S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000413 isl_id_free(Id);
414 isl_ast_node_free(User);
415}
416
Tobias Grossere602a072013-05-07 07:30:56 +0000417void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
418 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000419 isl_ast_node *Body = isl_ast_node_for_get_body(For);
420 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
421 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
422 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
423 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000424
425 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000426 Value *ValueInc = ExprBuilder.create(Inc);
427
428 Type *MaxType = ExprBuilder.getType(Iterator);
429 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000430 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
431
432 if (MaxType != ValueLB->getType())
433 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000434 if (MaxType != ValueInc->getType())
435 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
436
Tobias Grosserc14582f2013-02-05 18:01:29 +0000437 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000438 IVS[0] = ValueLB;
439
440 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000441 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000442
Johannes Doerfert94d90822014-07-23 20:26:25 +0000443 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000444 assert(Schedule && "For statement annotation does not contain its schedule");
445
446 IDToValue[IteratorID] = ValueLB;
447
448 switch (isl_ast_node_get_type(Body)) {
449 case isl_ast_node_user:
450 createUserVector(Body, IVS, isl_id_copy(IteratorID),
451 isl_union_map_copy(Schedule));
452 break;
453 case isl_ast_node_block: {
454 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
455
456 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
457 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000458 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000459
460 isl_ast_node_free(Body);
461 isl_ast_node_list_free(List);
462 break;
463 }
464 default:
465 isl_ast_node_dump(Body);
466 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
467 }
468
Tobias Grossere3c05582014-11-15 21:32:53 +0000469 IDToValue.erase(IDToValue.find(IteratorID));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000470 isl_id_free(IteratorID);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000471 isl_union_map_free(Schedule);
472
473 isl_ast_node_free(For);
474 isl_ast_expr_free(Iterator);
475}
476
477void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000478 isl_ast_node *Body;
479 isl_ast_expr *Init, *Inc, *Iterator, *UB;
480 isl_id *IteratorID;
481 Value *ValueLB, *ValueUB, *ValueInc;
482 Type *MaxType;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000483 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000484 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000485 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000486 bool Parallel;
487
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000488 Parallel =
489 IslAstInfo::isParallel(For) && !IslAstInfo::isReductionParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000490
491 Body = isl_ast_node_for_get_body(For);
492
493 // isl_ast_node_for_is_degenerate(For)
494 //
495 // TODO: For degenerated loops we could generate a plain assignment.
496 // However, for now we just reuse the logic for normal loops, which will
497 // create a loop with a single iteration.
498
499 Init = isl_ast_node_for_get_init(For);
500 Inc = isl_ast_node_for_get_inc(For);
501 Iterator = isl_ast_node_for_get_iterator(For);
502 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000503 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000504
505 ValueLB = ExprBuilder.create(Init);
506 ValueUB = ExprBuilder.create(UB);
507 ValueInc = ExprBuilder.create(Inc);
508
509 MaxType = ExprBuilder.getType(Iterator);
510 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
511 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
512 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
513
514 if (MaxType != ValueLB->getType())
515 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
516 if (MaxType != ValueUB->getType())
517 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
518 if (MaxType != ValueInc->getType())
519 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
520
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000521 // If we can show that LB <Predicate> UB holds at least once, we can
522 // omit the GuardBB in front of the loop.
523 bool UseGuardBB =
524 !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000525 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock,
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000526 Predicate, &Annotator, Parallel, UseGuardBB);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000527 IDToValue[IteratorID] = IV;
528
529 create(Body);
530
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000531 Annotator.popLoop(Parallel);
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000532
Tobias Grossere3c05582014-11-15 21:32:53 +0000533 IDToValue.erase(IDToValue.find(IteratorID));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000534
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000535 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000536
537 isl_ast_node_free(For);
538 isl_ast_expr_free(Iterator);
539 isl_id_free(IteratorID);
540}
541
Tobias Grossere3c05582014-11-15 21:32:53 +0000542/// @brief Remove the BBs contained in a (sub)function from the dominator tree.
543///
544/// This function removes the basic blocks that are part of a subfunction from
545/// the dominator tree. Specifically, when generating code it may happen that at
546/// some point the code generation continues in a new sub-function (e.g., when
547/// generating OpenMP code). The basic blocks that are created in this
548/// sub-function are then still part of the dominator tree of the original
549/// function, such that the dominator tree reaches over function boundaries.
550/// This is not only incorrect, but also causes crashes. This function now
551/// removes from the dominator tree all basic blocks that are dominated (and
552/// consequently reachable) from the entry block of this (sub)function.
553///
554/// FIXME: A LLVM (function or region) pass should not touch anything outside of
555/// the function/region it runs on. Hence, the pure need for this function shows
556/// that we do not comply to this rule. At the moment, this does not cause any
557/// issues, but we should be aware that such issues may appear. Unfortunately
558/// the current LLVM pass infrastructure does not allow to make Polly a module
559/// or call-graph pass to solve this issue, as such a pass would not have access
560/// to the per-function analyses passes needed by Polly. A future pass manager
561/// infrastructure is supposed to enable such kind of access possibly allowing
562/// us to create a cleaner solution here.
563///
564/// FIXME: Instead of adding the dominance information and then dropping it
565/// later on, we should try to just not add it in the first place. This requires
566/// some careful testing to make sure this does not break in interaction with
567/// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
568/// which may try to update it.
569///
570/// @param F The function which contains the BBs to removed.
571/// @param DT The dominator tree from which to remove the BBs.
572static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
573 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
574 std::vector<BasicBlock *> Nodes;
575
576 // We can only remove an element from the dominator tree, if all its children
577 // have been removed. To ensure this we obtain the list of nodes to remove
578 // using a post-order tree traversal.
579 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
580 Nodes.push_back(I->getBlock());
581
582 for (BasicBlock *BB : Nodes)
583 DT.eraseNode(BB);
584}
585
586void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
587 isl_ast_node *Body;
588 isl_ast_expr *Init, *Inc, *Iterator, *UB;
589 isl_id *IteratorID;
590 Value *ValueLB, *ValueUB, *ValueInc;
591 Type *MaxType;
592 Value *IV;
593 CmpInst::Predicate Predicate;
594
595 Body = isl_ast_node_for_get_body(For);
596 Init = isl_ast_node_for_get_init(For);
597 Inc = isl_ast_node_for_get_inc(For);
598 Iterator = isl_ast_node_for_get_iterator(For);
599 IteratorID = isl_ast_expr_get_id(Iterator);
600 UB = getUpperBound(For, Predicate);
601
602 ValueLB = ExprBuilder.create(Init);
603 ValueUB = ExprBuilder.create(UB);
604 ValueInc = ExprBuilder.create(Inc);
605
606 // OpenMP always uses SLE. In case the isl generated AST uses a SLT
607 // expression, we need to adjust the loop blound by one.
608 if (Predicate == CmpInst::ICMP_SLT)
609 ValueUB = Builder.CreateAdd(
610 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
611
612 MaxType = ExprBuilder.getType(Iterator);
613 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
614 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
615 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
616
617 if (MaxType != ValueLB->getType())
618 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
619 if (MaxType != ValueUB->getType())
620 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
621 if (MaxType != ValueInc->getType())
622 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
623
624 BasicBlock::iterator LoopBody;
625
626 SetVector<Value *> SubtreeValues;
627 SetVector<const Loop *> Loops;
628
629 getReferencesInSubtree(For, SubtreeValues, Loops);
630
631 // Create for all loops we depend on values that contain the current loop
632 // iteration. These values are necessary to generate code for SCEVs that
633 // depend on such loops. As a result we need to pass them to the subfunction.
634 for (const Loop *L : Loops) {
635 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
636 SE.getUnknown(Builder.getInt64(1)),
637 L, SCEV::FlagAnyWrap);
638 Value *V = generateSCEV(OuterLIV);
639 OutsideLoopIterations[L] = SE.getUnknown(V);
640 SubtreeValues.insert(V);
641 }
642
643 ParallelLoopGenerator::ValueToValueMapTy NewValues;
644 ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL);
645
646 IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc,
647 SubtreeValues, NewValues, &LoopBody);
648 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
649 Builder.SetInsertPoint(LoopBody);
650
651 // Save the current values.
652 ValueMapT ValueMapCopy = ValueMap;
653 IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
654
655 updateValues(NewValues);
656 IDToValue[IteratorID] = IV;
657
658 create(Body);
659
660 // Restore the original values.
661 ValueMap = ValueMapCopy;
662 IDToValue = IDToValueCopy;
663
664 Builder.SetInsertPoint(AfterLoop);
665 removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
666
667 for (const Loop *L : Loops)
668 OutsideLoopIterations.erase(L);
669
670 isl_ast_node_free(For);
671 isl_ast_expr_free(Iterator);
672 isl_id_free(IteratorID);
673}
674
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000675void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
676 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
677
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000678 if (Vector && IslAstInfo::isInnermostParallel(For) &&
679 !IslAstInfo::isReductionParallel(For)) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000680 int VectorWidth = getNumberOfIterations(For);
681 if (1 < VectorWidth && VectorWidth <= 16) {
682 createForVector(For, VectorWidth);
683 return;
684 }
685 }
Tobias Grossere3c05582014-11-15 21:32:53 +0000686
687 if (IslAstInfo::isExecutedInParallel(For)) {
688 createForParallel(For);
689 return;
690 }
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000691 createForSequential(For);
692}
693
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000694void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
695 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
696
697 Function *F = Builder.GetInsertBlock()->getParent();
698 LLVMContext &Context = F->getContext();
699
Tobias Grosserc14582f2013-02-05 18:01:29 +0000700 BasicBlock *CondBB =
701 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000702 CondBB->setName("polly.cond");
703 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
704 MergeBB->setName("polly.merge");
705 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
706 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
707
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000708 DT.addNewBlock(ThenBB, CondBB);
709 DT.addNewBlock(ElseBB, CondBB);
710 DT.changeImmediateDominator(MergeBB, CondBB);
711
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000712 Loop *L = LI.getLoopFor(CondBB);
713 if (L) {
714 L->addBasicBlockToLoop(ThenBB, LI.getBase());
715 L->addBasicBlockToLoop(ElseBB, LI.getBase());
716 }
717
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000718 CondBB->getTerminator()->eraseFromParent();
719
720 Builder.SetInsertPoint(CondBB);
721 Value *Predicate = ExprBuilder.create(Cond);
722 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
723 Builder.SetInsertPoint(ThenBB);
724 Builder.CreateBr(MergeBB);
725 Builder.SetInsertPoint(ElseBB);
726 Builder.CreateBr(MergeBB);
727 Builder.SetInsertPoint(ThenBB->begin());
728
729 create(isl_ast_node_if_get_then(If));
730
731 Builder.SetInsertPoint(ElseBB->begin());
732
733 if (isl_ast_node_if_has_else(If))
734 create(isl_ast_node_if_get_else(If));
735
736 Builder.SetInsertPoint(MergeBB->begin());
737
738 isl_ast_node_free(If);
739}
740
Tobias Grosserce67a042014-07-02 16:26:47 +0000741void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
742 ValueMapT &VMap, LoopToScevMapT &LTS) {
743 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
744 "Expression of type 'op' expected");
745 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
746 "Opertation of type 'call' expected");
747 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
748 isl_ast_expr *SubExpr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000749 Value *V;
750
Tobias Grosserce67a042014-07-02 16:26:47 +0000751 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
752 V = ExprBuilder.create(SubExpr);
Sebastian Pope039bb12013-03-18 19:09:49 +0000753 ScalarEvolution *SE = Stmt->getParent()->getSE();
754 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000755 }
756
Tobias Grossere3c05582014-11-15 21:32:53 +0000757 // Add the current ValueMap to our per-statement value map.
758 //
759 // This is needed e.g. to rewrite array base addresses when moving code
760 // into a parallely executed subfunction.
761 VMap.insert(ValueMap.begin(), ValueMap.end());
762
Tobias Grosserce67a042014-07-02 16:26:47 +0000763 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000764}
765
Tobias Grosserc14582f2013-02-05 18:01:29 +0000766void IslNodeBuilder::createSubstitutionsVector(
Tobias Grosserce67a042014-07-02 16:26:47 +0000767 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, VectorValueMapT &VMap,
768 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
769 __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000770 int i = 0;
771
772 Value *OldValue = IDToValue[IteratorID];
Tobias Grosser91f5b262014-06-04 08:06:40 +0000773 for (Value *IV : IVS) {
774 IDToValue[IteratorID] = IV;
Tobias Grosserce67a042014-07-02 16:26:47 +0000775 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000776 i++;
777 }
778
779 IDToValue[IteratorID] = OldValue;
780 isl_id_free(IteratorID);
Tobias Grosserce67a042014-07-02 16:26:47 +0000781 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000782}
783
784void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
785 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000786 LoopToScevMapT LTS;
Tobias Grosserce67a042014-07-02 16:26:47 +0000787 isl_id *Id;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000788 ScopStmt *Stmt;
789
Tobias Grosserce67a042014-07-02 16:26:47 +0000790 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
791 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
792 Id = isl_ast_expr_get_id(StmtExpr);
793 isl_ast_expr_free(StmtExpr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000794
Tobias Grossere3c05582014-11-15 21:32:53 +0000795 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
796
Tobias Grosserc14582f2013-02-05 18:01:29 +0000797 Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000798
Tobias Grosserce67a042014-07-02 16:26:47 +0000799 createSubstitutions(Expr, Stmt, VMap, LTS);
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000800 BlockGenerator::generate(Builder, *Stmt, VMap, LTS, P, LI, SE,
Johannes Doerferta63b2572014-08-03 01:51:59 +0000801 IslAstInfo::getBuild(User), &ExprBuilder);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000802
803 isl_ast_node_free(User);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000804 isl_id_free(Id);
805}
806
807void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
808 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
809
810 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
811 create(isl_ast_node_list_get_ast_node(List, i));
812
813 isl_ast_node_free(Block);
814 isl_ast_node_list_free(List);
815}
816
817void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
818 switch (isl_ast_node_get_type(Node)) {
819 case isl_ast_node_error:
820 llvm_unreachable("code generation error");
821 case isl_ast_node_for:
822 createFor(Node);
823 return;
824 case isl_ast_node_if:
825 createIf(Node);
826 return;
827 case isl_ast_node_user:
828 createUser(Node);
829 return;
830 case isl_ast_node_block:
831 createBlock(Node);
832 return;
833 }
834
835 llvm_unreachable("Unknown isl_ast_node type");
836}
837
838void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000839
840 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
841 isl_id *Id;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000842
843 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000844 IDToValue[Id] = generateSCEV((const SCEV *)isl_id_get_user(Id));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000845
846 isl_id_free(Id);
847 }
848
Tobias Grossere3c05582014-11-15 21:32:53 +0000849 // Generate values for the current loop iteration for all surrounding loops.
850 //
851 // We may also reference loops outside of the scop which do not contain the
852 // scop itself, but as the number of such scops may be arbitrarily large we do
853 // not generate code for them here, but only at the point of code generation
854 // where these values are needed.
855 Region &R = S.getRegion();
856 Loop *L = LI.getLoopFor(R.getEntry());
857
858 while (L != nullptr && R.contains(L))
859 L = L->getParentLoop();
860
861 while (L != nullptr) {
862 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
863 SE.getUnknown(Builder.getInt64(1)),
864 L, SCEV::FlagAnyWrap);
865 Value *V = generateSCEV(OuterLIV);
866 OutsideLoopIterations[L] = SE.getUnknown(V);
867 L = L->getParentLoop();
868 }
869
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000870 isl_set_free(Context);
871}
872
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000873Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
874 Instruction *InsertLocation = --(Builder.GetInsertBlock()->end());
Tobias Grosser55bc4c02015-01-08 19:26:53 +0000875 return Rewriter->expandCodeFor(Expr, Expr->getType(), InsertLocation);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000876}
877
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000878namespace {
879class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000880public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000881 static char ID;
882
883 IslCodeGeneration() : ScopPass(ID) {}
884
Tobias Grossere3c05582014-11-15 21:32:53 +0000885 /// @brief The datalayout used
886 const DataLayout *DL;
887
Johannes Doerfert38262242014-09-10 14:50:23 +0000888 /// @name The analysis passes we need to generate code.
889 ///
890 ///{
891 LoopInfo *LI;
892 IslAstInfo *AI;
893 DominatorTree *DT;
894 ScalarEvolution *SE;
895 ///}
896
897 /// @brief The loop annotator to generate llvm.loop metadata.
Johannes Doerfert51d1c742014-10-02 15:32:17 +0000898 ScopAnnotator Annotator;
Johannes Doerfert38262242014-09-10 14:50:23 +0000899
900 /// @brief Build the runtime condition.
901 ///
902 /// Build the condition that evaluates at run-time to true iff all
903 /// assumptions taken for the SCoP hold, and to false otherwise.
904 ///
905 /// @return A value evaluating to true/false if execution is save/unsafe.
906 Value *buildRTC(PollyIRBuilder &Builder, IslExprBuilder &ExprBuilder) {
907 Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
908 Value *RTC = ExprBuilder.create(AI->getRunCondition());
Johannes Doerfertb164c792014-09-18 11:17:17 +0000909 if (!RTC->getType()->isIntegerTy(1))
910 RTC = Builder.CreateIsNotNull(RTC);
911 return RTC;
Johannes Doerfert38262242014-09-10 14:50:23 +0000912 }
913
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000914 bool runOnScop(Scop &S) {
Chandler Carruthf5579872015-01-17 14:16:56 +0000915 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfert38262242014-09-10 14:50:23 +0000916 AI = &getAnalysis<IslAstInfo>();
917 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
918 SE = &getAnalysis<ScalarEvolution>();
Tobias Grossere3c05582014-11-15 21:32:53 +0000919 DL = &getAnalysis<DataLayoutPass>().getDataLayout();
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000920
Tobias Grossere602a072013-05-07 07:30:56 +0000921 assert(!S.getRegion().isTopLevelRegion() &&
922 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000923
Johannes Doerfertecdf2632014-10-02 15:31:24 +0000924 // Build the alias scopes for annotations first.
925 if (PollyAnnotateAliasScopes)
926 Annotator.buildAliasScopes(S);
927
Johannes Doerfert38262242014-09-10 14:50:23 +0000928 BasicBlock *EnteringBB = simplifyRegion(&S, this);
929 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000930
Tobias Grossere3c05582014-11-15 21:32:53 +0000931 IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S);
Tobias Grosser28735942014-08-16 09:09:15 +0000932 NodeBuilder.addParameters(S.getContext());
Johannes Doerfert38262242014-09-10 14:50:23 +0000933
934 Value *RTC = buildRTC(Builder, NodeBuilder.getExprBuilder());
935 BasicBlock *StartBlock = executeScopConditionally(S, this, RTC);
Tobias Grosser28735942014-08-16 09:09:15 +0000936 Builder.SetInsertPoint(StartBlock->begin());
937
Johannes Doerfert38262242014-09-10 14:50:23 +0000938 NodeBuilder.create(AI->getAst());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000939 return true;
940 }
941
Tobias Grosserc14582f2013-02-05 18:01:29 +0000942 virtual void printScop(raw_ostream &OS) const {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000943
944 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grossere3c05582014-11-15 21:32:53 +0000945 AU.addRequired<DataLayoutPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000946 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000947 AU.addRequired<IslAstInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000948 AU.addRequired<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000949 AU.addRequired<ScalarEvolution>();
950 AU.addRequired<ScopDetection>();
951 AU.addRequired<ScopInfo>();
Chandler Carruthf5579872015-01-17 14:16:56 +0000952 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000953
954 AU.addPreserved<Dependences>();
955
Chandler Carruthf5579872015-01-17 14:16:56 +0000956 AU.addPreserved<LoopInfoWrapperPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000957 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000958 AU.addPreserved<IslAstInfo>();
959 AU.addPreserved<ScopDetection>();
960 AU.addPreserved<ScalarEvolution>();
961
962 // FIXME: We do not yet add regions for the newly generated code to the
963 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +0000964 AU.addPreserved<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000965 AU.addPreserved<TempScopInfo>();
966 AU.addPreserved<ScopInfo>();
967 AU.addPreservedID(IndependentBlocksID);
968 }
969};
970}
971
972char IslCodeGeneration::ID = 1;
973
Tobias Grosser7242ad92013-02-22 08:07:06 +0000974Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000975
Tobias Grosser7242ad92013-02-22 08:07:06 +0000976INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
977 "Polly - Create LLVM-IR from SCoPs", false, false);
978INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +0000979INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +0000980INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +0000981INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +0000982INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
983INITIALIZE_PASS_DEPENDENCY(ScopDetection);
984INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
985 "Polly - Create LLVM-IR from SCoPs", false, false)