blob: 6db09258a6299436bc93eed60cda12d63b9eeb6c [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"
Sebastian Pop082cea82012-05-07 16:20:07 +000022
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000023#include "polly/Dependences.h"
24#include "polly/LinkAllPasses.h"
25#include "polly/ScopInfo.h"
26#include "polly/TempScopInfo.h"
27#include "polly/CodeGen/IslAst.h"
28#include "polly/CodeGen/BlockGenerators.h"
Sebastian Pop04c4ce32012-12-18 07:46:13 +000029#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000030#include "polly/CodeGen/LoopGenerators.h"
31#include "polly/CodeGen/Utils.h"
32#include "polly/Support/GICHelper.h"
33
Chandler Carruth535d52c2013-01-02 11:47:44 +000034#include "llvm/IR/Module.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000035#include "llvm/Analysis/LoopInfo.h"
36#include "llvm/Analysis/ScalarEvolutionExpander.h"
37#define DEBUG_TYPE "polly-codegen-isl"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000040#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42
43#include "isl/union_map.h"
44#include "isl/list.h"
45#include "isl/ast.h"
46#include "isl/ast_build.h"
47#include "isl/set.h"
48#include "isl/map.h"
49#include "isl/aff.h"
50
51#include <map>
52
53using namespace polly;
54using namespace llvm;
55
56/// @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:
62 RuntimeDebugBuilder(IRBuilder<> &Builder) : Builder(Builder) {}
63
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:
75 IRBuilder<> &Builder;
76
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 Grosser4d96c8d2013-03-23 01:05:07 +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 Grosser7242ad92013-02-22 08:07:06 +0000142 IslExprBuilder(IRBuilder<> &Builder, std::map<isl_id *, Value *> &IDToValue,
143 Pass *P)
144 : 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:
151 IRBuilder<> &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:
449 llvm_unreachable("Unsupported isl ast expression");
450 case isl_ast_op_max:
451 case isl_ast_op_min:
452 return createOpNAry(Expr);
453 case isl_ast_op_add:
454 case isl_ast_op_sub:
455 case isl_ast_op_mul:
456 case isl_ast_op_div:
457 case isl_ast_op_fdiv_q: // Round towards -infty
458 case isl_ast_op_pdiv_q: // Dividend is non-negative
459 case isl_ast_op_pdiv_r: // Dividend is non-negative
460 return createOpBin(Expr);
461 case isl_ast_op_minus:
462 return createOpUnary(Expr);
463 case isl_ast_op_select:
464 return createOpSelect(Expr);
465 case isl_ast_op_and:
466 case isl_ast_op_or:
467 return createOpBoolean(Expr);
468 case isl_ast_op_eq:
469 case isl_ast_op_le:
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000470 case isl_ast_op_lt:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000471 case isl_ast_op_ge:
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000472 case isl_ast_op_gt:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000473 return createOpICmp(Expr);
474 }
475
476 llvm_unreachable("Unsupported isl_ast_expr_op kind.");
477}
478
479Value *IslExprBuilder::createId(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000480 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_id &&
481 "Expression not of type isl_ast_expr_ident");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000482
483 isl_id *Id;
484 Value *V;
485
486 Id = isl_ast_expr_get_id(Expr);
487
488 assert(IDToValue.count(Id) && "Identifier not found");
489
490 V = IDToValue[Id];
491
492 isl_id_free(Id);
493 isl_ast_expr_free(Expr);
494
495 return V;
496}
497
498IntegerType *IslExprBuilder::getType(__isl_keep isl_ast_expr *Expr) {
499 // XXX: We assume i64 is large enough. This is often true, but in general
500 // incorrect. Also, on 32bit architectures, it would be beneficial to
501 // use a smaller type. We can and should directly derive this information
502 // during code generation.
503 return IntegerType::get(Builder.getContext(), 64);
504}
505
506Value *IslExprBuilder::createInt(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000507 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_int &&
508 "Expression not of type isl_ast_expr_int");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000509 isl_int Int;
510 Value *V;
511 APInt APValue;
512 IntegerType *T;
513
514 isl_int_init(Int);
515 isl_ast_expr_get_int(Expr, &Int);
516 APValue = APInt_from_MPZ(Int);
517 T = getType(Expr);
518 APValue = APValue.sextOrSelf(T->getBitWidth());
519 V = ConstantInt::get(T, APValue);
520
521 isl_ast_expr_free(Expr);
522 isl_int_clear(Int);
523 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 Grosser7242ad92013-02-22 08:07:06 +0000543 IslNodeBuilder(IRBuilder<> &Builder, Pass *P)
544 : Builder(Builder), ExprBuilder(Builder, IDToValue, P), P(P) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000545
546 void addParameters(__isl_take isl_set *Context);
547 void create(__isl_take isl_ast_node *Node);
548
549private:
550 IRBuilder<> &Builder;
551 IslExprBuilder ExprBuilder;
552 Pass *P;
553
554 // This maps an isl_id* to the Value* it has in the generated program. For now
555 // on, the only isl_ids that are stored here are the newly calculated loop
556 // ivs.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000557 std::map<isl_id *, Value *> IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000558
559 // Extract the upper bound of this loop
560 //
561 // The isl code generation can generate arbitrary expressions to check if the
562 // upper bound of a loop is reached, but it provides an option to enforce
563 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
564 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
565 //
566 // This function extracts 'atomic' upper bounds. Polly, in general, requires
567 // atomic upper bounds for the following reasons:
568 //
569 // 1. An atomic upper bound is loop invariant
570 //
571 // It must not be calculated at each loop iteration and can often even be
572 // hoisted out further by the loop invariant code motion.
573 //
574 // 2. OpenMP needs a loop invarient upper bound to calculate the number
575 // of loop iterations.
576 //
577 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000578 __isl_give isl_ast_expr *
579 getUpperBound(__isl_keep isl_ast_node *For, CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000580
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000581 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
582
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000583 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000584 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
585 void createForSequential(__isl_take isl_ast_node *For);
586 void createSubstitutions(__isl_take isl_pw_multi_aff *PMA,
Tobias Grosserc14582f2013-02-05 18:01:29 +0000587 __isl_take isl_ast_build *Context, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000588 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000589 void createSubstitutionsVector(
590 __isl_take isl_pw_multi_aff *PMA, __isl_take isl_ast_build *Context,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000591 ScopStmt *Stmt, VectorValueMapT &VMap, std::vector<LoopToScevMapT> &VLTS,
592 std::vector<Value *> &IVS, __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000593 void createIf(__isl_take isl_ast_node *If);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000594 void createUserVector(
595 __isl_take isl_ast_node *User, std::vector<Value *> &IVS,
596 __isl_take isl_id *IteratorID, __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000597 void createUser(__isl_take isl_ast_node *User);
598 void createBlock(__isl_take isl_ast_node *Block);
599};
600
601__isl_give isl_ast_expr *IslNodeBuilder::getUpperBound(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000602 __isl_keep isl_ast_node *For, ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000603 isl_id *UBID, *IteratorID;
604 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000605 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000606
607 Cond = isl_ast_node_for_get_cond(For);
608 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000609 Type = isl_ast_expr_get_op_type(Cond);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000610
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000611 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
612 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000613
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000614 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000615 case isl_ast_op_le:
616 Predicate = ICmpInst::ICMP_SLE;
617 break;
618 case isl_ast_op_lt:
619 Predicate = ICmpInst::ICMP_SLT;
620 break;
621 default:
622 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000623 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000624
625 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
626
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000627 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
628 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000629
630 UBID = isl_ast_expr_get_id(Arg0);
631
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000632 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
633 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000634
635 IteratorID = isl_ast_expr_get_id(Iterator);
636
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000637 assert(UBID == IteratorID &&
638 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000639
640 UB = isl_ast_expr_get_op_arg(Cond, 1);
641
642 isl_ast_expr_free(Cond);
643 isl_ast_expr_free(Iterator);
644 isl_ast_expr_free(Arg0);
645 isl_id_free(IteratorID);
646 isl_id_free(UBID);
647
648 return UB;
649}
650
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000651unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
652 isl_id *Annotation = isl_ast_node_get_annotation(For);
653 if (!Annotation)
654 return -1;
655
Tobias Grosserc14582f2013-02-05 18:01:29 +0000656 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000657 if (!Info) {
658 isl_id_free(Annotation);
659 return -1;
660 }
661
662 isl_union_map *Schedule = isl_ast_build_get_schedule(Info->Context);
663 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
664 isl_id_free(Annotation);
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000665 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
666 if (NumberOfIterations == -1)
667 return -1;
668 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000669}
670
Tobias Grosserc14582f2013-02-05 18:01:29 +0000671void IslNodeBuilder::createUserVector(
672 __isl_take isl_ast_node *User, std::vector<Value *> &IVS,
673 __isl_take isl_id *IteratorID, __isl_take isl_union_map *Schedule) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000674 isl_id *Annotation = isl_ast_node_get_annotation(User);
675 assert(Annotation && "Vector user statement is not annotated");
676
Tobias Grosserc14582f2013-02-05 18:01:29 +0000677 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000678 assert(Info && "Vector user statement annotation does not contain info");
679
680 isl_id *Id = isl_pw_multi_aff_get_tuple_id(Info->PMA, isl_dim_out);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000681 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000682 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000683 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000684
685 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
686 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
687 isl_map *S = isl_map_from_union_map(Schedule);
688
689 createSubstitutionsVector(isl_pw_multi_aff_copy(Info->PMA),
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000690 isl_ast_build_copy(Info->Context), Stmt, VectorMap,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000691 VLTS, IVS, IteratorID);
692 VectorBlockGenerator::generate(Builder, *Stmt, VectorMap, VLTS, S, P);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000693
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000694 isl_map_free(S);
695 isl_id_free(Annotation);
696 isl_id_free(Id);
697 isl_ast_node_free(User);
698}
699
700void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
701 int VectorWidth) {
702 isl_ast_node *Body = isl_ast_node_for_get_body(For);
703 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
704 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
705 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
706 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
707 CmpInst::Predicate Predicate;
708 isl_ast_expr *UB = getUpperBound(For, Predicate);
709
710 Value *ValueLB = ExprBuilder.create(Init);
711 Value *ValueUB = ExprBuilder.create(UB);
712 Value *ValueInc = ExprBuilder.create(Inc);
713
714 Type *MaxType = ExprBuilder.getType(Iterator);
715 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
716 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
717 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
718
719 if (MaxType != ValueLB->getType())
720 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
721 if (MaxType != ValueUB->getType())
722 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
723 if (MaxType != ValueInc->getType())
724 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
725
Tobias Grosserc14582f2013-02-05 18:01:29 +0000726 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000727 IVS[0] = ValueLB;
728
729 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000730 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000731
732 isl_id *Annotation = isl_ast_node_get_annotation(For);
733 assert(Annotation && "For statement is not annotated");
734
Tobias Grosserc14582f2013-02-05 18:01:29 +0000735 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000736 assert(Info && "For statement annotation does not contain info");
737
738 isl_union_map *Schedule = isl_ast_build_get_schedule(Info->Context);
739 assert(Schedule && "For statement annotation does not contain its schedule");
740
741 IDToValue[IteratorID] = ValueLB;
742
743 switch (isl_ast_node_get_type(Body)) {
744 case isl_ast_node_user:
745 createUserVector(Body, IVS, isl_id_copy(IteratorID),
746 isl_union_map_copy(Schedule));
747 break;
748 case isl_ast_node_block: {
749 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
750
751 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
752 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000753 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000754
755 isl_ast_node_free(Body);
756 isl_ast_node_list_free(List);
757 break;
758 }
759 default:
760 isl_ast_node_dump(Body);
761 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
762 }
763
764 IDToValue.erase(IteratorID);
765 isl_id_free(IteratorID);
766 isl_id_free(Annotation);
767 isl_union_map_free(Schedule);
768
769 isl_ast_node_free(For);
770 isl_ast_expr_free(Iterator);
771}
772
773void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000774 isl_ast_node *Body;
775 isl_ast_expr *Init, *Inc, *Iterator, *UB;
776 isl_id *IteratorID;
777 Value *ValueLB, *ValueUB, *ValueInc;
778 Type *MaxType;
779 BasicBlock *AfterBlock;
780 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000781 CmpInst::Predicate Predicate;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000782
783 Body = isl_ast_node_for_get_body(For);
784
785 // isl_ast_node_for_is_degenerate(For)
786 //
787 // TODO: For degenerated loops we could generate a plain assignment.
788 // However, for now we just reuse the logic for normal loops, which will
789 // create a loop with a single iteration.
790
791 Init = isl_ast_node_for_get_init(For);
792 Inc = isl_ast_node_for_get_inc(For);
793 Iterator = isl_ast_node_for_get_iterator(For);
794 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000795 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000796
797 ValueLB = ExprBuilder.create(Init);
798 ValueUB = ExprBuilder.create(UB);
799 ValueInc = ExprBuilder.create(Inc);
800
801 MaxType = ExprBuilder.getType(Iterator);
802 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
803 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
804 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
805
806 if (MaxType != ValueLB->getType())
807 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
808 if (MaxType != ValueUB->getType())
809 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
810 if (MaxType != ValueInc->getType())
811 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
812
813 // TODO: In case we can proof a loop is executed at least once, we can
814 // generate the condition iv != UB + stride (consider possible
815 // overflow). This condition will allow LLVM to prove the loop is
816 // executed at least once, which will enable a lot of loop invariant
817 // code motion.
818
Tobias Grosserc14582f2013-02-05 18:01:29 +0000819 IV =
820 createLoop(ValueLB, ValueUB, ValueInc, Builder, P, AfterBlock, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000821 IDToValue[IteratorID] = IV;
822
823 create(Body);
824
825 IDToValue.erase(IteratorID);
826
827 Builder.SetInsertPoint(AfterBlock->begin());
828
829 isl_ast_node_free(For);
830 isl_ast_expr_free(Iterator);
831 isl_id_free(IteratorID);
832}
833
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000834void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
835 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
836
837 if (Vector && isInnermostParallel(For)) {
838 int VectorWidth = getNumberOfIterations(For);
839 if (1 < VectorWidth && VectorWidth <= 16) {
840 createForVector(For, VectorWidth);
841 return;
842 }
843 }
844 createForSequential(For);
845}
846
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000847void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
848 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
849
850 Function *F = Builder.GetInsertBlock()->getParent();
851 LLVMContext &Context = F->getContext();
852
Tobias Grosserc14582f2013-02-05 18:01:29 +0000853 BasicBlock *CondBB =
854 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000855 CondBB->setName("polly.cond");
856 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
857 MergeBB->setName("polly.merge");
858 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
859 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
860
861 DominatorTree &DT = P->getAnalysis<DominatorTree>();
862 DT.addNewBlock(ThenBB, CondBB);
863 DT.addNewBlock(ElseBB, CondBB);
864 DT.changeImmediateDominator(MergeBB, CondBB);
865
866 CondBB->getTerminator()->eraseFromParent();
867
868 Builder.SetInsertPoint(CondBB);
869 Value *Predicate = ExprBuilder.create(Cond);
870 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
871 Builder.SetInsertPoint(ThenBB);
872 Builder.CreateBr(MergeBB);
873 Builder.SetInsertPoint(ElseBB);
874 Builder.CreateBr(MergeBB);
875 Builder.SetInsertPoint(ThenBB->begin());
876
877 create(isl_ast_node_if_get_then(If));
878
879 Builder.SetInsertPoint(ElseBB->begin());
880
881 if (isl_ast_node_if_has_else(If))
882 create(isl_ast_node_if_get_else(If));
883
884 Builder.SetInsertPoint(MergeBB->begin());
885
886 isl_ast_node_free(If);
887}
888
Tobias Grosser7242ad92013-02-22 08:07:06 +0000889void IslNodeBuilder::createSubstitutions(
890 __isl_take isl_pw_multi_aff *PMA, __isl_take isl_ast_build *Context,
891 ScopStmt *Stmt, ValueMapT &VMap, LoopToScevMapT &LTS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000892 for (unsigned i = 0; i < isl_pw_multi_aff_dim(PMA, isl_dim_out); ++i) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000893 isl_pw_aff *Aff;
894 isl_ast_expr *Expr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000895 Value *V;
896
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000897 Aff = isl_pw_multi_aff_get_pw_aff(PMA, i);
898 Expr = isl_ast_build_expr_from_pw_aff(Context, Aff);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000899 V = ExprBuilder.create(Expr);
900
Sebastian Pope039bb12013-03-18 19:09:49 +0000901 ScalarEvolution *SE = Stmt->getParent()->getSE();
902 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
903
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000904 // CreateIntCast can introduce trunc expressions. This is correct, as the
905 // result will always fit into the type of the original induction variable
906 // (because we calculate a value of the original induction variable).
Sebastian Pope039bb12013-03-18 19:09:49 +0000907 const Value *OldIV = Stmt->getInductionVariableForDimension(i);
908 if (OldIV) {
909 V = Builder.CreateIntCast(V, OldIV->getType(), true);
910 VMap[OldIV] = V;
911 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000912 }
913
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000914 isl_pw_multi_aff_free(PMA);
915 isl_ast_build_free(Context);
916}
917
Tobias Grosserc14582f2013-02-05 18:01:29 +0000918void IslNodeBuilder::createSubstitutionsVector(
919 __isl_take isl_pw_multi_aff *PMA, __isl_take isl_ast_build *Context,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000920 ScopStmt *Stmt, VectorValueMapT &VMap, std::vector<LoopToScevMapT> &VLTS,
921 std::vector<Value *> &IVS, __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000922 int i = 0;
923
924 Value *OldValue = IDToValue[IteratorID];
Tobias Grosserc14582f2013-02-05 18:01:29 +0000925 for (std::vector<Value *>::iterator II = IVS.begin(), IE = IVS.end();
926 II != IE; ++II) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000927 IDToValue[IteratorID] = *II;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000928 createSubstitutions(isl_pw_multi_aff_copy(PMA), isl_ast_build_copy(Context),
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000929 Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000930 i++;
931 }
932
933 IDToValue[IteratorID] = OldValue;
934 isl_id_free(IteratorID);
935 isl_pw_multi_aff_free(PMA);
936 isl_ast_build_free(Context);
937}
938
939void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
940 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000941 LoopToScevMapT LTS;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000942 struct IslAstUser *Info;
943 isl_id *Annotation, *Id;
944 ScopStmt *Stmt;
945
946 Annotation = isl_ast_node_get_annotation(User);
947 assert(Annotation && "Scalar user statement is not annotated");
948
Tobias Grosserc14582f2013-02-05 18:01:29 +0000949 Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000950 assert(Info && "Scalar user statement annotation does not contain info");
951
952 Id = isl_pw_multi_aff_get_tuple_id(Info->PMA, isl_dim_out);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000953 Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000954
955 createSubstitutions(isl_pw_multi_aff_copy(Info->PMA),
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000956 isl_ast_build_copy(Info->Context), Stmt, VMap, LTS);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000957
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000958 BlockGenerator::generate(Builder, *Stmt, VMap, LTS, P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000959
960 isl_ast_node_free(User);
961 isl_id_free(Annotation);
962 isl_id_free(Id);
963}
964
965void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
966 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
967
968 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
969 create(isl_ast_node_list_get_ast_node(List, i));
970
971 isl_ast_node_free(Block);
972 isl_ast_node_list_free(List);
973}
974
975void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
976 switch (isl_ast_node_get_type(Node)) {
977 case isl_ast_node_error:
978 llvm_unreachable("code generation error");
979 case isl_ast_node_for:
980 createFor(Node);
981 return;
982 case isl_ast_node_if:
983 createIf(Node);
984 return;
985 case isl_ast_node_user:
986 createUser(Node);
987 return;
988 case isl_ast_node_block:
989 createBlock(Node);
990 return;
991 }
992
993 llvm_unreachable("Unknown isl_ast_node type");
994}
995
996void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
997 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
998
999 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
1000 isl_id *Id;
1001 const SCEV *Scev;
1002 IntegerType *T;
1003 Instruction *InsertLocation;
1004
1005 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserc14582f2013-02-05 18:01:29 +00001006 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001007 T = dyn_cast<IntegerType>(Scev->getType());
1008 InsertLocation = --(Builder.GetInsertBlock()->end());
1009 Value *V = Rewriter.expandCodeFor(Scev, T, InsertLocation);
1010 IDToValue[Id] = V;
1011
1012 isl_id_free(Id);
1013 }
1014
1015 isl_set_free(Context);
1016}
1017
1018namespace {
1019class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001020public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001021 static char ID;
1022
1023 IslCodeGeneration() : ScopPass(ID) {}
1024
1025 bool runOnScop(Scop &S) {
1026 IslAstInfo &AstInfo = getAnalysis<IslAstInfo>();
1027 assert(S.getRegion().isSimple() && "Only simple regions are supported");
1028
1029 BasicBlock *StartBlock = executeScopConditionally(S, this);
1030 isl_ast_node *Ast = AstInfo.getAst();
1031 IRBuilder<> Builder(StartBlock->begin());
1032
1033 IslNodeBuilder NodeBuilder(Builder, this);
1034 NodeBuilder.addParameters(S.getContext());
1035 NodeBuilder.create(Ast);
1036 return true;
1037 }
1038
Tobias Grosserc14582f2013-02-05 18:01:29 +00001039 virtual void printScop(raw_ostream &OS) const {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001040
1041 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1042 AU.addRequired<DominatorTree>();
1043 AU.addRequired<IslAstInfo>();
1044 AU.addRequired<RegionInfo>();
1045 AU.addRequired<ScalarEvolution>();
1046 AU.addRequired<ScopDetection>();
1047 AU.addRequired<ScopInfo>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001048 AU.addRequired<LoopInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001049
1050 AU.addPreserved<Dependences>();
1051
1052 // FIXME: We do not create LoopInfo for the newly generated loops.
1053 AU.addPreserved<LoopInfo>();
1054 AU.addPreserved<DominatorTree>();
1055 AU.addPreserved<IslAstInfo>();
1056 AU.addPreserved<ScopDetection>();
1057 AU.addPreserved<ScalarEvolution>();
1058
1059 // FIXME: We do not yet add regions for the newly generated code to the
1060 // region tree.
1061 AU.addPreserved<RegionInfo>();
1062 AU.addPreserved<TempScopInfo>();
1063 AU.addPreserved<ScopInfo>();
1064 AU.addPreservedID(IndependentBlocksID);
1065 }
1066};
1067}
1068
1069char IslCodeGeneration::ID = 1;
1070
Tobias Grosser7242ad92013-02-22 08:07:06 +00001071Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001072
Tobias Grosser7242ad92013-02-22 08:07:06 +00001073INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
1074 "Polly - Create LLVM-IR from SCoPs", false, false);
1075INITIALIZE_PASS_DEPENDENCY(Dependences);
1076INITIALIZE_PASS_DEPENDENCY(DominatorTree);
1077INITIALIZE_PASS_DEPENDENCY(LoopInfo);
1078INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1079INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1080INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1081INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
1082 "Polly - Create LLVM-IR from SCoPs", false, false)