blob: e030d9a3002b222ef7ca08e29132a33c9128acdf [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"
Johannes Doerfertf6557f92015-03-04 22:43:40 +000028#include "polly/DependenceInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000029#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"
Johannes Doerfert0b169c02015-02-27 17:37:05 +000044#include "llvm/IR/Verifier.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000045#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47
48#include "isl/union_map.h"
49#include "isl/list.h"
50#include "isl/ast.h"
51#include "isl/ast_build.h"
52#include "isl/set.h"
53#include "isl/map.h"
54#include "isl/aff.h"
55
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000056using namespace polly;
57using namespace llvm;
58
Chandler Carruth95fef942014-04-22 03:30:19 +000059#define DEBUG_TYPE "polly-codegen-isl"
60
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000061class IslNodeBuilder {
62public:
Johannes Doerfert51d1c742014-10-02 15:32:17 +000063 IslNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
Tobias Grossere3c05582014-11-15 21:32:53 +000064 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
65 DominatorTree &DT, Scop &S)
Tobias Grosserbb8d1562015-03-04 19:33:31 +000066 : S(S), Builder(Builder), Annotator(Annotator), Rewriter(SE, "polly"),
67 ExprBuilder(Builder, IDToValue, Rewriter, DT, LI),
Johannes Doerfertf4af99b2015-03-08 21:38:35 +000068 BlockGen(Builder, LI, SE, DT, &ExprBuilder), RegionGen(BlockGen), P(P),
69 DL(DL), LI(LI), SE(SE), DT(DT) {}
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000070
Tobias Grosserbb8d1562015-03-04 19:33:31 +000071 ~IslNodeBuilder() {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000072
73 void addParameters(__isl_take isl_set *Context);
74 void create(__isl_take isl_ast_node *Node);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +000075 IslExprBuilder &getExprBuilder() { return ExprBuilder; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000076
77private:
Tobias Grossere3c05582014-11-15 21:32:53 +000078 Scop &S;
Tobias Grosser5103ba72014-03-04 14:58:49 +000079 PollyIRBuilder &Builder;
Johannes Doerfert51d1c742014-10-02 15:32:17 +000080 ScopAnnotator &Annotator;
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000081
82 /// @brief A SCEVExpander to create llvm values from SCEVs.
Tobias Grosserbb8d1562015-03-04 19:33:31 +000083 SCEVExpander Rewriter;
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000084
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000085 IslExprBuilder ExprBuilder;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +000086 BlockGenerator BlockGen;
Johannes Doerfert275a1752015-02-24 16:16:32 +000087
88 /// @brief Generator for region statements.
89 RegionGenerator RegionGen;
90
Johannes Doerfertf4af99b2015-03-08 21:38:35 +000091 Pass *const P;
Tobias Grossere3c05582014-11-15 21:32:53 +000092 const DataLayout &DL;
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +000093 LoopInfo &LI;
94 ScalarEvolution &SE;
95 DominatorTree &DT;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000096
Tobias Grossere3c05582014-11-15 21:32:53 +000097 /// @brief The current iteration of out-of-scop loops
98 ///
99 /// This map provides for a given loop a llvm::Value that contains the current
100 /// loop iteration.
101 LoopToScevMapT OutsideLoopIterations;
102
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000103 // This maps an isl_id* to the Value* it has in the generated program. For now
104 // on, the only isl_ids that are stored here are the newly calculated loop
105 // ivs.
Tobias Grosser566ad582014-08-31 16:21:12 +0000106 IslExprBuilder::IDToValueTy IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000107
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000108 /// Generate code for a given SCEV*
109 ///
110 /// This function generates code for a given SCEV expression. It generated
111 /// code is emmitted at the end of the basic block our Builder currently
112 /// points to and the resulting value is returned.
113 ///
114 /// @param Expr The expression to code generate.
115 Value *generateSCEV(const SCEV *Expr);
116
Tobias Grossere3c05582014-11-15 21:32:53 +0000117 /// A set of Value -> Value remappings to apply when generating new code.
118 ///
119 /// When generating new code for a ScopStmt this map is used to map certain
120 /// llvm::Values to new llvm::Values.
121 ValueMapT ValueMap;
122
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000123 // Extract the upper bound of this loop
124 //
125 // The isl code generation can generate arbitrary expressions to check if the
126 // upper bound of a loop is reached, but it provides an option to enforce
127 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
128 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
129 //
130 // This function extracts 'atomic' upper bounds. Polly, in general, requires
131 // atomic upper bounds for the following reasons:
132 //
133 // 1. An atomic upper bound is loop invariant
134 //
135 // It must not be calculated at each loop iteration and can often even be
136 // hoisted out further by the loop invariant code motion.
137 //
138 // 2. OpenMP needs a loop invarient upper bound to calculate the number
139 // of loop iterations.
140 //
141 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grossere602a072013-05-07 07:30:56 +0000142 __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
143 CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000144
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000145 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
146
Tobias Grossere3c05582014-11-15 21:32:53 +0000147 /// Compute the values and loops referenced in this subtree.
148 ///
149 /// This function looks at all ScopStmts scheduled below the provided For node
150 /// and finds the llvm::Value[s] and llvm::Loops[s] which are referenced but
151 /// not locally defined.
152 ///
153 /// Values that can be synthesized or that are available as globals are
154 /// considered locally defined.
155 ///
156 /// Loops that contain the scop or that are part of the scop are considered
157 /// locally defined. Loops that are before the scop, but do not contain the
158 /// scop itself are considered not locally defined.
159 ///
160 /// @param For The node defining the subtree.
161 /// @param Values A vector that will be filled with the Values referenced in
162 /// this subtree.
163 /// @param Loops A vector that will be filled with the Loops referenced in
164 /// this subtree.
165 void getReferencesInSubtree(__isl_keep isl_ast_node *For,
166 SetVector<Value *> &Values,
167 SetVector<const Loop *> &Loops);
168
169 /// Change the llvm::Value(s) used for code generation.
170 ///
171 /// When generating code certain values (e.g., references to induction
172 /// variables or array base pointers) in the original code may be replaced by
173 /// new values. This function allows to (partially) update the set of values
174 /// used. A typical use case for this function is the case when we continue
175 /// code generation in a subfunction/kernel function and need to explicitly
176 /// pass down certain values.
177 ///
178 /// @param NewValues A map that maps certain llvm::Values to new llvm::Values.
179 void updateValues(ParallelLoopGenerator::ValueToValueMapTy &NewValues);
180
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000181 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000182 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
183 void createForSequential(__isl_take isl_ast_node *For);
Tobias Grosserce67a042014-07-02 16:26:47 +0000184
Tobias Grossere3c05582014-11-15 21:32:53 +0000185 /// Create LLVM-IR that executes a for node thread parallel.
186 ///
187 /// @param For The FOR isl_ast_node for which code is generated.
188 void createForParallel(__isl_take isl_ast_node *For);
189
Tobias Grosserce67a042014-07-02 16:26:47 +0000190 /// Generate LLVM-IR that computes the values of the original induction
191 /// variables in function of the newly generated loop induction variables.
192 ///
193 /// Example:
194 ///
195 /// // Original
196 /// for i
197 /// for j
198 /// S(i)
199 ///
200 /// Schedule: [i,j] -> [i+j, j]
201 ///
202 /// // New
203 /// for c0
204 /// for c1
205 /// S(c0 - c1, c1)
206 ///
207 /// Assuming the original code consists of two loops which are
208 /// transformed according to a schedule [i,j] -> [c0=i+j,c1=j]. The resulting
209 /// ast models the original statement as a call expression where each argument
210 /// is an expression that computes the old induction variables from the new
211 /// ones, ordered such that the first argument computes the value of induction
212 /// variable that was outermost in the original code.
213 ///
214 /// @param Expr The call expression that represents the statement.
215 /// @param Stmt The statement that is called.
216 /// @param VMap The value map into which the mapping from the old induction
217 /// variable to the new one is inserted. This mapping is used
218 /// for the classical code generation (not scev-based) and
219 /// gives an explicit mapping from an original, materialized
220 /// induction variable. It consequently can only be expressed
221 /// if there was an explicit induction variable.
222 /// @param LTS The loop to SCEV map in which the mapping from the original
223 /// loop to a SCEV representing the new loop iv is added. This
224 /// mapping does not require an explicit induction variable.
225 /// Instead, we think in terms of an implicit induction variable
226 /// that counts the number of times a loop is executed. For each
227 /// original loop this count, expressed in function of the new
228 /// induction variables, is added to the LTS map.
229 void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000230 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grosserce67a042014-07-02 16:26:47 +0000231 void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
232 VectorValueMapT &VMap,
Tobias Grossere602a072013-05-07 07:30:56 +0000233 std::vector<LoopToScevMapT> &VLTS,
234 std::vector<Value *> &IVS,
235 __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000236 void createIf(__isl_take isl_ast_node *If);
Tobias Grossere602a072013-05-07 07:30:56 +0000237 void createUserVector(__isl_take isl_ast_node *User,
238 std::vector<Value *> &IVS,
239 __isl_take isl_id *IteratorID,
240 __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000241 void createUser(__isl_take isl_ast_node *User);
242 void createBlock(__isl_take isl_ast_node *Block);
243};
244
Tobias Grossere602a072013-05-07 07:30:56 +0000245__isl_give isl_ast_expr *
246IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
247 ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000248 isl_id *UBID, *IteratorID;
249 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000250 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000251
252 Cond = isl_ast_node_for_get_cond(For);
253 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosser2784b082015-01-10 07:40:39 +0000254 isl_ast_expr_get_type(Cond);
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000255 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
256 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000257
Tobias Grosser2784b082015-01-10 07:40:39 +0000258 Type = isl_ast_expr_get_op_type(Cond);
259
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000260 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000261 case isl_ast_op_le:
262 Predicate = ICmpInst::ICMP_SLE;
263 break;
264 case isl_ast_op_lt:
265 Predicate = ICmpInst::ICMP_SLT;
266 break;
267 default:
268 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000269 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000270
271 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
272
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000273 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
274 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000275
276 UBID = isl_ast_expr_get_id(Arg0);
277
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000278 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
279 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000280
281 IteratorID = isl_ast_expr_get_id(Iterator);
282
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000283 assert(UBID == IteratorID &&
284 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000285
286 UB = isl_ast_expr_get_op_arg(Cond, 1);
287
288 isl_ast_expr_free(Cond);
289 isl_ast_expr_free(Iterator);
290 isl_ast_expr_free(Arg0);
291 isl_id_free(IteratorID);
292 isl_id_free(UBID);
293
294 return UB;
295}
296
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000297unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
Johannes Doerfert94d90822014-07-23 20:26:25 +0000298 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000299 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000300 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
301 if (NumberOfIterations == -1)
302 return -1;
303 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000304}
305
Tobias Grossere3c05582014-11-15 21:32:53 +0000306struct FindValuesUser {
307 LoopInfo &LI;
308 ScalarEvolution &SE;
309 Region &R;
310 SetVector<Value *> &Values;
311 SetVector<const SCEV *> &SCEVs;
312};
313
Johannes Doerfertbbf30842015-03-02 13:41:53 +0000314/// @brief Extract the values and SCEVs needed to generate code for a block.
315static int findValuesInBlock(struct FindValuesUser &User, const ScopStmt *Stmt,
316 const BasicBlock *BB) {
Tobias Grossere3c05582014-11-15 21:32:53 +0000317 // Check all the operands of instructions in the basic block.
318 for (const Instruction &Inst : *BB) {
319 for (Value *SrcVal : Inst.operands()) {
320 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
321 if (canSynthesize(OpInst, &User.LI, &User.SE, &User.R)) {
322 User.SCEVs.insert(
323 User.SE.getSCEVAtScope(OpInst, User.LI.getLoopFor(BB)));
324 continue;
325 }
326 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
327 if (Stmt->getParent()->getRegion().contains(OpInst))
328 continue;
329
330 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
331 User.Values.insert(SrcVal);
332 }
333 }
Johannes Doerfertbbf30842015-03-02 13:41:53 +0000334 return 0;
335}
336
337/// Extract the values and SCEVs needed to generate code for a ScopStmt.
338///
339/// This function extracts a ScopStmt from a given isl_set and computes the
340/// Values this statement depends on as well as a set of SCEV expressions that
341/// need to be synthesized when generating code for this statment.
342static int findValuesInStmt(isl_set *Set, void *UserPtr) {
343 isl_id *Id = isl_set_get_tuple_id(Set);
344 struct FindValuesUser &User = *static_cast<struct FindValuesUser *>(UserPtr);
345 const ScopStmt *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id));
346
347 if (Stmt->isBlockStmt())
348 findValuesInBlock(User, Stmt, Stmt->getBasicBlock());
349 else {
350 assert(Stmt->isRegionStmt() &&
351 "Stmt was neither block nor region statement");
352 for (const BasicBlock *BB : Stmt->getRegion()->blocks())
353 findValuesInBlock(User, Stmt, BB);
354 }
355
Tobias Grossere3c05582014-11-15 21:32:53 +0000356 isl_id_free(Id);
357 isl_set_free(Set);
358 return 0;
359}
360
361void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For,
362 SetVector<Value *> &Values,
363 SetVector<const Loop *> &Loops) {
364
365 SetVector<const SCEV *> SCEVs;
366 struct FindValuesUser FindValues = {LI, SE, S.getRegion(), Values, SCEVs};
367
368 for (const auto &I : IDToValue)
369 Values.insert(I.second);
370
371 for (const auto &I : OutsideLoopIterations)
372 Values.insert(cast<SCEVUnknown>(I.second)->getValue());
373
374 isl_union_set *Schedule = isl_union_map_domain(IslAstInfo::getSchedule(For));
375
376 isl_union_set_foreach_set(Schedule, findValuesInStmt, &FindValues);
377 isl_union_set_free(Schedule);
378
379 for (const SCEV *Expr : SCEVs) {
380 findValues(Expr, Values);
381 findLoops(Expr, Loops);
382 }
383
384 Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
385
386 /// Remove loops that contain the scop or that are part of the scop, as they
387 /// are considered local. This leaves only loops that are before the scop, but
388 /// do not contain the scop itself.
389 Loops.remove_if([this](const Loop *L) {
390 return this->S.getRegion().contains(L) ||
391 L->contains(S.getRegion().getEntry());
392 });
393}
394
395void IslNodeBuilder::updateValues(
396 ParallelLoopGenerator::ValueToValueMapTy &NewValues) {
397 SmallPtrSet<Value *, 5> Inserted;
398
399 for (const auto &I : IDToValue) {
400 IDToValue[I.first] = NewValues[I.second];
401 Inserted.insert(I.second);
402 }
403
404 for (const auto &I : NewValues) {
405 if (Inserted.count(I.first))
406 continue;
407
408 ValueMap[I.first] = I.second;
409 }
410}
411
Tobias Grossere602a072013-05-07 07:30:56 +0000412void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
413 std::vector<Value *> &IVS,
414 __isl_take isl_id *IteratorID,
415 __isl_take isl_union_map *Schedule) {
Tobias Grosserce67a042014-07-02 16:26:47 +0000416 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
417 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
418 isl_id *Id = isl_ast_expr_get_id(StmtExpr);
419 isl_ast_expr_free(StmtExpr);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000420 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000421 Stmt->setAstBuild(IslAstInfo::getBuild(User));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000422 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000423 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000424
425 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
426 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
427 isl_map *S = isl_map_from_union_map(Schedule);
428
Tobias Grosserce67a042014-07-02 16:26:47 +0000429 createSubstitutionsVector(Expr, Stmt, VectorMap, VLTS, IVS, IteratorID);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000430 VectorBlockGenerator::generate(BlockGen, *Stmt, VectorMap, VLTS, S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000431
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000432 isl_map_free(S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000433 isl_id_free(Id);
434 isl_ast_node_free(User);
435}
436
Tobias Grossere602a072013-05-07 07:30:56 +0000437void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
438 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000439 isl_ast_node *Body = isl_ast_node_for_get_body(For);
440 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
441 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
442 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
443 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000444
445 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000446 Value *ValueInc = ExprBuilder.create(Inc);
447
448 Type *MaxType = ExprBuilder.getType(Iterator);
449 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000450 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
451
452 if (MaxType != ValueLB->getType())
453 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000454 if (MaxType != ValueInc->getType())
455 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
456
Tobias Grosserc14582f2013-02-05 18:01:29 +0000457 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000458 IVS[0] = ValueLB;
459
460 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000461 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000462
Johannes Doerfert94d90822014-07-23 20:26:25 +0000463 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000464 assert(Schedule && "For statement annotation does not contain its schedule");
465
466 IDToValue[IteratorID] = ValueLB;
467
468 switch (isl_ast_node_get_type(Body)) {
469 case isl_ast_node_user:
470 createUserVector(Body, IVS, isl_id_copy(IteratorID),
471 isl_union_map_copy(Schedule));
472 break;
473 case isl_ast_node_block: {
474 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
475
476 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
477 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000478 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000479
480 isl_ast_node_free(Body);
481 isl_ast_node_list_free(List);
482 break;
483 }
484 default:
485 isl_ast_node_dump(Body);
486 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
487 }
488
Tobias Grossere3c05582014-11-15 21:32:53 +0000489 IDToValue.erase(IDToValue.find(IteratorID));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000490 isl_id_free(IteratorID);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000491 isl_union_map_free(Schedule);
492
493 isl_ast_node_free(For);
494 isl_ast_expr_free(Iterator);
495}
496
497void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000498 isl_ast_node *Body;
499 isl_ast_expr *Init, *Inc, *Iterator, *UB;
500 isl_id *IteratorID;
501 Value *ValueLB, *ValueUB, *ValueInc;
502 Type *MaxType;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000503 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000504 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000505 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000506 bool Parallel;
507
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000508 Parallel =
509 IslAstInfo::isParallel(For) && !IslAstInfo::isReductionParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000510
511 Body = isl_ast_node_for_get_body(For);
512
513 // isl_ast_node_for_is_degenerate(For)
514 //
515 // TODO: For degenerated loops we could generate a plain assignment.
516 // However, for now we just reuse the logic for normal loops, which will
517 // create a loop with a single iteration.
518
519 Init = isl_ast_node_for_get_init(For);
520 Inc = isl_ast_node_for_get_inc(For);
521 Iterator = isl_ast_node_for_get_iterator(For);
522 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000523 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000524
525 ValueLB = ExprBuilder.create(Init);
526 ValueUB = ExprBuilder.create(UB);
527 ValueInc = ExprBuilder.create(Inc);
528
529 MaxType = ExprBuilder.getType(Iterator);
530 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
531 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
532 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
533
534 if (MaxType != ValueLB->getType())
535 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
536 if (MaxType != ValueUB->getType())
537 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
538 if (MaxType != ValueInc->getType())
539 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
540
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000541 // If we can show that LB <Predicate> UB holds at least once, we can
542 // omit the GuardBB in front of the loop.
543 bool UseGuardBB =
544 !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000545 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock,
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000546 Predicate, &Annotator, Parallel, UseGuardBB);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000547 IDToValue[IteratorID] = IV;
548
549 create(Body);
550
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000551 Annotator.popLoop(Parallel);
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000552
Tobias Grossere3c05582014-11-15 21:32:53 +0000553 IDToValue.erase(IDToValue.find(IteratorID));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000554
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000555 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000556
557 isl_ast_node_free(For);
558 isl_ast_expr_free(Iterator);
559 isl_id_free(IteratorID);
560}
561
Tobias Grossere3c05582014-11-15 21:32:53 +0000562/// @brief Remove the BBs contained in a (sub)function from the dominator tree.
563///
564/// This function removes the basic blocks that are part of a subfunction from
565/// the dominator tree. Specifically, when generating code it may happen that at
566/// some point the code generation continues in a new sub-function (e.g., when
567/// generating OpenMP code). The basic blocks that are created in this
568/// sub-function are then still part of the dominator tree of the original
569/// function, such that the dominator tree reaches over function boundaries.
570/// This is not only incorrect, but also causes crashes. This function now
571/// removes from the dominator tree all basic blocks that are dominated (and
572/// consequently reachable) from the entry block of this (sub)function.
573///
574/// FIXME: A LLVM (function or region) pass should not touch anything outside of
575/// the function/region it runs on. Hence, the pure need for this function shows
576/// that we do not comply to this rule. At the moment, this does not cause any
577/// issues, but we should be aware that such issues may appear. Unfortunately
578/// the current LLVM pass infrastructure does not allow to make Polly a module
579/// or call-graph pass to solve this issue, as such a pass would not have access
580/// to the per-function analyses passes needed by Polly. A future pass manager
581/// infrastructure is supposed to enable such kind of access possibly allowing
582/// us to create a cleaner solution here.
583///
584/// FIXME: Instead of adding the dominance information and then dropping it
585/// later on, we should try to just not add it in the first place. This requires
586/// some careful testing to make sure this does not break in interaction with
587/// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
588/// which may try to update it.
589///
590/// @param F The function which contains the BBs to removed.
591/// @param DT The dominator tree from which to remove the BBs.
592static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
593 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
594 std::vector<BasicBlock *> Nodes;
595
596 // We can only remove an element from the dominator tree, if all its children
597 // have been removed. To ensure this we obtain the list of nodes to remove
598 // using a post-order tree traversal.
599 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
600 Nodes.push_back(I->getBlock());
601
602 for (BasicBlock *BB : Nodes)
603 DT.eraseNode(BB);
604}
605
606void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
607 isl_ast_node *Body;
608 isl_ast_expr *Init, *Inc, *Iterator, *UB;
609 isl_id *IteratorID;
610 Value *ValueLB, *ValueUB, *ValueInc;
611 Type *MaxType;
612 Value *IV;
613 CmpInst::Predicate Predicate;
614
615 Body = isl_ast_node_for_get_body(For);
616 Init = isl_ast_node_for_get_init(For);
617 Inc = isl_ast_node_for_get_inc(For);
618 Iterator = isl_ast_node_for_get_iterator(For);
619 IteratorID = isl_ast_expr_get_id(Iterator);
620 UB = getUpperBound(For, Predicate);
621
622 ValueLB = ExprBuilder.create(Init);
623 ValueUB = ExprBuilder.create(UB);
624 ValueInc = ExprBuilder.create(Inc);
625
626 // OpenMP always uses SLE. In case the isl generated AST uses a SLT
627 // expression, we need to adjust the loop blound by one.
628 if (Predicate == CmpInst::ICMP_SLT)
629 ValueUB = Builder.CreateAdd(
630 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
631
632 MaxType = ExprBuilder.getType(Iterator);
633 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
634 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
635 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
636
637 if (MaxType != ValueLB->getType())
638 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
639 if (MaxType != ValueUB->getType())
640 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
641 if (MaxType != ValueInc->getType())
642 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
643
644 BasicBlock::iterator LoopBody;
645
646 SetVector<Value *> SubtreeValues;
647 SetVector<const Loop *> Loops;
648
649 getReferencesInSubtree(For, SubtreeValues, Loops);
650
651 // Create for all loops we depend on values that contain the current loop
652 // iteration. These values are necessary to generate code for SCEVs that
653 // depend on such loops. As a result we need to pass them to the subfunction.
654 for (const Loop *L : Loops) {
655 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
656 SE.getUnknown(Builder.getInt64(1)),
657 L, SCEV::FlagAnyWrap);
658 Value *V = generateSCEV(OuterLIV);
659 OutsideLoopIterations[L] = SE.getUnknown(V);
660 SubtreeValues.insert(V);
661 }
662
663 ParallelLoopGenerator::ValueToValueMapTy NewValues;
664 ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL);
665
666 IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc,
667 SubtreeValues, NewValues, &LoopBody);
668 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
669 Builder.SetInsertPoint(LoopBody);
670
671 // Save the current values.
672 ValueMapT ValueMapCopy = ValueMap;
673 IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
674
675 updateValues(NewValues);
676 IDToValue[IteratorID] = IV;
677
678 create(Body);
679
680 // Restore the original values.
681 ValueMap = ValueMapCopy;
682 IDToValue = IDToValueCopy;
683
684 Builder.SetInsertPoint(AfterLoop);
685 removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
686
687 for (const Loop *L : Loops)
688 OutsideLoopIterations.erase(L);
689
690 isl_ast_node_free(For);
691 isl_ast_expr_free(Iterator);
692 isl_id_free(IteratorID);
693}
694
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000695void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
696 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
697
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000698 if (Vector && IslAstInfo::isInnermostParallel(For) &&
699 !IslAstInfo::isReductionParallel(For)) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000700 int VectorWidth = getNumberOfIterations(For);
701 if (1 < VectorWidth && VectorWidth <= 16) {
702 createForVector(For, VectorWidth);
703 return;
704 }
705 }
Tobias Grossere3c05582014-11-15 21:32:53 +0000706
707 if (IslAstInfo::isExecutedInParallel(For)) {
708 createForParallel(For);
709 return;
710 }
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000711 createForSequential(For);
712}
713
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000714void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
715 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
716
717 Function *F = Builder.GetInsertBlock()->getParent();
718 LLVMContext &Context = F->getContext();
719
Tobias Grosserc14582f2013-02-05 18:01:29 +0000720 BasicBlock *CondBB =
Chandler Carruth5ec33332015-01-18 10:52:23 +0000721 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000722 CondBB->setName("polly.cond");
Chandler Carruth5ec33332015-01-18 10:52:23 +0000723 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), &DT, &LI);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000724 MergeBB->setName("polly.merge");
725 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
726 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
727
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000728 DT.addNewBlock(ThenBB, CondBB);
729 DT.addNewBlock(ElseBB, CondBB);
730 DT.changeImmediateDominator(MergeBB, CondBB);
731
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000732 Loop *L = LI.getLoopFor(CondBB);
733 if (L) {
Chandler Carruth6adcf562015-01-18 01:47:30 +0000734 L->addBasicBlockToLoop(ThenBB, LI);
735 L->addBasicBlockToLoop(ElseBB, LI);
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000736 }
737
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000738 CondBB->getTerminator()->eraseFromParent();
739
740 Builder.SetInsertPoint(CondBB);
741 Value *Predicate = ExprBuilder.create(Cond);
742 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
743 Builder.SetInsertPoint(ThenBB);
744 Builder.CreateBr(MergeBB);
745 Builder.SetInsertPoint(ElseBB);
746 Builder.CreateBr(MergeBB);
747 Builder.SetInsertPoint(ThenBB->begin());
748
749 create(isl_ast_node_if_get_then(If));
750
751 Builder.SetInsertPoint(ElseBB->begin());
752
753 if (isl_ast_node_if_has_else(If))
754 create(isl_ast_node_if_get_else(If));
755
756 Builder.SetInsertPoint(MergeBB->begin());
757
758 isl_ast_node_free(If);
759}
760
Tobias Grosserce67a042014-07-02 16:26:47 +0000761void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
762 ValueMapT &VMap, LoopToScevMapT &LTS) {
763 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
764 "Expression of type 'op' expected");
765 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
766 "Opertation of type 'call' expected");
767 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
768 isl_ast_expr *SubExpr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000769 Value *V;
770
Tobias Grosserce67a042014-07-02 16:26:47 +0000771 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
772 V = ExprBuilder.create(SubExpr);
Sebastian Pope039bb12013-03-18 19:09:49 +0000773 ScalarEvolution *SE = Stmt->getParent()->getSE();
774 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000775 }
776
Tobias Grossere3c05582014-11-15 21:32:53 +0000777 // Add the current ValueMap to our per-statement value map.
778 //
779 // This is needed e.g. to rewrite array base addresses when moving code
780 // into a parallely executed subfunction.
781 VMap.insert(ValueMap.begin(), ValueMap.end());
782
Tobias Grosserce67a042014-07-02 16:26:47 +0000783 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000784}
785
Tobias Grosserc14582f2013-02-05 18:01:29 +0000786void IslNodeBuilder::createSubstitutionsVector(
Tobias Grosserce67a042014-07-02 16:26:47 +0000787 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, VectorValueMapT &VMap,
788 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
789 __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000790 int i = 0;
791
792 Value *OldValue = IDToValue[IteratorID];
Tobias Grosser91f5b262014-06-04 08:06:40 +0000793 for (Value *IV : IVS) {
794 IDToValue[IteratorID] = IV;
Tobias Grosserce67a042014-07-02 16:26:47 +0000795 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000796 i++;
797 }
798
799 IDToValue[IteratorID] = OldValue;
800 isl_id_free(IteratorID);
Tobias Grosserce67a042014-07-02 16:26:47 +0000801 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000802}
803
804void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
805 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000806 LoopToScevMapT LTS;
Tobias Grosserce67a042014-07-02 16:26:47 +0000807 isl_id *Id;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000808 ScopStmt *Stmt;
809
Tobias Grosserce67a042014-07-02 16:26:47 +0000810 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
811 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
812 Id = isl_ast_expr_get_id(StmtExpr);
813 isl_ast_expr_free(StmtExpr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000814
Tobias Grossere3c05582014-11-15 21:32:53 +0000815 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
816
Tobias Grosserc14582f2013-02-05 18:01:29 +0000817 Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000818 Stmt->setAstBuild(IslAstInfo::getBuild(User));
Johannes Doerferta63b2572014-08-03 01:51:59 +0000819
Tobias Grosserce67a042014-07-02 16:26:47 +0000820 createSubstitutions(Expr, Stmt, VMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000821 if (Stmt->isBlockStmt())
822 BlockGen.copyStmt(*Stmt, VMap, LTS);
823 else
824 RegionGen.copyStmt(*Stmt, VMap, LTS);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000825
826 isl_ast_node_free(User);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000827 isl_id_free(Id);
828}
829
830void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
831 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
832
833 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
834 create(isl_ast_node_list_get_ast_node(List, i));
835
836 isl_ast_node_free(Block);
837 isl_ast_node_list_free(List);
838}
839
840void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
841 switch (isl_ast_node_get_type(Node)) {
842 case isl_ast_node_error:
843 llvm_unreachable("code generation error");
844 case isl_ast_node_for:
845 createFor(Node);
846 return;
847 case isl_ast_node_if:
848 createIf(Node);
849 return;
850 case isl_ast_node_user:
851 createUser(Node);
852 return;
853 case isl_ast_node_block:
854 createBlock(Node);
855 return;
856 }
857
858 llvm_unreachable("Unknown isl_ast_node type");
859}
860
861void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000862
863 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
864 isl_id *Id;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000865
866 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000867 IDToValue[Id] = generateSCEV((const SCEV *)isl_id_get_user(Id));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000868
869 isl_id_free(Id);
870 }
871
Tobias Grossere3c05582014-11-15 21:32:53 +0000872 // Generate values for the current loop iteration for all surrounding loops.
873 //
874 // We may also reference loops outside of the scop which do not contain the
875 // scop itself, but as the number of such scops may be arbitrarily large we do
876 // not generate code for them here, but only at the point of code generation
877 // where these values are needed.
878 Region &R = S.getRegion();
879 Loop *L = LI.getLoopFor(R.getEntry());
880
881 while (L != nullptr && R.contains(L))
882 L = L->getParentLoop();
883
884 while (L != nullptr) {
885 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
886 SE.getUnknown(Builder.getInt64(1)),
887 L, SCEV::FlagAnyWrap);
888 Value *V = generateSCEV(OuterLIV);
889 OutsideLoopIterations[L] = SE.getUnknown(V);
890 L = L->getParentLoop();
891 }
892
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000893 isl_set_free(Context);
894}
895
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000896Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
897 Instruction *InsertLocation = --(Builder.GetInsertBlock()->end());
Tobias Grosserbb8d1562015-03-04 19:33:31 +0000898 return Rewriter.expandCodeFor(Expr, Expr->getType(), InsertLocation);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000899}
900
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000901namespace {
902class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000903public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000904 static char ID;
905
906 IslCodeGeneration() : ScopPass(ID) {}
907
Tobias Grossere3c05582014-11-15 21:32:53 +0000908 /// @brief The datalayout used
909 const DataLayout *DL;
910
Johannes Doerfert38262242014-09-10 14:50:23 +0000911 /// @name The analysis passes we need to generate code.
912 ///
913 ///{
914 LoopInfo *LI;
915 IslAstInfo *AI;
916 DominatorTree *DT;
917 ScalarEvolution *SE;
918 ///}
919
920 /// @brief The loop annotator to generate llvm.loop metadata.
Johannes Doerfert51d1c742014-10-02 15:32:17 +0000921 ScopAnnotator Annotator;
Johannes Doerfert38262242014-09-10 14:50:23 +0000922
923 /// @brief Build the runtime condition.
924 ///
925 /// Build the condition that evaluates at run-time to true iff all
926 /// assumptions taken for the SCoP hold, and to false otherwise.
927 ///
928 /// @return A value evaluating to true/false if execution is save/unsafe.
929 Value *buildRTC(PollyIRBuilder &Builder, IslExprBuilder &ExprBuilder) {
930 Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
931 Value *RTC = ExprBuilder.create(AI->getRunCondition());
Johannes Doerfertb164c792014-09-18 11:17:17 +0000932 if (!RTC->getType()->isIntegerTy(1))
933 RTC = Builder.CreateIsNotNull(RTC);
934 return RTC;
Johannes Doerfert38262242014-09-10 14:50:23 +0000935 }
936
Johannes Doerfert0b169c02015-02-27 17:37:05 +0000937 bool verifyGeneratedFunction(Scop &S, Function &F) {
938 if (!verifyFunction(F))
939 return false;
940
941 DEBUG({
942 errs() << "== ISL Codegen created an invalid function ==\n\n== The "
943 "SCoP ==\n";
944 S.print(errs());
945 errs() << "\n== The isl AST ==\n";
Johannes Doerfert3fe584d2015-03-01 18:40:25 +0000946 AI->printScop(errs(), S);
Johannes Doerfert0b169c02015-02-27 17:37:05 +0000947 errs() << "\n== The invalid function ==\n";
948 F.print(errs());
949 errs() << "\n== The errors ==\n";
950 verifyFunction(F, &errs());
951 });
952
953 return true;
954 }
955
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000956 bool runOnScop(Scop &S) override {
Johannes Doerfert38262242014-09-10 14:50:23 +0000957 AI = &getAnalysis<IslAstInfo>();
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000958
959 // Check if we created an isl_ast root node, otherwise exit.
960 isl_ast_node *AstRoot = AI->getAst();
961 if (!AstRoot)
962 return false;
963
964 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfert38262242014-09-10 14:50:23 +0000965 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
966 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser140b3942015-03-05 09:48:20 +0000967 DL = &S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000968
Tobias Grossere602a072013-05-07 07:30:56 +0000969 assert(!S.getRegion().isTopLevelRegion() &&
970 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000971
Johannes Doerfertecdf2632014-10-02 15:31:24 +0000972 // Build the alias scopes for annotations first.
973 if (PollyAnnotateAliasScopes)
974 Annotator.buildAliasScopes(S);
975
Johannes Doerfert38262242014-09-10 14:50:23 +0000976 BasicBlock *EnteringBB = simplifyRegion(&S, this);
977 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000978
Tobias Grossere3c05582014-11-15 21:32:53 +0000979 IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S);
Tobias Grosser28735942014-08-16 09:09:15 +0000980 NodeBuilder.addParameters(S.getContext());
Johannes Doerfert38262242014-09-10 14:50:23 +0000981
982 Value *RTC = buildRTC(Builder, NodeBuilder.getExprBuilder());
983 BasicBlock *StartBlock = executeScopConditionally(S, this, RTC);
Tobias Grosser28735942014-08-16 09:09:15 +0000984 Builder.SetInsertPoint(StartBlock->begin());
985
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000986 NodeBuilder.create(AstRoot);
Johannes Doerfert0b169c02015-02-27 17:37:05 +0000987
988 assert(!verifyGeneratedFunction(S, *EnteringBB->getParent()) &&
989 "Verification of generated function failed");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000990 return true;
991 }
992
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000993 void printScop(raw_ostream &, Scop &) const override {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000994
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000995 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tobias Grosser42aff302014-01-13 22:29:56 +0000996 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000997 AU.addRequired<IslAstInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000998 AU.addRequired<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000999 AU.addRequired<ScalarEvolution>();
1000 AU.addRequired<ScopDetection>();
1001 AU.addRequired<ScopInfo>();
Chandler Carruthf5579872015-01-17 14:16:56 +00001002 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001003
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001004 AU.addPreserved<DependenceInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001005
Chandler Carruthf5579872015-01-17 14:16:56 +00001006 AU.addPreserved<LoopInfoWrapperPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001007 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001008 AU.addPreserved<IslAstInfo>();
1009 AU.addPreserved<ScopDetection>();
1010 AU.addPreserved<ScalarEvolution>();
1011
1012 // FIXME: We do not yet add regions for the newly generated code to the
1013 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +00001014 AU.addPreserved<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001015 AU.addPreserved<TempScopInfo>();
1016 AU.addPreserved<ScopInfo>();
1017 AU.addPreservedID(IndependentBlocksID);
1018 }
1019};
1020}
1021
1022char IslCodeGeneration::ID = 1;
1023
Tobias Grosser7242ad92013-02-22 08:07:06 +00001024Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001025
Tobias Grosser7242ad92013-02-22 08:07:06 +00001026INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
1027 "Polly - Create LLVM-IR from SCoPs", false, false);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001028INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
Tobias Grosser42aff302014-01-13 22:29:56 +00001029INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001030INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001031INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001032INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1033INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1034INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
1035 "Polly - Create LLVM-IR from SCoPs", false, false)