blob: ed1b5f27268aacb99c479e6833ff238487a41a0a [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"
Tobias Grosser83628182013-05-07 08:11:54 +000022#include "polly/CodeGen/BlockGenerators.h"
23#include "polly/CodeGen/CodeGeneration.h"
24#include "polly/CodeGen/IslAst.h"
25#include "polly/CodeGen/LoopGenerators.h"
26#include "polly/CodeGen/Utils.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000027#include "polly/Dependences.h"
28#include "polly/LinkAllPasses.h"
29#include "polly/ScopInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000030#include "polly/Support/GICHelper.h"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000031#include "polly/Support/ScopHelper.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "polly/TempScopInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000033#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/IR/Module.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000038#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
40
41#include "isl/union_map.h"
42#include "isl/list.h"
43#include "isl/ast.h"
44#include "isl/ast_build.h"
45#include "isl/set.h"
46#include "isl/map.h"
47#include "isl/aff.h"
48
49#include <map>
50
51using namespace polly;
52using namespace llvm;
53
Chandler Carruth95fef942014-04-22 03:30:19 +000054#define DEBUG_TYPE "polly-codegen-isl"
55
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000056/// @brief Insert function calls that print certain LLVM values at run time.
57///
58/// This class inserts libc function calls to print certain LLVM values at
59/// run time.
60class RuntimeDebugBuilder {
61public:
Tobias Grosser5103ba72014-03-04 14:58:49 +000062 RuntimeDebugBuilder(PollyIRBuilder &Builder) : Builder(Builder) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000063
64 /// @brief Print a string to stdout.
65 ///
66 /// @param String The string to print.
67 void createStrPrinter(std::string String);
68
69 /// @brief Print an integer value to stdout.
70 ///
71 /// @param V The value to print.
72 void createIntPrinter(Value *V);
73
74private:
Tobias Grosser5103ba72014-03-04 14:58:49 +000075 PollyIRBuilder &Builder;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000076
77 /// @brief Add a call to the fflush function with no file pointer given.
78 ///
79 /// This call will flush all opened file pointers including stdout and stderr.
80 void createFlush();
81
82 /// @brief Get a reference to the 'printf' function.
83 ///
84 /// If the current module does not yet contain a reference to printf, we
85 /// insert a reference to it. Otherwise the existing reference is returned.
86 Function *getPrintF();
87};
88
89Function *RuntimeDebugBuilder::getPrintF() {
90 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
91 const char *Name = "printf";
92 Function *F = M->getFunction(Name);
93
94 if (!F) {
95 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosserc14582f2013-02-05 18:01:29 +000096 FunctionType *Ty =
97 FunctionType::get(Builder.getInt32Ty(), Builder.getInt8PtrTy(), true);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000098 F = Function::Create(Ty, Linkage, Name, M);
99 }
100
101 return F;
102}
103
104void RuntimeDebugBuilder::createFlush() {
105 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
106 const char *Name = "fflush";
107 Function *F = M->getFunction(Name);
108
109 if (!F) {
110 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000111 FunctionType *Ty =
112 FunctionType::get(Builder.getInt32Ty(), Builder.getInt8PtrTy(), false);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000113 F = Function::Create(Ty, Linkage, Name, M);
114 }
115
116 Builder.CreateCall(F, Constant::getNullValue(Builder.getInt8PtrTy()));
117}
118
119void RuntimeDebugBuilder::createStrPrinter(std::string String) {
120 Function *F = getPrintF();
121 Value *StringValue = Builder.CreateGlobalStringPtr(String);
122 Builder.CreateCall(F, StringValue);
123
124 createFlush();
125}
126
127void RuntimeDebugBuilder::createIntPrinter(Value *V) {
128 IntegerType *Ty = dyn_cast<IntegerType>(V->getType());
Tobias Grosser58032cb2013-06-23 01:29:29 +0000129 (void)Ty;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000130 assert(Ty && Ty->getBitWidth() == 64 &&
131 "Cannot insert printer for this type.");
132
133 Function *F = getPrintF();
134 Value *String = Builder.CreateGlobalStringPtr("%ld");
135 Builder.CreateCall2(F, String, V);
136 createFlush();
137}
138
139/// @brief Calculate the Value of a certain isl_ast_expr
140class IslExprBuilder {
141public:
Tobias Grosser5103ba72014-03-04 14:58:49 +0000142 IslExprBuilder(PollyIRBuilder &Builder,
143 std::map<isl_id *, Value *> &IDToValue, Pass *P)
Tobias Grosser7242ad92013-02-22 08:07:06 +0000144 : Builder(Builder), IDToValue(IDToValue) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000145
146 Value *create(__isl_take isl_ast_expr *Expr);
147 Type *getWidestType(Type *T1, Type *T2);
148 IntegerType *getType(__isl_keep isl_ast_expr *Expr);
149
150private:
Tobias Grosser5103ba72014-03-04 14:58:49 +0000151 PollyIRBuilder &Builder;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000152 std::map<isl_id *, Value *> &IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000153
154 Value *createOp(__isl_take isl_ast_expr *Expr);
155 Value *createOpUnary(__isl_take isl_ast_expr *Expr);
156 Value *createOpBin(__isl_take isl_ast_expr *Expr);
157 Value *createOpNAry(__isl_take isl_ast_expr *Expr);
158 Value *createOpSelect(__isl_take isl_ast_expr *Expr);
159 Value *createOpICmp(__isl_take isl_ast_expr *Expr);
160 Value *createOpBoolean(__isl_take isl_ast_expr *Expr);
161 Value *createId(__isl_take isl_ast_expr *Expr);
162 Value *createInt(__isl_take isl_ast_expr *Expr);
163};
164
165Type *IslExprBuilder::getWidestType(Type *T1, Type *T2) {
166 assert(isa<IntegerType>(T1) && isa<IntegerType>(T2));
167
168 if (T1->getPrimitiveSizeInBits() < T2->getPrimitiveSizeInBits())
169 return T2;
170 else
171 return T1;
172}
173
174Value *IslExprBuilder::createOpUnary(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000175 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_minus &&
176 "Unsupported unary operation");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000177
178 Value *V;
179 Type *MaxType = getType(Expr);
180
181 V = create(isl_ast_expr_get_op_arg(Expr, 0));
182 MaxType = getWidestType(MaxType, V->getType());
183
184 if (MaxType != V->getType())
185 V = Builder.CreateSExt(V, MaxType);
186
187 isl_ast_expr_free(Expr);
188 return Builder.CreateNSWNeg(V);
189}
190
191Value *IslExprBuilder::createOpNAry(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000192 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
193 "isl ast expression not of type isl_ast_op");
194 assert(isl_ast_expr_get_op_n_arg(Expr) >= 2 &&
195 "We need at least two operands in an n-ary operation");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000196
197 Value *V;
198
199 V = create(isl_ast_expr_get_op_arg(Expr, 0));
200
201 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr); ++i) {
202 Value *OpV;
203 OpV = create(isl_ast_expr_get_op_arg(Expr, i));
204
205 Type *Ty = getWidestType(V->getType(), OpV->getType());
206
207 if (Ty != OpV->getType())
208 OpV = Builder.CreateSExt(OpV, Ty);
209
210 if (Ty != V->getType())
211 V = Builder.CreateSExt(V, Ty);
212
213 switch (isl_ast_expr_get_op_type(Expr)) {
214 default:
215 llvm_unreachable("This is no n-ary isl ast expression");
216
Tobias Grosserc14582f2013-02-05 18:01:29 +0000217 case isl_ast_op_max: {
218 Value *Cmp = Builder.CreateICmpSGT(V, OpV);
219 V = Builder.CreateSelect(Cmp, V, OpV);
220 continue;
221 }
222 case isl_ast_op_min: {
223 Value *Cmp = Builder.CreateICmpSLT(V, OpV);
224 V = Builder.CreateSelect(Cmp, V, OpV);
225 continue;
226 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000227 }
228 }
229
230 // TODO: We can truncate the result, if it fits into a smaller type. This can
231 // help in cases where we have larger operands (e.g. i67) but the result is
232 // known to fit into i64. Without the truncation, the larger i67 type may
233 // force all subsequent operations to be performed on a non-native type.
234 isl_ast_expr_free(Expr);
235 return V;
236}
237
238Value *IslExprBuilder::createOpBin(__isl_take isl_ast_expr *Expr) {
239 Value *LHS, *RHS, *Res;
240 Type *MaxType;
241 isl_ast_op_type OpType;
242
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000243 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
244 "isl ast expression not of type isl_ast_op");
245 assert(isl_ast_expr_get_op_n_arg(Expr) == 2 &&
246 "not a binary isl ast expression");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000247
248 OpType = isl_ast_expr_get_op_type(Expr);
249
250 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
251 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
252
253 MaxType = LHS->getType();
254 MaxType = getWidestType(MaxType, RHS->getType());
255
256 // Take the result into account when calculating the widest type.
257 //
258 // For operations such as '+' the result may require a type larger than
259 // the type of the individual operands. For other operations such as '/', the
260 // result type cannot be larger than the type of the individual operand. isl
261 // does not calculate correct types for these operations and we consequently
262 // exclude those operations here.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000263 switch (OpType) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000264 case isl_ast_op_pdiv_q:
265 case isl_ast_op_pdiv_r:
266 case isl_ast_op_div:
267 case isl_ast_op_fdiv_q:
268 // Do nothing
269 break;
270 case isl_ast_op_add:
271 case isl_ast_op_sub:
272 case isl_ast_op_mul:
273 MaxType = getWidestType(MaxType, getType(Expr));
274 break;
275 default:
276 llvm_unreachable("This is no binary isl ast expression");
277 }
278
279 if (MaxType != RHS->getType())
280 RHS = Builder.CreateSExt(RHS, MaxType);
281
282 if (MaxType != LHS->getType())
283 LHS = Builder.CreateSExt(LHS, MaxType);
284
285 switch (OpType) {
286 default:
287 llvm_unreachable("This is no binary isl ast expression");
288 case isl_ast_op_add:
289 Res = Builder.CreateNSWAdd(LHS, RHS);
290 break;
291 case isl_ast_op_sub:
292 Res = Builder.CreateNSWSub(LHS, RHS);
293 break;
294 case isl_ast_op_mul:
295 Res = Builder.CreateNSWMul(LHS, RHS);
296 break;
297 case isl_ast_op_div:
298 case isl_ast_op_pdiv_q: // Dividend is non-negative
299 Res = Builder.CreateSDiv(LHS, RHS);
300 break;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000301 case isl_ast_op_fdiv_q: { // Round towards -infty
302 // TODO: Review code and check that this calculation does not yield
303 // incorrect overflow in some bordercases.
304 //
305 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
306 Value *One = ConstantInt::get(MaxType, 1);
307 Value *Zero = ConstantInt::get(MaxType, 0);
308 Value *Sum1 = Builder.CreateSub(LHS, RHS);
309 Value *Sum2 = Builder.CreateAdd(Sum1, One);
310 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
311 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
312 Res = Builder.CreateSDiv(Dividend, RHS);
313 break;
314 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000315 case isl_ast_op_pdiv_r: // Dividend is non-negative
316 Res = Builder.CreateSRem(LHS, RHS);
317 break;
318 }
319
320 // TODO: We can truncate the result, if it fits into a smaller type. This can
321 // help in cases where we have larger operands (e.g. i67) but the result is
322 // known to fit into i64. Without the truncation, the larger i67 type may
323 // force all subsequent operations to be performed on a non-native type.
324 isl_ast_expr_free(Expr);
325 return Res;
326}
327
328Value *IslExprBuilder::createOpSelect(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000329 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_select &&
330 "Unsupported unary isl ast expression");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000331 Value *LHS, *RHS, *Cond;
332 Type *MaxType = getType(Expr);
333
334 Cond = create(isl_ast_expr_get_op_arg(Expr, 0));
335
336 LHS = create(isl_ast_expr_get_op_arg(Expr, 1));
337 RHS = create(isl_ast_expr_get_op_arg(Expr, 2));
338
339 MaxType = getWidestType(MaxType, LHS->getType());
340 MaxType = getWidestType(MaxType, RHS->getType());
341
342 if (MaxType != RHS->getType())
343 RHS = Builder.CreateSExt(RHS, MaxType);
344
345 if (MaxType != LHS->getType())
346 LHS = Builder.CreateSExt(LHS, MaxType);
347
348 // TODO: Do we want to truncate the result?
349 isl_ast_expr_free(Expr);
350 return Builder.CreateSelect(Cond, LHS, RHS);
351}
352
353Value *IslExprBuilder::createOpICmp(__isl_take isl_ast_expr *Expr) {
354 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
355 "Expected an isl_ast_expr_op expression");
356
357 Value *LHS, *RHS, *Res;
358
359 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
360 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
361
362 Type *MaxType = LHS->getType();
363 MaxType = getWidestType(MaxType, RHS->getType());
364
365 if (MaxType != RHS->getType())
366 RHS = Builder.CreateSExt(RHS, MaxType);
367
368 if (MaxType != LHS->getType())
369 LHS = Builder.CreateSExt(LHS, MaxType);
370
371 switch (isl_ast_expr_get_op_type(Expr)) {
372 default:
373 llvm_unreachable("Unsupported ICmp isl ast expression");
374 case isl_ast_op_eq:
375 Res = Builder.CreateICmpEQ(LHS, RHS);
376 break;
377 case isl_ast_op_le:
378 Res = Builder.CreateICmpSLE(LHS, RHS);
379 break;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000380 case isl_ast_op_lt:
381 Res = Builder.CreateICmpSLT(LHS, RHS);
382 break;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000383 case isl_ast_op_ge:
384 Res = Builder.CreateICmpSGE(LHS, RHS);
385 break;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000386 case isl_ast_op_gt:
387 Res = Builder.CreateICmpSGT(LHS, RHS);
388 break;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000389 }
390
391 isl_ast_expr_free(Expr);
392 return Res;
393}
394
395Value *IslExprBuilder::createOpBoolean(__isl_take isl_ast_expr *Expr) {
396 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
397 "Expected an isl_ast_expr_op expression");
398
399 Value *LHS, *RHS, *Res;
400 isl_ast_op_type OpType;
401
402 OpType = isl_ast_expr_get_op_type(Expr);
403
404 assert((OpType == isl_ast_op_and || OpType == isl_ast_op_or) &&
405 "Unsupported isl_ast_op_type");
406
407 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
408 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
409
410 // Even though the isl pretty printer prints the expressions as 'exp && exp'
411 // or 'exp || exp', we actually code generate the bitwise expressions
412 // 'exp & exp' or 'exp | exp'. This forces the evaluation of both branches,
413 // but it is, due to the use of i1 types, otherwise equivalent. The reason
414 // to go for bitwise operations is, that we assume the reduced control flow
415 // will outweight the overhead introduced by evaluating unneeded expressions.
416 // The isl code generation currently does not take advantage of the fact that
417 // the expression after an '||' or '&&' is in some cases not evaluated.
418 // Evaluating it anyways does not cause any undefined behaviour.
419 //
420 // TODO: Document in isl itself, that the unconditionally evaluating the
421 // second part of '||' or '&&' expressions is safe.
422 assert(LHS->getType() == Builder.getInt1Ty() && "Expected i1 type");
423 assert(RHS->getType() == Builder.getInt1Ty() && "Expected i1 type");
424
425 switch (OpType) {
426 default:
427 llvm_unreachable("Unsupported boolean expression");
428 case isl_ast_op_and:
429 Res = Builder.CreateAnd(LHS, RHS);
430 break;
431 case isl_ast_op_or:
432 Res = Builder.CreateOr(LHS, RHS);
433 break;
434 }
435
436 isl_ast_expr_free(Expr);
437 return Res;
438}
439
440Value *IslExprBuilder::createOp(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000441 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
442 "Expression not of type isl_ast_expr_op");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000443 switch (isl_ast_expr_get_op_type(Expr)) {
444 case isl_ast_op_error:
445 case isl_ast_op_cond:
446 case isl_ast_op_and_then:
447 case isl_ast_op_or_else:
448 case isl_ast_op_call:
Tobias Grossera38c9242014-01-26 19:36:28 +0000449 case isl_ast_op_member:
450 case isl_ast_op_access:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000451 llvm_unreachable("Unsupported isl ast expression");
452 case isl_ast_op_max:
453 case isl_ast_op_min:
454 return createOpNAry(Expr);
455 case isl_ast_op_add:
456 case isl_ast_op_sub:
457 case isl_ast_op_mul:
458 case isl_ast_op_div:
459 case isl_ast_op_fdiv_q: // Round towards -infty
460 case isl_ast_op_pdiv_q: // Dividend is non-negative
461 case isl_ast_op_pdiv_r: // Dividend is non-negative
462 return createOpBin(Expr);
463 case isl_ast_op_minus:
464 return createOpUnary(Expr);
465 case isl_ast_op_select:
466 return createOpSelect(Expr);
467 case isl_ast_op_and:
468 case isl_ast_op_or:
469 return createOpBoolean(Expr);
470 case isl_ast_op_eq:
471 case isl_ast_op_le:
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000472 case isl_ast_op_lt:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000473 case isl_ast_op_ge:
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000474 case isl_ast_op_gt:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000475 return createOpICmp(Expr);
476 }
477
478 llvm_unreachable("Unsupported isl_ast_expr_op kind.");
479}
480
481Value *IslExprBuilder::createId(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000482 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_id &&
483 "Expression not of type isl_ast_expr_ident");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000484
485 isl_id *Id;
486 Value *V;
487
488 Id = isl_ast_expr_get_id(Expr);
489
490 assert(IDToValue.count(Id) && "Identifier not found");
491
492 V = IDToValue[Id];
493
494 isl_id_free(Id);
495 isl_ast_expr_free(Expr);
496
497 return V;
498}
499
500IntegerType *IslExprBuilder::getType(__isl_keep isl_ast_expr *Expr) {
501 // XXX: We assume i64 is large enough. This is often true, but in general
502 // incorrect. Also, on 32bit architectures, it would be beneficial to
503 // use a smaller type. We can and should directly derive this information
504 // during code generation.
505 return IntegerType::get(Builder.getContext(), 64);
506}
507
508Value *IslExprBuilder::createInt(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000509 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_int &&
510 "Expression not of type isl_ast_expr_int");
Tobias Grosseredab1352013-06-21 06:41:31 +0000511 isl_val *Val;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000512 Value *V;
513 APInt APValue;
514 IntegerType *T;
515
Tobias Grosseredab1352013-06-21 06:41:31 +0000516 Val = isl_ast_expr_get_val(Expr);
517 APValue = APIntFromVal(Val);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000518 T = getType(Expr);
519 APValue = APValue.sextOrSelf(T->getBitWidth());
520 V = ConstantInt::get(T, APValue);
521
522 isl_ast_expr_free(Expr);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000523 return V;
524}
525
526Value *IslExprBuilder::create(__isl_take isl_ast_expr *Expr) {
527 switch (isl_ast_expr_get_type(Expr)) {
528 case isl_ast_expr_error:
529 llvm_unreachable("Code generation error");
530 case isl_ast_expr_op:
531 return createOp(Expr);
532 case isl_ast_expr_id:
533 return createId(Expr);
534 case isl_ast_expr_int:
535 return createInt(Expr);
536 }
537
538 llvm_unreachable("Unexpected enum value");
539}
540
541class IslNodeBuilder {
542public:
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000543 IslNodeBuilder(PollyIRBuilder &Builder, LoopAnnotator &Annotator, Pass *P)
544 : Builder(Builder), Annotator(Annotator),
545 ExprBuilder(Builder, IDToValue, P), P(P) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000546
547 void addParameters(__isl_take isl_set *Context);
548 void create(__isl_take isl_ast_node *Node);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +0000549 IslExprBuilder &getExprBuilder() { return ExprBuilder; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000550
551private:
Tobias Grosser5103ba72014-03-04 14:58:49 +0000552 PollyIRBuilder &Builder;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000553 LoopAnnotator &Annotator;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000554 IslExprBuilder ExprBuilder;
555 Pass *P;
556
557 // This maps an isl_id* to the Value* it has in the generated program. For now
558 // on, the only isl_ids that are stored here are the newly calculated loop
559 // ivs.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000560 std::map<isl_id *, Value *> IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000561
562 // Extract the upper bound of this loop
563 //
564 // The isl code generation can generate arbitrary expressions to check if the
565 // upper bound of a loop is reached, but it provides an option to enforce
566 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
567 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
568 //
569 // This function extracts 'atomic' upper bounds. Polly, in general, requires
570 // atomic upper bounds for the following reasons:
571 //
572 // 1. An atomic upper bound is loop invariant
573 //
574 // It must not be calculated at each loop iteration and can often even be
575 // hoisted out further by the loop invariant code motion.
576 //
577 // 2. OpenMP needs a loop invarient upper bound to calculate the number
578 // of loop iterations.
579 //
580 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grossere602a072013-05-07 07:30:56 +0000581 __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
582 CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000583
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000584 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
585
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000586 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000587 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
588 void createForSequential(__isl_take isl_ast_node *For);
589 void createSubstitutions(__isl_take isl_pw_multi_aff *PMA,
Tobias Grosserc14582f2013-02-05 18:01:29 +0000590 __isl_take isl_ast_build *Context, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000591 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grossere602a072013-05-07 07:30:56 +0000592 void createSubstitutionsVector(__isl_take isl_pw_multi_aff *PMA,
593 __isl_take isl_ast_build *Context,
594 ScopStmt *Stmt, VectorValueMapT &VMap,
595 std::vector<LoopToScevMapT> &VLTS,
596 std::vector<Value *> &IVS,
597 __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000598 void createIf(__isl_take isl_ast_node *If);
Tobias Grossere602a072013-05-07 07:30:56 +0000599 void createUserVector(__isl_take isl_ast_node *User,
600 std::vector<Value *> &IVS,
601 __isl_take isl_id *IteratorID,
602 __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000603 void createUser(__isl_take isl_ast_node *User);
604 void createBlock(__isl_take isl_ast_node *Block);
605};
606
Tobias Grossere602a072013-05-07 07:30:56 +0000607__isl_give isl_ast_expr *
608IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
609 ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000610 isl_id *UBID, *IteratorID;
611 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000612 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000613
614 Cond = isl_ast_node_for_get_cond(For);
615 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000616 Type = isl_ast_expr_get_op_type(Cond);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000617
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000618 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
619 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000620
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000621 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000622 case isl_ast_op_le:
623 Predicate = ICmpInst::ICMP_SLE;
624 break;
625 case isl_ast_op_lt:
626 Predicate = ICmpInst::ICMP_SLT;
627 break;
628 default:
629 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000630 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000631
632 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
633
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000634 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
635 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000636
637 UBID = isl_ast_expr_get_id(Arg0);
638
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000639 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
640 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000641
642 IteratorID = isl_ast_expr_get_id(Iterator);
643
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000644 assert(UBID == IteratorID &&
645 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000646
647 UB = isl_ast_expr_get_op_arg(Cond, 1);
648
649 isl_ast_expr_free(Cond);
650 isl_ast_expr_free(Iterator);
651 isl_ast_expr_free(Arg0);
652 isl_id_free(IteratorID);
653 isl_id_free(UBID);
654
655 return UB;
656}
657
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000658unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
659 isl_id *Annotation = isl_ast_node_get_annotation(For);
660 if (!Annotation)
661 return -1;
662
Tobias Grosserc14582f2013-02-05 18:01:29 +0000663 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000664 if (!Info) {
665 isl_id_free(Annotation);
666 return -1;
667 }
668
669 isl_union_map *Schedule = isl_ast_build_get_schedule(Info->Context);
670 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
671 isl_id_free(Annotation);
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000672 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
673 if (NumberOfIterations == -1)
674 return -1;
675 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000676}
677
Tobias Grossere602a072013-05-07 07:30:56 +0000678void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
679 std::vector<Value *> &IVS,
680 __isl_take isl_id *IteratorID,
681 __isl_take isl_union_map *Schedule) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000682 isl_id *Annotation = isl_ast_node_get_annotation(User);
683 assert(Annotation && "Vector user statement is not annotated");
684
Tobias Grosserc14582f2013-02-05 18:01:29 +0000685 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000686 assert(Info && "Vector user statement annotation does not contain info");
687
688 isl_id *Id = isl_pw_multi_aff_get_tuple_id(Info->PMA, isl_dim_out);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000689 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000690 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000691 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000692
693 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
694 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
695 isl_map *S = isl_map_from_union_map(Schedule);
696
697 createSubstitutionsVector(isl_pw_multi_aff_copy(Info->PMA),
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000698 isl_ast_build_copy(Info->Context), Stmt, VectorMap,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000699 VLTS, IVS, IteratorID);
700 VectorBlockGenerator::generate(Builder, *Stmt, VectorMap, VLTS, S, P);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000701
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000702 isl_map_free(S);
703 isl_id_free(Annotation);
704 isl_id_free(Id);
705 isl_ast_node_free(User);
706}
707
Tobias Grossere602a072013-05-07 07:30:56 +0000708void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
709 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000710 isl_ast_node *Body = isl_ast_node_for_get_body(For);
711 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
712 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
713 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
714 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000715
716 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000717 Value *ValueInc = ExprBuilder.create(Inc);
718
719 Type *MaxType = ExprBuilder.getType(Iterator);
720 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000721 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
722
723 if (MaxType != ValueLB->getType())
724 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000725 if (MaxType != ValueInc->getType())
726 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
727
Tobias Grosserc14582f2013-02-05 18:01:29 +0000728 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000729 IVS[0] = ValueLB;
730
731 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000732 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000733
734 isl_id *Annotation = isl_ast_node_get_annotation(For);
735 assert(Annotation && "For statement is not annotated");
736
Tobias Grosserc14582f2013-02-05 18:01:29 +0000737 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000738 assert(Info && "For statement annotation does not contain info");
739
740 isl_union_map *Schedule = isl_ast_build_get_schedule(Info->Context);
741 assert(Schedule && "For statement annotation does not contain its schedule");
742
743 IDToValue[IteratorID] = ValueLB;
744
745 switch (isl_ast_node_get_type(Body)) {
746 case isl_ast_node_user:
747 createUserVector(Body, IVS, isl_id_copy(IteratorID),
748 isl_union_map_copy(Schedule));
749 break;
750 case isl_ast_node_block: {
751 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
752
753 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
754 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000755 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000756
757 isl_ast_node_free(Body);
758 isl_ast_node_list_free(List);
759 break;
760 }
761 default:
762 isl_ast_node_dump(Body);
763 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
764 }
765
766 IDToValue.erase(IteratorID);
767 isl_id_free(IteratorID);
768 isl_id_free(Annotation);
769 isl_union_map_free(Schedule);
770
771 isl_ast_node_free(For);
772 isl_ast_expr_free(Iterator);
773}
774
775void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000776 isl_ast_node *Body;
777 isl_ast_expr *Init, *Inc, *Iterator, *UB;
778 isl_id *IteratorID;
779 Value *ValueLB, *ValueUB, *ValueInc;
780 Type *MaxType;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000781 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000782 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000783 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000784 bool Parallel;
785
786 Parallel = isInnermostParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000787
788 Body = isl_ast_node_for_get_body(For);
789
790 // isl_ast_node_for_is_degenerate(For)
791 //
792 // TODO: For degenerated loops we could generate a plain assignment.
793 // However, for now we just reuse the logic for normal loops, which will
794 // create a loop with a single iteration.
795
796 Init = isl_ast_node_for_get_init(For);
797 Inc = isl_ast_node_for_get_inc(For);
798 Iterator = isl_ast_node_for_get_iterator(For);
799 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000800 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000801
802 ValueLB = ExprBuilder.create(Init);
803 ValueUB = ExprBuilder.create(UB);
804 ValueInc = ExprBuilder.create(Inc);
805
806 MaxType = ExprBuilder.getType(Iterator);
807 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
808 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
809 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
810
811 if (MaxType != ValueLB->getType())
812 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
813 if (MaxType != ValueUB->getType())
814 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
815 if (MaxType != ValueInc->getType())
816 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
817
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000818 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, ExitBlock, Predicate,
819 &Annotator, Parallel);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000820 IDToValue[IteratorID] = IV;
821
822 create(Body);
823
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000824 Annotator.End();
825
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000826 IDToValue.erase(IteratorID);
827
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000828 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000829
830 isl_ast_node_free(For);
831 isl_ast_expr_free(Iterator);
832 isl_id_free(IteratorID);
833}
834
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000835void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
836 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
837
838 if (Vector && isInnermostParallel(For)) {
839 int VectorWidth = getNumberOfIterations(For);
840 if (1 < VectorWidth && VectorWidth <= 16) {
841 createForVector(For, VectorWidth);
842 return;
843 }
844 }
845 createForSequential(For);
846}
847
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000848void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
849 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
850
851 Function *F = Builder.GetInsertBlock()->getParent();
852 LLVMContext &Context = F->getContext();
853
Tobias Grosserc14582f2013-02-05 18:01:29 +0000854 BasicBlock *CondBB =
855 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000856 CondBB->setName("polly.cond");
857 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
858 MergeBB->setName("polly.merge");
859 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
860 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
861
Tobias Grosser42aff302014-01-13 22:29:56 +0000862 DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000863 DT.addNewBlock(ThenBB, CondBB);
864 DT.addNewBlock(ElseBB, CondBB);
865 DT.changeImmediateDominator(MergeBB, CondBB);
866
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000867 LoopInfo &LI = P->getAnalysis<LoopInfo>();
868 Loop *L = LI.getLoopFor(CondBB);
869 if (L) {
870 L->addBasicBlockToLoop(ThenBB, LI.getBase());
871 L->addBasicBlockToLoop(ElseBB, LI.getBase());
872 }
873
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000874 CondBB->getTerminator()->eraseFromParent();
875
876 Builder.SetInsertPoint(CondBB);
877 Value *Predicate = ExprBuilder.create(Cond);
878 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
879 Builder.SetInsertPoint(ThenBB);
880 Builder.CreateBr(MergeBB);
881 Builder.SetInsertPoint(ElseBB);
882 Builder.CreateBr(MergeBB);
883 Builder.SetInsertPoint(ThenBB->begin());
884
885 create(isl_ast_node_if_get_then(If));
886
887 Builder.SetInsertPoint(ElseBB->begin());
888
889 if (isl_ast_node_if_has_else(If))
890 create(isl_ast_node_if_get_else(If));
891
892 Builder.SetInsertPoint(MergeBB->begin());
893
894 isl_ast_node_free(If);
895}
896
Tobias Grossere602a072013-05-07 07:30:56 +0000897void IslNodeBuilder::createSubstitutions(__isl_take isl_pw_multi_aff *PMA,
898 __isl_take isl_ast_build *Context,
899 ScopStmt *Stmt, ValueMapT &VMap,
900 LoopToScevMapT &LTS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000901 for (unsigned i = 0; i < isl_pw_multi_aff_dim(PMA, isl_dim_out); ++i) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000902 isl_pw_aff *Aff;
903 isl_ast_expr *Expr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000904 Value *V;
905
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000906 Aff = isl_pw_multi_aff_get_pw_aff(PMA, i);
907 Expr = isl_ast_build_expr_from_pw_aff(Context, Aff);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000908 V = ExprBuilder.create(Expr);
909
Sebastian Pope039bb12013-03-18 19:09:49 +0000910 ScalarEvolution *SE = Stmt->getParent()->getSE();
911 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
912
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000913 // CreateIntCast can introduce trunc expressions. This is correct, as the
914 // result will always fit into the type of the original induction variable
915 // (because we calculate a value of the original induction variable).
Sebastian Pope039bb12013-03-18 19:09:49 +0000916 const Value *OldIV = Stmt->getInductionVariableForDimension(i);
917 if (OldIV) {
918 V = Builder.CreateIntCast(V, OldIV->getType(), true);
919 VMap[OldIV] = V;
920 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000921 }
922
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000923 isl_pw_multi_aff_free(PMA);
924 isl_ast_build_free(Context);
925}
926
Tobias Grosserc14582f2013-02-05 18:01:29 +0000927void IslNodeBuilder::createSubstitutionsVector(
928 __isl_take isl_pw_multi_aff *PMA, __isl_take isl_ast_build *Context,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000929 ScopStmt *Stmt, VectorValueMapT &VMap, std::vector<LoopToScevMapT> &VLTS,
930 std::vector<Value *> &IVS, __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000931 int i = 0;
932
933 Value *OldValue = IDToValue[IteratorID];
Tobias Grosserc14582f2013-02-05 18:01:29 +0000934 for (std::vector<Value *>::iterator II = IVS.begin(), IE = IVS.end();
935 II != IE; ++II) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000936 IDToValue[IteratorID] = *II;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000937 createSubstitutions(isl_pw_multi_aff_copy(PMA), isl_ast_build_copy(Context),
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000938 Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000939 i++;
940 }
941
942 IDToValue[IteratorID] = OldValue;
943 isl_id_free(IteratorID);
944 isl_pw_multi_aff_free(PMA);
945 isl_ast_build_free(Context);
946}
947
948void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
949 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000950 LoopToScevMapT LTS;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000951 struct IslAstUser *Info;
952 isl_id *Annotation, *Id;
953 ScopStmt *Stmt;
954
955 Annotation = isl_ast_node_get_annotation(User);
956 assert(Annotation && "Scalar user statement is not annotated");
957
Tobias Grosserc14582f2013-02-05 18:01:29 +0000958 Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000959 assert(Info && "Scalar user statement annotation does not contain info");
960
961 Id = isl_pw_multi_aff_get_tuple_id(Info->PMA, isl_dim_out);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000962 Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000963
964 createSubstitutions(isl_pw_multi_aff_copy(Info->PMA),
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000965 isl_ast_build_copy(Info->Context), Stmt, VMap, LTS);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000966
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000967 BlockGenerator::generate(Builder, *Stmt, VMap, LTS, P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000968
969 isl_ast_node_free(User);
970 isl_id_free(Annotation);
971 isl_id_free(Id);
972}
973
974void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
975 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
976
977 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
978 create(isl_ast_node_list_get_ast_node(List, i));
979
980 isl_ast_node_free(Block);
981 isl_ast_node_list_free(List);
982}
983
984void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
985 switch (isl_ast_node_get_type(Node)) {
986 case isl_ast_node_error:
987 llvm_unreachable("code generation error");
988 case isl_ast_node_for:
989 createFor(Node);
990 return;
991 case isl_ast_node_if:
992 createIf(Node);
993 return;
994 case isl_ast_node_user:
995 createUser(Node);
996 return;
997 case isl_ast_node_block:
998 createBlock(Node);
999 return;
1000 }
1001
1002 llvm_unreachable("Unknown isl_ast_node type");
1003}
1004
1005void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
1006 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
1007
1008 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
1009 isl_id *Id;
1010 const SCEV *Scev;
1011 IntegerType *T;
1012 Instruction *InsertLocation;
1013
1014 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserc14582f2013-02-05 18:01:29 +00001015 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001016 T = dyn_cast<IntegerType>(Scev->getType());
1017 InsertLocation = --(Builder.GetInsertBlock()->end());
1018 Value *V = Rewriter.expandCodeFor(Scev, T, InsertLocation);
1019 IDToValue[Id] = V;
1020
1021 isl_id_free(Id);
1022 }
1023
1024 isl_set_free(Context);
1025}
1026
1027namespace {
1028class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001029public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001030 static char ID;
1031
1032 IslCodeGeneration() : ScopPass(ID) {}
1033
1034 bool runOnScop(Scop &S) {
1035 IslAstInfo &AstInfo = getAnalysis<IslAstInfo>();
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001036
Tobias Grossere602a072013-05-07 07:30:56 +00001037 assert(!S.getRegion().isTopLevelRegion() &&
1038 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001039
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001040 simplifyRegion(&S, this);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001041
1042 BasicBlock *StartBlock = executeScopConditionally(S, this);
1043 isl_ast_node *Ast = AstInfo.getAst();
Tobias Grosser37c9b8e2014-03-04 14:59:00 +00001044 LoopAnnotator Annotator;
1045 PollyIRBuilder Builder(StartBlock->getContext(), llvm::ConstantFolder(),
1046 polly::IRInserter(Annotator));
1047 Builder.SetInsertPoint(StartBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001048
Tobias Grosser37c9b8e2014-03-04 14:59:00 +00001049 IslNodeBuilder NodeBuilder(Builder, Annotator, this);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +00001050
1051 // Build condition that evaluates at run-time if all assumptions taken
1052 // for the scop hold. If we detect some assumptions do not hold, the
1053 // original code is executed.
1054 Value *V = NodeBuilder.getExprBuilder().create(AstInfo.getRunCondition());
1055 Value *Zero = ConstantInt::get(V->getType(), 0);
1056 V = Builder.CreateICmp(CmpInst::ICMP_NE, Zero, V);
1057 BasicBlock *PrevBB = StartBlock->getUniquePredecessor();
1058 BranchInst *Branch = dyn_cast<BranchInst>(PrevBB->getTerminator());
1059 Branch->setCondition(V);
1060
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001061 NodeBuilder.addParameters(S.getContext());
1062 NodeBuilder.create(Ast);
1063 return true;
1064 }
1065
Tobias Grosserc14582f2013-02-05 18:01:29 +00001066 virtual void printScop(raw_ostream &OS) const {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001067
1068 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +00001069 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001070 AU.addRequired<IslAstInfo>();
1071 AU.addRequired<RegionInfo>();
1072 AU.addRequired<ScalarEvolution>();
1073 AU.addRequired<ScopDetection>();
1074 AU.addRequired<ScopInfo>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001075 AU.addRequired<LoopInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001076
1077 AU.addPreserved<Dependences>();
1078
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001079 AU.addPreserved<LoopInfo>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001080 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001081 AU.addPreserved<IslAstInfo>();
1082 AU.addPreserved<ScopDetection>();
1083 AU.addPreserved<ScalarEvolution>();
1084
1085 // FIXME: We do not yet add regions for the newly generated code to the
1086 // region tree.
1087 AU.addPreserved<RegionInfo>();
1088 AU.addPreserved<TempScopInfo>();
1089 AU.addPreserved<ScopInfo>();
1090 AU.addPreservedID(IndependentBlocksID);
1091 }
1092};
1093}
1094
1095char IslCodeGeneration::ID = 1;
1096
Tobias Grosser7242ad92013-02-22 08:07:06 +00001097Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001098
Tobias Grosser7242ad92013-02-22 08:07:06 +00001099INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
1100 "Polly - Create LLVM-IR from SCoPs", false, false);
1101INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +00001102INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001103INITIALIZE_PASS_DEPENDENCY(LoopInfo);
1104INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1105INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1106INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1107INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
1108 "Polly - Create LLVM-IR from SCoPs", false, false)