blob: e3617d9b67bcd7a8ce4e08d2bb54a4aa7b2e556d [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"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000033#include "polly/Support/ScopHelper.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000034
Chandler Carruth535d52c2013-01-02 11:47:44 +000035#include "llvm/IR/Module.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000036#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Analysis/ScalarEvolutionExpander.h"
38#define DEBUG_TYPE "polly-codegen-isl"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000041#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43
44#include "isl/union_map.h"
45#include "isl/list.h"
46#include "isl/ast.h"
47#include "isl/ast_build.h"
48#include "isl/set.h"
49#include "isl/map.h"
50#include "isl/aff.h"
51
52#include <map>
53
54using namespace polly;
55using namespace llvm;
56
57/// @brief Insert function calls that print certain LLVM values at run time.
58///
59/// This class inserts libc function calls to print certain LLVM values at
60/// run time.
61class RuntimeDebugBuilder {
62public:
63 RuntimeDebugBuilder(IRBuilder<> &Builder) : Builder(Builder) {}
64
65 /// @brief Print a string to stdout.
66 ///
67 /// @param String The string to print.
68 void createStrPrinter(std::string String);
69
70 /// @brief Print an integer value to stdout.
71 ///
72 /// @param V The value to print.
73 void createIntPrinter(Value *V);
74
75private:
76 IRBuilder<> &Builder;
77
78 /// @brief Add a call to the fflush function with no file pointer given.
79 ///
80 /// This call will flush all opened file pointers including stdout and stderr.
81 void createFlush();
82
83 /// @brief Get a reference to the 'printf' function.
84 ///
85 /// If the current module does not yet contain a reference to printf, we
86 /// insert a reference to it. Otherwise the existing reference is returned.
87 Function *getPrintF();
88};
89
90Function *RuntimeDebugBuilder::getPrintF() {
91 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
92 const char *Name = "printf";
93 Function *F = M->getFunction(Name);
94
95 if (!F) {
96 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosserc14582f2013-02-05 18:01:29 +000097 FunctionType *Ty =
98 FunctionType::get(Builder.getInt32Ty(), Builder.getInt8PtrTy(), true);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000099 F = Function::Create(Ty, Linkage, Name, M);
100 }
101
102 return F;
103}
104
105void RuntimeDebugBuilder::createFlush() {
106 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
107 const char *Name = "fflush";
108 Function *F = M->getFunction(Name);
109
110 if (!F) {
111 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000112 FunctionType *Ty =
113 FunctionType::get(Builder.getInt32Ty(), Builder.getInt8PtrTy(), false);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000114 F = Function::Create(Ty, Linkage, Name, M);
115 }
116
117 Builder.CreateCall(F, Constant::getNullValue(Builder.getInt8PtrTy()));
118}
119
120void RuntimeDebugBuilder::createStrPrinter(std::string String) {
121 Function *F = getPrintF();
122 Value *StringValue = Builder.CreateGlobalStringPtr(String);
123 Builder.CreateCall(F, StringValue);
124
125 createFlush();
126}
127
128void RuntimeDebugBuilder::createIntPrinter(Value *V) {
129 IntegerType *Ty = dyn_cast<IntegerType>(V->getType());
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000130 (void) Ty;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000131 assert(Ty && Ty->getBitWidth() == 64 &&
132 "Cannot insert printer for this type.");
133
134 Function *F = getPrintF();
135 Value *String = Builder.CreateGlobalStringPtr("%ld");
136 Builder.CreateCall2(F, String, V);
137 createFlush();
138}
139
140/// @brief Calculate the Value of a certain isl_ast_expr
141class IslExprBuilder {
142public:
Tobias Grosser7242ad92013-02-22 08:07:06 +0000143 IslExprBuilder(IRBuilder<> &Builder, std::map<isl_id *, Value *> &IDToValue,
144 Pass *P)
145 : Builder(Builder), IDToValue(IDToValue) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000146
147 Value *create(__isl_take isl_ast_expr *Expr);
148 Type *getWidestType(Type *T1, Type *T2);
149 IntegerType *getType(__isl_keep isl_ast_expr *Expr);
150
151private:
152 IRBuilder<> &Builder;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000153 std::map<isl_id *, Value *> &IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000154
155 Value *createOp(__isl_take isl_ast_expr *Expr);
156 Value *createOpUnary(__isl_take isl_ast_expr *Expr);
157 Value *createOpBin(__isl_take isl_ast_expr *Expr);
158 Value *createOpNAry(__isl_take isl_ast_expr *Expr);
159 Value *createOpSelect(__isl_take isl_ast_expr *Expr);
160 Value *createOpICmp(__isl_take isl_ast_expr *Expr);
161 Value *createOpBoolean(__isl_take isl_ast_expr *Expr);
162 Value *createId(__isl_take isl_ast_expr *Expr);
163 Value *createInt(__isl_take isl_ast_expr *Expr);
164};
165
166Type *IslExprBuilder::getWidestType(Type *T1, Type *T2) {
167 assert(isa<IntegerType>(T1) && isa<IntegerType>(T2));
168
169 if (T1->getPrimitiveSizeInBits() < T2->getPrimitiveSizeInBits())
170 return T2;
171 else
172 return T1;
173}
174
175Value *IslExprBuilder::createOpUnary(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000176 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_minus &&
177 "Unsupported unary operation");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000178
179 Value *V;
180 Type *MaxType = getType(Expr);
181
182 V = create(isl_ast_expr_get_op_arg(Expr, 0));
183 MaxType = getWidestType(MaxType, V->getType());
184
185 if (MaxType != V->getType())
186 V = Builder.CreateSExt(V, MaxType);
187
188 isl_ast_expr_free(Expr);
189 return Builder.CreateNSWNeg(V);
190}
191
192Value *IslExprBuilder::createOpNAry(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000193 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
194 "isl ast expression not of type isl_ast_op");
195 assert(isl_ast_expr_get_op_n_arg(Expr) >= 2 &&
196 "We need at least two operands in an n-ary operation");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000197
198 Value *V;
199
200 V = create(isl_ast_expr_get_op_arg(Expr, 0));
201
202 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr); ++i) {
203 Value *OpV;
204 OpV = create(isl_ast_expr_get_op_arg(Expr, i));
205
206 Type *Ty = getWidestType(V->getType(), OpV->getType());
207
208 if (Ty != OpV->getType())
209 OpV = Builder.CreateSExt(OpV, Ty);
210
211 if (Ty != V->getType())
212 V = Builder.CreateSExt(V, Ty);
213
214 switch (isl_ast_expr_get_op_type(Expr)) {
215 default:
216 llvm_unreachable("This is no n-ary isl ast expression");
217
Tobias Grosserc14582f2013-02-05 18:01:29 +0000218 case isl_ast_op_max: {
219 Value *Cmp = Builder.CreateICmpSGT(V, OpV);
220 V = Builder.CreateSelect(Cmp, V, OpV);
221 continue;
222 }
223 case isl_ast_op_min: {
224 Value *Cmp = Builder.CreateICmpSLT(V, OpV);
225 V = Builder.CreateSelect(Cmp, V, OpV);
226 continue;
227 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000228 }
229 }
230
231 // TODO: We can truncate the result, if it fits into a smaller type. This can
232 // help in cases where we have larger operands (e.g. i67) but the result is
233 // known to fit into i64. Without the truncation, the larger i67 type may
234 // force all subsequent operations to be performed on a non-native type.
235 isl_ast_expr_free(Expr);
236 return V;
237}
238
239Value *IslExprBuilder::createOpBin(__isl_take isl_ast_expr *Expr) {
240 Value *LHS, *RHS, *Res;
241 Type *MaxType;
242 isl_ast_op_type OpType;
243
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000244 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
245 "isl ast expression not of type isl_ast_op");
246 assert(isl_ast_expr_get_op_n_arg(Expr) == 2 &&
247 "not a binary isl ast expression");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000248
249 OpType = isl_ast_expr_get_op_type(Expr);
250
251 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
252 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
253
254 MaxType = LHS->getType();
255 MaxType = getWidestType(MaxType, RHS->getType());
256
257 // Take the result into account when calculating the widest type.
258 //
259 // For operations such as '+' the result may require a type larger than
260 // the type of the individual operands. For other operations such as '/', the
261 // result type cannot be larger than the type of the individual operand. isl
262 // does not calculate correct types for these operations and we consequently
263 // exclude those operations here.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000264 switch (OpType) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000265 case isl_ast_op_pdiv_q:
266 case isl_ast_op_pdiv_r:
267 case isl_ast_op_div:
268 case isl_ast_op_fdiv_q:
269 // Do nothing
270 break;
271 case isl_ast_op_add:
272 case isl_ast_op_sub:
273 case isl_ast_op_mul:
274 MaxType = getWidestType(MaxType, getType(Expr));
275 break;
276 default:
277 llvm_unreachable("This is no binary isl ast expression");
278 }
279
280 if (MaxType != RHS->getType())
281 RHS = Builder.CreateSExt(RHS, MaxType);
282
283 if (MaxType != LHS->getType())
284 LHS = Builder.CreateSExt(LHS, MaxType);
285
286 switch (OpType) {
287 default:
288 llvm_unreachable("This is no binary isl ast expression");
289 case isl_ast_op_add:
290 Res = Builder.CreateNSWAdd(LHS, RHS);
291 break;
292 case isl_ast_op_sub:
293 Res = Builder.CreateNSWSub(LHS, RHS);
294 break;
295 case isl_ast_op_mul:
296 Res = Builder.CreateNSWMul(LHS, RHS);
297 break;
298 case isl_ast_op_div:
299 case isl_ast_op_pdiv_q: // Dividend is non-negative
300 Res = Builder.CreateSDiv(LHS, RHS);
301 break;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000302 case isl_ast_op_fdiv_q: { // Round towards -infty
303 // TODO: Review code and check that this calculation does not yield
304 // incorrect overflow in some bordercases.
305 //
306 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
307 Value *One = ConstantInt::get(MaxType, 1);
308 Value *Zero = ConstantInt::get(MaxType, 0);
309 Value *Sum1 = Builder.CreateSub(LHS, RHS);
310 Value *Sum2 = Builder.CreateAdd(Sum1, One);
311 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
312 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
313 Res = Builder.CreateSDiv(Dividend, RHS);
314 break;
315 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000316 case isl_ast_op_pdiv_r: // Dividend is non-negative
317 Res = Builder.CreateSRem(LHS, RHS);
318 break;
319 }
320
321 // TODO: We can truncate the result, if it fits into a smaller type. This can
322 // help in cases where we have larger operands (e.g. i67) but the result is
323 // known to fit into i64. Without the truncation, the larger i67 type may
324 // force all subsequent operations to be performed on a non-native type.
325 isl_ast_expr_free(Expr);
326 return Res;
327}
328
329Value *IslExprBuilder::createOpSelect(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000330 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_select &&
331 "Unsupported unary isl ast expression");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000332 Value *LHS, *RHS, *Cond;
333 Type *MaxType = getType(Expr);
334
335 Cond = create(isl_ast_expr_get_op_arg(Expr, 0));
336
337 LHS = create(isl_ast_expr_get_op_arg(Expr, 1));
338 RHS = create(isl_ast_expr_get_op_arg(Expr, 2));
339
340 MaxType = getWidestType(MaxType, LHS->getType());
341 MaxType = getWidestType(MaxType, RHS->getType());
342
343 if (MaxType != RHS->getType())
344 RHS = Builder.CreateSExt(RHS, MaxType);
345
346 if (MaxType != LHS->getType())
347 LHS = Builder.CreateSExt(LHS, MaxType);
348
349 // TODO: Do we want to truncate the result?
350 isl_ast_expr_free(Expr);
351 return Builder.CreateSelect(Cond, LHS, RHS);
352}
353
354Value *IslExprBuilder::createOpICmp(__isl_take isl_ast_expr *Expr) {
355 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
356 "Expected an isl_ast_expr_op expression");
357
358 Value *LHS, *RHS, *Res;
359
360 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
361 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
362
363 Type *MaxType = LHS->getType();
364 MaxType = getWidestType(MaxType, RHS->getType());
365
366 if (MaxType != RHS->getType())
367 RHS = Builder.CreateSExt(RHS, MaxType);
368
369 if (MaxType != LHS->getType())
370 LHS = Builder.CreateSExt(LHS, MaxType);
371
372 switch (isl_ast_expr_get_op_type(Expr)) {
373 default:
374 llvm_unreachable("Unsupported ICmp isl ast expression");
375 case isl_ast_op_eq:
376 Res = Builder.CreateICmpEQ(LHS, RHS);
377 break;
378 case isl_ast_op_le:
379 Res = Builder.CreateICmpSLE(LHS, RHS);
380 break;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000381 case isl_ast_op_lt:
382 Res = Builder.CreateICmpSLT(LHS, RHS);
383 break;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000384 case isl_ast_op_ge:
385 Res = Builder.CreateICmpSGE(LHS, RHS);
386 break;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000387 case isl_ast_op_gt:
388 Res = Builder.CreateICmpSGT(LHS, RHS);
389 break;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000390 }
391
392 isl_ast_expr_free(Expr);
393 return Res;
394}
395
396Value *IslExprBuilder::createOpBoolean(__isl_take isl_ast_expr *Expr) {
397 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
398 "Expected an isl_ast_expr_op expression");
399
400 Value *LHS, *RHS, *Res;
401 isl_ast_op_type OpType;
402
403 OpType = isl_ast_expr_get_op_type(Expr);
404
405 assert((OpType == isl_ast_op_and || OpType == isl_ast_op_or) &&
406 "Unsupported isl_ast_op_type");
407
408 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
409 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
410
411 // Even though the isl pretty printer prints the expressions as 'exp && exp'
412 // or 'exp || exp', we actually code generate the bitwise expressions
413 // 'exp & exp' or 'exp | exp'. This forces the evaluation of both branches,
414 // but it is, due to the use of i1 types, otherwise equivalent. The reason
415 // to go for bitwise operations is, that we assume the reduced control flow
416 // will outweight the overhead introduced by evaluating unneeded expressions.
417 // The isl code generation currently does not take advantage of the fact that
418 // the expression after an '||' or '&&' is in some cases not evaluated.
419 // Evaluating it anyways does not cause any undefined behaviour.
420 //
421 // TODO: Document in isl itself, that the unconditionally evaluating the
422 // second part of '||' or '&&' expressions is safe.
423 assert(LHS->getType() == Builder.getInt1Ty() && "Expected i1 type");
424 assert(RHS->getType() == Builder.getInt1Ty() && "Expected i1 type");
425
426 switch (OpType) {
427 default:
428 llvm_unreachable("Unsupported boolean expression");
429 case isl_ast_op_and:
430 Res = Builder.CreateAnd(LHS, RHS);
431 break;
432 case isl_ast_op_or:
433 Res = Builder.CreateOr(LHS, RHS);
434 break;
435 }
436
437 isl_ast_expr_free(Expr);
438 return Res;
439}
440
441Value *IslExprBuilder::createOp(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000442 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
443 "Expression not of type isl_ast_expr_op");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000444 switch (isl_ast_expr_get_op_type(Expr)) {
445 case isl_ast_op_error:
446 case isl_ast_op_cond:
447 case isl_ast_op_and_then:
448 case isl_ast_op_or_else:
449 case isl_ast_op_call:
450 llvm_unreachable("Unsupported isl ast expression");
451 case isl_ast_op_max:
452 case isl_ast_op_min:
453 return createOpNAry(Expr);
454 case isl_ast_op_add:
455 case isl_ast_op_sub:
456 case isl_ast_op_mul:
457 case isl_ast_op_div:
458 case isl_ast_op_fdiv_q: // Round towards -infty
459 case isl_ast_op_pdiv_q: // Dividend is non-negative
460 case isl_ast_op_pdiv_r: // Dividend is non-negative
461 return createOpBin(Expr);
462 case isl_ast_op_minus:
463 return createOpUnary(Expr);
464 case isl_ast_op_select:
465 return createOpSelect(Expr);
466 case isl_ast_op_and:
467 case isl_ast_op_or:
468 return createOpBoolean(Expr);
469 case isl_ast_op_eq:
470 case isl_ast_op_le:
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000471 case isl_ast_op_lt:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000472 case isl_ast_op_ge:
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000473 case isl_ast_op_gt:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000474 return createOpICmp(Expr);
475 }
476
477 llvm_unreachable("Unsupported isl_ast_expr_op kind.");
478}
479
480Value *IslExprBuilder::createId(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000481 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_id &&
482 "Expression not of type isl_ast_expr_ident");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000483
484 isl_id *Id;
485 Value *V;
486
487 Id = isl_ast_expr_get_id(Expr);
488
489 assert(IDToValue.count(Id) && "Identifier not found");
490
491 V = IDToValue[Id];
492
493 isl_id_free(Id);
494 isl_ast_expr_free(Expr);
495
496 return V;
497}
498
499IntegerType *IslExprBuilder::getType(__isl_keep isl_ast_expr *Expr) {
500 // XXX: We assume i64 is large enough. This is often true, but in general
501 // incorrect. Also, on 32bit architectures, it would be beneficial to
502 // use a smaller type. We can and should directly derive this information
503 // during code generation.
504 return IntegerType::get(Builder.getContext(), 64);
505}
506
507Value *IslExprBuilder::createInt(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000508 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_int &&
509 "Expression not of type isl_ast_expr_int");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000510 isl_int Int;
511 Value *V;
512 APInt APValue;
513 IntegerType *T;
514
515 isl_int_init(Int);
516 isl_ast_expr_get_int(Expr, &Int);
517 APValue = APInt_from_MPZ(Int);
518 T = getType(Expr);
519 APValue = APValue.sextOrSelf(T->getBitWidth());
520 V = ConstantInt::get(T, APValue);
521
522 isl_ast_expr_free(Expr);
523 isl_int_clear(Int);
524 return V;
525}
526
527Value *IslExprBuilder::create(__isl_take isl_ast_expr *Expr) {
528 switch (isl_ast_expr_get_type(Expr)) {
529 case isl_ast_expr_error:
530 llvm_unreachable("Code generation error");
531 case isl_ast_expr_op:
532 return createOp(Expr);
533 case isl_ast_expr_id:
534 return createId(Expr);
535 case isl_ast_expr_int:
536 return createInt(Expr);
537 }
538
539 llvm_unreachable("Unexpected enum value");
540}
541
542class IslNodeBuilder {
543public:
Tobias Grosser7242ad92013-02-22 08:07:06 +0000544 IslNodeBuilder(IRBuilder<> &Builder, Pass *P)
545 : Builder(Builder), 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);
549
550private:
551 IRBuilder<> &Builder;
552 IslExprBuilder ExprBuilder;
553 Pass *P;
554
555 // This maps an isl_id* to the Value* it has in the generated program. For now
556 // on, the only isl_ids that are stored here are the newly calculated loop
557 // ivs.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000558 std::map<isl_id *, Value *> IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000559
560 // Extract the upper bound of this loop
561 //
562 // The isl code generation can generate arbitrary expressions to check if the
563 // upper bound of a loop is reached, but it provides an option to enforce
564 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
565 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
566 //
567 // This function extracts 'atomic' upper bounds. Polly, in general, requires
568 // atomic upper bounds for the following reasons:
569 //
570 // 1. An atomic upper bound is loop invariant
571 //
572 // It must not be calculated at each loop iteration and can often even be
573 // hoisted out further by the loop invariant code motion.
574 //
575 // 2. OpenMP needs a loop invarient upper bound to calculate the number
576 // of loop iterations.
577 //
578 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000579 __isl_give isl_ast_expr *
580 getUpperBound(__isl_keep isl_ast_node *For, CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000581
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000582 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
583
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000584 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000585 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
586 void createForSequential(__isl_take isl_ast_node *For);
587 void createSubstitutions(__isl_take isl_pw_multi_aff *PMA,
Tobias Grosserc14582f2013-02-05 18:01:29 +0000588 __isl_take isl_ast_build *Context, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000589 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000590 void createSubstitutionsVector(
591 __isl_take isl_pw_multi_aff *PMA, __isl_take isl_ast_build *Context,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000592 ScopStmt *Stmt, VectorValueMapT &VMap, std::vector<LoopToScevMapT> &VLTS,
593 std::vector<Value *> &IVS, __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000594 void createIf(__isl_take isl_ast_node *If);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000595 void createUserVector(
596 __isl_take isl_ast_node *User, std::vector<Value *> &IVS,
597 __isl_take isl_id *IteratorID, __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000598 void createUser(__isl_take isl_ast_node *User);
599 void createBlock(__isl_take isl_ast_node *Block);
600};
601
602__isl_give isl_ast_expr *IslNodeBuilder::getUpperBound(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000603 __isl_keep isl_ast_node *For, ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000604 isl_id *UBID, *IteratorID;
605 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000606 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000607
608 Cond = isl_ast_node_for_get_cond(For);
609 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000610 Type = isl_ast_expr_get_op_type(Cond);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000611
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000612 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
613 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000614
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000615 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000616 case isl_ast_op_le:
617 Predicate = ICmpInst::ICMP_SLE;
618 break;
619 case isl_ast_op_lt:
620 Predicate = ICmpInst::ICMP_SLT;
621 break;
622 default:
623 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000624 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000625
626 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
627
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000628 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
629 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000630
631 UBID = isl_ast_expr_get_id(Arg0);
632
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000633 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
634 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000635
636 IteratorID = isl_ast_expr_get_id(Iterator);
637
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000638 assert(UBID == IteratorID &&
639 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000640
641 UB = isl_ast_expr_get_op_arg(Cond, 1);
642
643 isl_ast_expr_free(Cond);
644 isl_ast_expr_free(Iterator);
645 isl_ast_expr_free(Arg0);
646 isl_id_free(IteratorID);
647 isl_id_free(UBID);
648
649 return UB;
650}
651
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000652unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
653 isl_id *Annotation = isl_ast_node_get_annotation(For);
654 if (!Annotation)
655 return -1;
656
Tobias Grosserc14582f2013-02-05 18:01:29 +0000657 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000658 if (!Info) {
659 isl_id_free(Annotation);
660 return -1;
661 }
662
663 isl_union_map *Schedule = isl_ast_build_get_schedule(Info->Context);
664 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
665 isl_id_free(Annotation);
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000666 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
667 if (NumberOfIterations == -1)
668 return -1;
669 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000670}
671
Tobias Grosserc14582f2013-02-05 18:01:29 +0000672void IslNodeBuilder::createUserVector(
673 __isl_take isl_ast_node *User, std::vector<Value *> &IVS,
674 __isl_take isl_id *IteratorID, __isl_take isl_union_map *Schedule) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000675 isl_id *Annotation = isl_ast_node_get_annotation(User);
676 assert(Annotation && "Vector user statement is not annotated");
677
Tobias Grosserc14582f2013-02-05 18:01:29 +0000678 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000679 assert(Info && "Vector user statement annotation does not contain info");
680
681 isl_id *Id = isl_pw_multi_aff_get_tuple_id(Info->PMA, isl_dim_out);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000682 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000683 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000684 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000685
686 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
687 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
688 isl_map *S = isl_map_from_union_map(Schedule);
689
690 createSubstitutionsVector(isl_pw_multi_aff_copy(Info->PMA),
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000691 isl_ast_build_copy(Info->Context), Stmt, VectorMap,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000692 VLTS, IVS, IteratorID);
693 VectorBlockGenerator::generate(Builder, *Stmt, VectorMap, VLTS, S, P);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000694
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000695 isl_map_free(S);
696 isl_id_free(Annotation);
697 isl_id_free(Id);
698 isl_ast_node_free(User);
699}
700
Tobias Grosserd7e58642013-04-10 06:55:45 +0000701void
702IslNodeBuilder::createForVector(__isl_take isl_ast_node *For, int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000703 isl_ast_node *Body = isl_ast_node_for_get_body(For);
704 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
705 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
706 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
707 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
708 CmpInst::Predicate Predicate;
709 isl_ast_expr *UB = getUpperBound(For, Predicate);
710
711 Value *ValueLB = ExprBuilder.create(Init);
712 Value *ValueUB = ExprBuilder.create(UB);
713 Value *ValueInc = ExprBuilder.create(Inc);
714
715 Type *MaxType = ExprBuilder.getType(Iterator);
716 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
717 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
718 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
719
720 if (MaxType != ValueLB->getType())
721 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
722 if (MaxType != ValueUB->getType())
723 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
724 if (MaxType != ValueInc->getType())
725 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
726
Tobias Grosserc14582f2013-02-05 18:01:29 +0000727 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000728 IVS[0] = ValueLB;
729
730 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000731 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000732
733 isl_id *Annotation = isl_ast_node_get_annotation(For);
734 assert(Annotation && "For statement is not annotated");
735
Tobias Grosserc14582f2013-02-05 18:01:29 +0000736 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000737 assert(Info && "For statement annotation does not contain info");
738
739 isl_union_map *Schedule = isl_ast_build_get_schedule(Info->Context);
740 assert(Schedule && "For statement annotation does not contain its schedule");
741
742 IDToValue[IteratorID] = ValueLB;
743
744 switch (isl_ast_node_get_type(Body)) {
745 case isl_ast_node_user:
746 createUserVector(Body, IVS, isl_id_copy(IteratorID),
747 isl_union_map_copy(Schedule));
748 break;
749 case isl_ast_node_block: {
750 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
751
752 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
753 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000754 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000755
756 isl_ast_node_free(Body);
757 isl_ast_node_list_free(List);
758 break;
759 }
760 default:
761 isl_ast_node_dump(Body);
762 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
763 }
764
765 IDToValue.erase(IteratorID);
766 isl_id_free(IteratorID);
767 isl_id_free(Annotation);
768 isl_union_map_free(Schedule);
769
770 isl_ast_node_free(For);
771 isl_ast_expr_free(Iterator);
772}
773
774void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000775 isl_ast_node *Body;
776 isl_ast_expr *Init, *Inc, *Iterator, *UB;
777 isl_id *IteratorID;
778 Value *ValueLB, *ValueUB, *ValueInc;
779 Type *MaxType;
780 BasicBlock *AfterBlock;
781 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000782 CmpInst::Predicate Predicate;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000783
784 Body = isl_ast_node_for_get_body(For);
785
786 // isl_ast_node_for_is_degenerate(For)
787 //
788 // TODO: For degenerated loops we could generate a plain assignment.
789 // However, for now we just reuse the logic for normal loops, which will
790 // create a loop with a single iteration.
791
792 Init = isl_ast_node_for_get_init(For);
793 Inc = isl_ast_node_for_get_inc(For);
794 Iterator = isl_ast_node_for_get_iterator(For);
795 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000796 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000797
798 ValueLB = ExprBuilder.create(Init);
799 ValueUB = ExprBuilder.create(UB);
800 ValueInc = ExprBuilder.create(Inc);
801
802 MaxType = ExprBuilder.getType(Iterator);
803 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
804 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
805 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
806
807 if (MaxType != ValueLB->getType())
808 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
809 if (MaxType != ValueUB->getType())
810 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
811 if (MaxType != ValueInc->getType())
812 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
813
814 // TODO: In case we can proof a loop is executed at least once, we can
815 // generate the condition iv != UB + stride (consider possible
816 // overflow). This condition will allow LLVM to prove the loop is
817 // executed at least once, which will enable a lot of loop invariant
818 // code motion.
819
Tobias Grosserc14582f2013-02-05 18:01:29 +0000820 IV =
821 createLoop(ValueLB, ValueUB, ValueInc, Builder, P, AfterBlock, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000822 IDToValue[IteratorID] = IV;
823
824 create(Body);
825
826 IDToValue.erase(IteratorID);
827
828 Builder.SetInsertPoint(AfterBlock->begin());
829
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
862 DominatorTree &DT = P->getAnalysis<DominatorTree>();
863 DT.addNewBlock(ThenBB, CondBB);
864 DT.addNewBlock(ElseBB, CondBB);
865 DT.changeImmediateDominator(MergeBB, CondBB);
866
867 CondBB->getTerminator()->eraseFromParent();
868
869 Builder.SetInsertPoint(CondBB);
870 Value *Predicate = ExprBuilder.create(Cond);
871 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
872 Builder.SetInsertPoint(ThenBB);
873 Builder.CreateBr(MergeBB);
874 Builder.SetInsertPoint(ElseBB);
875 Builder.CreateBr(MergeBB);
876 Builder.SetInsertPoint(ThenBB->begin());
877
878 create(isl_ast_node_if_get_then(If));
879
880 Builder.SetInsertPoint(ElseBB->begin());
881
882 if (isl_ast_node_if_has_else(If))
883 create(isl_ast_node_if_get_else(If));
884
885 Builder.SetInsertPoint(MergeBB->begin());
886
887 isl_ast_node_free(If);
888}
889
Tobias Grosser7242ad92013-02-22 08:07:06 +0000890void IslNodeBuilder::createSubstitutions(
891 __isl_take isl_pw_multi_aff *PMA, __isl_take isl_ast_build *Context,
892 ScopStmt *Stmt, ValueMapT &VMap, LoopToScevMapT &LTS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000893 for (unsigned i = 0; i < isl_pw_multi_aff_dim(PMA, isl_dim_out); ++i) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000894 isl_pw_aff *Aff;
895 isl_ast_expr *Expr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000896 Value *V;
897
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000898 Aff = isl_pw_multi_aff_get_pw_aff(PMA, i);
899 Expr = isl_ast_build_expr_from_pw_aff(Context, Aff);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000900 V = ExprBuilder.create(Expr);
901
Sebastian Pope039bb12013-03-18 19:09:49 +0000902 ScalarEvolution *SE = Stmt->getParent()->getSE();
903 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
904
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000905 // CreateIntCast can introduce trunc expressions. This is correct, as the
906 // result will always fit into the type of the original induction variable
907 // (because we calculate a value of the original induction variable).
Sebastian Pope039bb12013-03-18 19:09:49 +0000908 const Value *OldIV = Stmt->getInductionVariableForDimension(i);
909 if (OldIV) {
910 V = Builder.CreateIntCast(V, OldIV->getType(), true);
911 VMap[OldIV] = V;
912 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000913 }
914
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000915 isl_pw_multi_aff_free(PMA);
916 isl_ast_build_free(Context);
917}
918
Tobias Grosserc14582f2013-02-05 18:01:29 +0000919void IslNodeBuilder::createSubstitutionsVector(
920 __isl_take isl_pw_multi_aff *PMA, __isl_take isl_ast_build *Context,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000921 ScopStmt *Stmt, VectorValueMapT &VMap, std::vector<LoopToScevMapT> &VLTS,
922 std::vector<Value *> &IVS, __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000923 int i = 0;
924
925 Value *OldValue = IDToValue[IteratorID];
Tobias Grosserc14582f2013-02-05 18:01:29 +0000926 for (std::vector<Value *>::iterator II = IVS.begin(), IE = IVS.end();
927 II != IE; ++II) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000928 IDToValue[IteratorID] = *II;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000929 createSubstitutions(isl_pw_multi_aff_copy(PMA), isl_ast_build_copy(Context),
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000930 Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000931 i++;
932 }
933
934 IDToValue[IteratorID] = OldValue;
935 isl_id_free(IteratorID);
936 isl_pw_multi_aff_free(PMA);
937 isl_ast_build_free(Context);
938}
939
940void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
941 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000942 LoopToScevMapT LTS;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000943 struct IslAstUser *Info;
944 isl_id *Annotation, *Id;
945 ScopStmt *Stmt;
946
947 Annotation = isl_ast_node_get_annotation(User);
948 assert(Annotation && "Scalar user statement is not annotated");
949
Tobias Grosserc14582f2013-02-05 18:01:29 +0000950 Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000951 assert(Info && "Scalar user statement annotation does not contain info");
952
953 Id = isl_pw_multi_aff_get_tuple_id(Info->PMA, isl_dim_out);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000954 Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000955
956 createSubstitutions(isl_pw_multi_aff_copy(Info->PMA),
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000957 isl_ast_build_copy(Info->Context), Stmt, VMap, LTS);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000958
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000959 BlockGenerator::generate(Builder, *Stmt, VMap, LTS, P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000960
961 isl_ast_node_free(User);
962 isl_id_free(Annotation);
963 isl_id_free(Id);
964}
965
966void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
967 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
968
969 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
970 create(isl_ast_node_list_get_ast_node(List, i));
971
972 isl_ast_node_free(Block);
973 isl_ast_node_list_free(List);
974}
975
976void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
977 switch (isl_ast_node_get_type(Node)) {
978 case isl_ast_node_error:
979 llvm_unreachable("code generation error");
980 case isl_ast_node_for:
981 createFor(Node);
982 return;
983 case isl_ast_node_if:
984 createIf(Node);
985 return;
986 case isl_ast_node_user:
987 createUser(Node);
988 return;
989 case isl_ast_node_block:
990 createBlock(Node);
991 return;
992 }
993
994 llvm_unreachable("Unknown isl_ast_node type");
995}
996
997void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
998 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
999
1000 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
1001 isl_id *Id;
1002 const SCEV *Scev;
1003 IntegerType *T;
1004 Instruction *InsertLocation;
1005
1006 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserc14582f2013-02-05 18:01:29 +00001007 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001008 T = dyn_cast<IntegerType>(Scev->getType());
1009 InsertLocation = --(Builder.GetInsertBlock()->end());
1010 Value *V = Rewriter.expandCodeFor(Scev, T, InsertLocation);
1011 IDToValue[Id] = V;
1012
1013 isl_id_free(Id);
1014 }
1015
1016 isl_set_free(Context);
1017}
1018
1019namespace {
1020class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001021public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001022 static char ID;
1023
1024 IslCodeGeneration() : ScopPass(ID) {}
1025
1026 bool runOnScop(Scop &S) {
1027 IslAstInfo &AstInfo = getAnalysis<IslAstInfo>();
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001028
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001029 assert(!S.getRegion().isTopLevelRegion()
1030 && "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001031
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001032 simplifyRegion(&S, this);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001033
1034 BasicBlock *StartBlock = executeScopConditionally(S, this);
1035 isl_ast_node *Ast = AstInfo.getAst();
1036 IRBuilder<> Builder(StartBlock->begin());
1037
1038 IslNodeBuilder NodeBuilder(Builder, this);
1039 NodeBuilder.addParameters(S.getContext());
1040 NodeBuilder.create(Ast);
1041 return true;
1042 }
1043
Tobias Grosserc14582f2013-02-05 18:01:29 +00001044 virtual void printScop(raw_ostream &OS) const {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001045
1046 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1047 AU.addRequired<DominatorTree>();
1048 AU.addRequired<IslAstInfo>();
1049 AU.addRequired<RegionInfo>();
1050 AU.addRequired<ScalarEvolution>();
1051 AU.addRequired<ScopDetection>();
1052 AU.addRequired<ScopInfo>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001053 AU.addRequired<LoopInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001054
1055 AU.addPreserved<Dependences>();
1056
1057 // FIXME: We do not create LoopInfo for the newly generated loops.
1058 AU.addPreserved<LoopInfo>();
1059 AU.addPreserved<DominatorTree>();
1060 AU.addPreserved<IslAstInfo>();
1061 AU.addPreserved<ScopDetection>();
1062 AU.addPreserved<ScalarEvolution>();
1063
1064 // FIXME: We do not yet add regions for the newly generated code to the
1065 // region tree.
1066 AU.addPreserved<RegionInfo>();
1067 AU.addPreserved<TempScopInfo>();
1068 AU.addPreserved<ScopInfo>();
1069 AU.addPreservedID(IndependentBlocksID);
1070 }
1071};
1072}
1073
1074char IslCodeGeneration::ID = 1;
1075
Tobias Grosser7242ad92013-02-22 08:07:06 +00001076Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001077
Tobias Grosser7242ad92013-02-22 08:07:06 +00001078INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
1079 "Polly - Create LLVM-IR from SCoPs", false, false);
1080INITIALIZE_PASS_DEPENDENCY(Dependences);
1081INITIALIZE_PASS_DEPENDENCY(DominatorTree);
1082INITIALIZE_PASS_DEPENDENCY(LoopInfo);
1083INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1084INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1085INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1086INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
1087 "Polly - Create LLVM-IR from SCoPs", false, false)