blob: 56b065404c3fc60af8be1535da750d9b462bfd90 [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#define DEBUG_TYPE "polly-codegen-isl"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000039#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41
42#include "isl/union_map.h"
43#include "isl/list.h"
44#include "isl/ast.h"
45#include "isl/ast_build.h"
46#include "isl/set.h"
47#include "isl/map.h"
48#include "isl/aff.h"
49
50#include <map>
51
52using namespace polly;
53using namespace llvm;
54
55/// @brief Insert function calls that print certain LLVM values at run time.
56///
57/// This class inserts libc function calls to print certain LLVM values at
58/// run time.
59class RuntimeDebugBuilder {
60public:
Tobias Grosser5103ba72014-03-04 14:58:49 +000061 RuntimeDebugBuilder(PollyIRBuilder &Builder) : Builder(Builder) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000062
63 /// @brief Print a string to stdout.
64 ///
65 /// @param String The string to print.
66 void createStrPrinter(std::string String);
67
68 /// @brief Print an integer value to stdout.
69 ///
70 /// @param V The value to print.
71 void createIntPrinter(Value *V);
72
73private:
Tobias Grosser5103ba72014-03-04 14:58:49 +000074 PollyIRBuilder &Builder;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000075
76 /// @brief Add a call to the fflush function with no file pointer given.
77 ///
78 /// This call will flush all opened file pointers including stdout and stderr.
79 void createFlush();
80
81 /// @brief Get a reference to the 'printf' function.
82 ///
83 /// If the current module does not yet contain a reference to printf, we
84 /// insert a reference to it. Otherwise the existing reference is returned.
85 Function *getPrintF();
86};
87
88Function *RuntimeDebugBuilder::getPrintF() {
89 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
90 const char *Name = "printf";
91 Function *F = M->getFunction(Name);
92
93 if (!F) {
94 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosserc14582f2013-02-05 18:01:29 +000095 FunctionType *Ty =
96 FunctionType::get(Builder.getInt32Ty(), Builder.getInt8PtrTy(), true);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000097 F = Function::Create(Ty, Linkage, Name, M);
98 }
99
100 return F;
101}
102
103void RuntimeDebugBuilder::createFlush() {
104 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
105 const char *Name = "fflush";
106 Function *F = M->getFunction(Name);
107
108 if (!F) {
109 GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000110 FunctionType *Ty =
111 FunctionType::get(Builder.getInt32Ty(), Builder.getInt8PtrTy(), false);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000112 F = Function::Create(Ty, Linkage, Name, M);
113 }
114
115 Builder.CreateCall(F, Constant::getNullValue(Builder.getInt8PtrTy()));
116}
117
118void RuntimeDebugBuilder::createStrPrinter(std::string String) {
119 Function *F = getPrintF();
120 Value *StringValue = Builder.CreateGlobalStringPtr(String);
121 Builder.CreateCall(F, StringValue);
122
123 createFlush();
124}
125
126void RuntimeDebugBuilder::createIntPrinter(Value *V) {
127 IntegerType *Ty = dyn_cast<IntegerType>(V->getType());
Tobias Grosser58032cb2013-06-23 01:29:29 +0000128 (void)Ty;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000129 assert(Ty && Ty->getBitWidth() == 64 &&
130 "Cannot insert printer for this type.");
131
132 Function *F = getPrintF();
133 Value *String = Builder.CreateGlobalStringPtr("%ld");
134 Builder.CreateCall2(F, String, V);
135 createFlush();
136}
137
138/// @brief Calculate the Value of a certain isl_ast_expr
139class IslExprBuilder {
140public:
Tobias Grosser5103ba72014-03-04 14:58:49 +0000141 IslExprBuilder(PollyIRBuilder &Builder,
142 std::map<isl_id *, Value *> &IDToValue, Pass *P)
Tobias Grosser7242ad92013-02-22 08:07:06 +0000143 : Builder(Builder), IDToValue(IDToValue) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000144
145 Value *create(__isl_take isl_ast_expr *Expr);
146 Type *getWidestType(Type *T1, Type *T2);
147 IntegerType *getType(__isl_keep isl_ast_expr *Expr);
148
149private:
Tobias Grosser5103ba72014-03-04 14:58:49 +0000150 PollyIRBuilder &Builder;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000151 std::map<isl_id *, Value *> &IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000152
153 Value *createOp(__isl_take isl_ast_expr *Expr);
154 Value *createOpUnary(__isl_take isl_ast_expr *Expr);
155 Value *createOpBin(__isl_take isl_ast_expr *Expr);
156 Value *createOpNAry(__isl_take isl_ast_expr *Expr);
157 Value *createOpSelect(__isl_take isl_ast_expr *Expr);
158 Value *createOpICmp(__isl_take isl_ast_expr *Expr);
159 Value *createOpBoolean(__isl_take isl_ast_expr *Expr);
160 Value *createId(__isl_take isl_ast_expr *Expr);
161 Value *createInt(__isl_take isl_ast_expr *Expr);
162};
163
164Type *IslExprBuilder::getWidestType(Type *T1, Type *T2) {
165 assert(isa<IntegerType>(T1) && isa<IntegerType>(T2));
166
167 if (T1->getPrimitiveSizeInBits() < T2->getPrimitiveSizeInBits())
168 return T2;
169 else
170 return T1;
171}
172
173Value *IslExprBuilder::createOpUnary(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000174 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_minus &&
175 "Unsupported unary operation");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000176
177 Value *V;
178 Type *MaxType = getType(Expr);
179
180 V = create(isl_ast_expr_get_op_arg(Expr, 0));
181 MaxType = getWidestType(MaxType, V->getType());
182
183 if (MaxType != V->getType())
184 V = Builder.CreateSExt(V, MaxType);
185
186 isl_ast_expr_free(Expr);
187 return Builder.CreateNSWNeg(V);
188}
189
190Value *IslExprBuilder::createOpNAry(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000191 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
192 "isl ast expression not of type isl_ast_op");
193 assert(isl_ast_expr_get_op_n_arg(Expr) >= 2 &&
194 "We need at least two operands in an n-ary operation");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000195
196 Value *V;
197
198 V = create(isl_ast_expr_get_op_arg(Expr, 0));
199
200 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr); ++i) {
201 Value *OpV;
202 OpV = create(isl_ast_expr_get_op_arg(Expr, i));
203
204 Type *Ty = getWidestType(V->getType(), OpV->getType());
205
206 if (Ty != OpV->getType())
207 OpV = Builder.CreateSExt(OpV, Ty);
208
209 if (Ty != V->getType())
210 V = Builder.CreateSExt(V, Ty);
211
212 switch (isl_ast_expr_get_op_type(Expr)) {
213 default:
214 llvm_unreachable("This is no n-ary isl ast expression");
215
Tobias Grosserc14582f2013-02-05 18:01:29 +0000216 case isl_ast_op_max: {
217 Value *Cmp = Builder.CreateICmpSGT(V, OpV);
218 V = Builder.CreateSelect(Cmp, V, OpV);
219 continue;
220 }
221 case isl_ast_op_min: {
222 Value *Cmp = Builder.CreateICmpSLT(V, OpV);
223 V = Builder.CreateSelect(Cmp, V, OpV);
224 continue;
225 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000226 }
227 }
228
229 // TODO: We can truncate the result, if it fits into a smaller type. This can
230 // help in cases where we have larger operands (e.g. i67) but the result is
231 // known to fit into i64. Without the truncation, the larger i67 type may
232 // force all subsequent operations to be performed on a non-native type.
233 isl_ast_expr_free(Expr);
234 return V;
235}
236
237Value *IslExprBuilder::createOpBin(__isl_take isl_ast_expr *Expr) {
238 Value *LHS, *RHS, *Res;
239 Type *MaxType;
240 isl_ast_op_type OpType;
241
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000242 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
243 "isl ast expression not of type isl_ast_op");
244 assert(isl_ast_expr_get_op_n_arg(Expr) == 2 &&
245 "not a binary isl ast expression");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000246
247 OpType = isl_ast_expr_get_op_type(Expr);
248
249 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
250 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
251
252 MaxType = LHS->getType();
253 MaxType = getWidestType(MaxType, RHS->getType());
254
255 // Take the result into account when calculating the widest type.
256 //
257 // For operations such as '+' the result may require a type larger than
258 // the type of the individual operands. For other operations such as '/', the
259 // result type cannot be larger than the type of the individual operand. isl
260 // does not calculate correct types for these operations and we consequently
261 // exclude those operations here.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000262 switch (OpType) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000263 case isl_ast_op_pdiv_q:
264 case isl_ast_op_pdiv_r:
265 case isl_ast_op_div:
266 case isl_ast_op_fdiv_q:
267 // Do nothing
268 break;
269 case isl_ast_op_add:
270 case isl_ast_op_sub:
271 case isl_ast_op_mul:
272 MaxType = getWidestType(MaxType, getType(Expr));
273 break;
274 default:
275 llvm_unreachable("This is no binary isl ast expression");
276 }
277
278 if (MaxType != RHS->getType())
279 RHS = Builder.CreateSExt(RHS, MaxType);
280
281 if (MaxType != LHS->getType())
282 LHS = Builder.CreateSExt(LHS, MaxType);
283
284 switch (OpType) {
285 default:
286 llvm_unreachable("This is no binary isl ast expression");
287 case isl_ast_op_add:
288 Res = Builder.CreateNSWAdd(LHS, RHS);
289 break;
290 case isl_ast_op_sub:
291 Res = Builder.CreateNSWSub(LHS, RHS);
292 break;
293 case isl_ast_op_mul:
294 Res = Builder.CreateNSWMul(LHS, RHS);
295 break;
296 case isl_ast_op_div:
297 case isl_ast_op_pdiv_q: // Dividend is non-negative
298 Res = Builder.CreateSDiv(LHS, RHS);
299 break;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000300 case isl_ast_op_fdiv_q: { // Round towards -infty
301 // TODO: Review code and check that this calculation does not yield
302 // incorrect overflow in some bordercases.
303 //
304 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
305 Value *One = ConstantInt::get(MaxType, 1);
306 Value *Zero = ConstantInt::get(MaxType, 0);
307 Value *Sum1 = Builder.CreateSub(LHS, RHS);
308 Value *Sum2 = Builder.CreateAdd(Sum1, One);
309 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
310 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
311 Res = Builder.CreateSDiv(Dividend, RHS);
312 break;
313 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000314 case isl_ast_op_pdiv_r: // Dividend is non-negative
315 Res = Builder.CreateSRem(LHS, RHS);
316 break;
317 }
318
319 // TODO: We can truncate the result, if it fits into a smaller type. This can
320 // help in cases where we have larger operands (e.g. i67) but the result is
321 // known to fit into i64. Without the truncation, the larger i67 type may
322 // force all subsequent operations to be performed on a non-native type.
323 isl_ast_expr_free(Expr);
324 return Res;
325}
326
327Value *IslExprBuilder::createOpSelect(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000328 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_select &&
329 "Unsupported unary isl ast expression");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000330 Value *LHS, *RHS, *Cond;
331 Type *MaxType = getType(Expr);
332
333 Cond = create(isl_ast_expr_get_op_arg(Expr, 0));
334
335 LHS = create(isl_ast_expr_get_op_arg(Expr, 1));
336 RHS = create(isl_ast_expr_get_op_arg(Expr, 2));
337
338 MaxType = getWidestType(MaxType, LHS->getType());
339 MaxType = getWidestType(MaxType, RHS->getType());
340
341 if (MaxType != RHS->getType())
342 RHS = Builder.CreateSExt(RHS, MaxType);
343
344 if (MaxType != LHS->getType())
345 LHS = Builder.CreateSExt(LHS, MaxType);
346
347 // TODO: Do we want to truncate the result?
348 isl_ast_expr_free(Expr);
349 return Builder.CreateSelect(Cond, LHS, RHS);
350}
351
352Value *IslExprBuilder::createOpICmp(__isl_take isl_ast_expr *Expr) {
353 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
354 "Expected an isl_ast_expr_op expression");
355
356 Value *LHS, *RHS, *Res;
357
358 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
359 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
360
361 Type *MaxType = LHS->getType();
362 MaxType = getWidestType(MaxType, RHS->getType());
363
364 if (MaxType != RHS->getType())
365 RHS = Builder.CreateSExt(RHS, MaxType);
366
367 if (MaxType != LHS->getType())
368 LHS = Builder.CreateSExt(LHS, MaxType);
369
370 switch (isl_ast_expr_get_op_type(Expr)) {
371 default:
372 llvm_unreachable("Unsupported ICmp isl ast expression");
373 case isl_ast_op_eq:
374 Res = Builder.CreateICmpEQ(LHS, RHS);
375 break;
376 case isl_ast_op_le:
377 Res = Builder.CreateICmpSLE(LHS, RHS);
378 break;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000379 case isl_ast_op_lt:
380 Res = Builder.CreateICmpSLT(LHS, RHS);
381 break;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000382 case isl_ast_op_ge:
383 Res = Builder.CreateICmpSGE(LHS, RHS);
384 break;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000385 case isl_ast_op_gt:
386 Res = Builder.CreateICmpSGT(LHS, RHS);
387 break;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000388 }
389
390 isl_ast_expr_free(Expr);
391 return Res;
392}
393
394Value *IslExprBuilder::createOpBoolean(__isl_take isl_ast_expr *Expr) {
395 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
396 "Expected an isl_ast_expr_op expression");
397
398 Value *LHS, *RHS, *Res;
399 isl_ast_op_type OpType;
400
401 OpType = isl_ast_expr_get_op_type(Expr);
402
403 assert((OpType == isl_ast_op_and || OpType == isl_ast_op_or) &&
404 "Unsupported isl_ast_op_type");
405
406 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
407 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
408
409 // Even though the isl pretty printer prints the expressions as 'exp && exp'
410 // or 'exp || exp', we actually code generate the bitwise expressions
411 // 'exp & exp' or 'exp | exp'. This forces the evaluation of both branches,
412 // but it is, due to the use of i1 types, otherwise equivalent. The reason
413 // to go for bitwise operations is, that we assume the reduced control flow
414 // will outweight the overhead introduced by evaluating unneeded expressions.
415 // The isl code generation currently does not take advantage of the fact that
416 // the expression after an '||' or '&&' is in some cases not evaluated.
417 // Evaluating it anyways does not cause any undefined behaviour.
418 //
419 // TODO: Document in isl itself, that the unconditionally evaluating the
420 // second part of '||' or '&&' expressions is safe.
421 assert(LHS->getType() == Builder.getInt1Ty() && "Expected i1 type");
422 assert(RHS->getType() == Builder.getInt1Ty() && "Expected i1 type");
423
424 switch (OpType) {
425 default:
426 llvm_unreachable("Unsupported boolean expression");
427 case isl_ast_op_and:
428 Res = Builder.CreateAnd(LHS, RHS);
429 break;
430 case isl_ast_op_or:
431 Res = Builder.CreateOr(LHS, RHS);
432 break;
433 }
434
435 isl_ast_expr_free(Expr);
436 return Res;
437}
438
439Value *IslExprBuilder::createOp(__isl_take isl_ast_expr *Expr) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000440 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
441 "Expression not of type isl_ast_expr_op");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000442 switch (isl_ast_expr_get_op_type(Expr)) {
443 case isl_ast_op_error:
444 case isl_ast_op_cond:
445 case isl_ast_op_and_then:
446 case isl_ast_op_or_else:
447 case isl_ast_op_call:
Tobias Grossera38c9242014-01-26 19:36:28 +0000448 case isl_ast_op_member:
449 case isl_ast_op_access:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000450 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 Grosseredab1352013-06-21 06:41:31 +0000510 isl_val *Val;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000511 Value *V;
512 APInt APValue;
513 IntegerType *T;
514
Tobias Grosseredab1352013-06-21 06:41:31 +0000515 Val = isl_ast_expr_get_val(Expr);
516 APValue = APIntFromVal(Val);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000517 T = getType(Expr);
518 APValue = APValue.sextOrSelf(T->getBitWidth());
519 V = ConstantInt::get(T, APValue);
520
521 isl_ast_expr_free(Expr);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000522 return V;
523}
524
525Value *IslExprBuilder::create(__isl_take isl_ast_expr *Expr) {
526 switch (isl_ast_expr_get_type(Expr)) {
527 case isl_ast_expr_error:
528 llvm_unreachable("Code generation error");
529 case isl_ast_expr_op:
530 return createOp(Expr);
531 case isl_ast_expr_id:
532 return createId(Expr);
533 case isl_ast_expr_int:
534 return createInt(Expr);
535 }
536
537 llvm_unreachable("Unexpected enum value");
538}
539
540class IslNodeBuilder {
541public:
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000542 IslNodeBuilder(PollyIRBuilder &Builder, LoopAnnotator &Annotator, Pass *P)
543 : Builder(Builder), Annotator(Annotator),
544 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);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +0000548 IslExprBuilder &getExprBuilder() { return ExprBuilder; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000549
550private:
Tobias Grosser5103ba72014-03-04 14:58:49 +0000551 PollyIRBuilder &Builder;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000552 LoopAnnotator &Annotator;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000553 IslExprBuilder ExprBuilder;
554 Pass *P;
555
556 // This maps an isl_id* to the Value* it has in the generated program. For now
557 // on, the only isl_ids that are stored here are the newly calculated loop
558 // ivs.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000559 std::map<isl_id *, Value *> IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000560
561 // Extract the upper bound of this loop
562 //
563 // The isl code generation can generate arbitrary expressions to check if the
564 // upper bound of a loop is reached, but it provides an option to enforce
565 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
566 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
567 //
568 // This function extracts 'atomic' upper bounds. Polly, in general, requires
569 // atomic upper bounds for the following reasons:
570 //
571 // 1. An atomic upper bound is loop invariant
572 //
573 // It must not be calculated at each loop iteration and can often even be
574 // hoisted out further by the loop invariant code motion.
575 //
576 // 2. OpenMP needs a loop invarient upper bound to calculate the number
577 // of loop iterations.
578 //
579 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grossere602a072013-05-07 07:30:56 +0000580 __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
581 CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000582
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000583 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
584
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000585 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000586 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
587 void createForSequential(__isl_take isl_ast_node *For);
588 void createSubstitutions(__isl_take isl_pw_multi_aff *PMA,
Tobias Grosserc14582f2013-02-05 18:01:29 +0000589 __isl_take isl_ast_build *Context, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000590 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grossere602a072013-05-07 07:30:56 +0000591 void createSubstitutionsVector(__isl_take isl_pw_multi_aff *PMA,
592 __isl_take isl_ast_build *Context,
593 ScopStmt *Stmt, VectorValueMapT &VMap,
594 std::vector<LoopToScevMapT> &VLTS,
595 std::vector<Value *> &IVS,
596 __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000597 void createIf(__isl_take isl_ast_node *If);
Tobias Grossere602a072013-05-07 07:30:56 +0000598 void createUserVector(__isl_take isl_ast_node *User,
599 std::vector<Value *> &IVS,
600 __isl_take isl_id *IteratorID,
601 __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000602 void createUser(__isl_take isl_ast_node *User);
603 void createBlock(__isl_take isl_ast_node *Block);
604};
605
Tobias Grossere602a072013-05-07 07:30:56 +0000606__isl_give isl_ast_expr *
607IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
608 ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000609 isl_id *UBID, *IteratorID;
610 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000611 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000612
613 Cond = isl_ast_node_for_get_cond(For);
614 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000615 Type = isl_ast_expr_get_op_type(Cond);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000616
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000617 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
618 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000619
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000620 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000621 case isl_ast_op_le:
622 Predicate = ICmpInst::ICMP_SLE;
623 break;
624 case isl_ast_op_lt:
625 Predicate = ICmpInst::ICMP_SLT;
626 break;
627 default:
628 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000629 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000630
631 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
632
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000633 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
634 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000635
636 UBID = isl_ast_expr_get_id(Arg0);
637
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000638 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
639 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000640
641 IteratorID = isl_ast_expr_get_id(Iterator);
642
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000643 assert(UBID == IteratorID &&
644 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000645
646 UB = isl_ast_expr_get_op_arg(Cond, 1);
647
648 isl_ast_expr_free(Cond);
649 isl_ast_expr_free(Iterator);
650 isl_ast_expr_free(Arg0);
651 isl_id_free(IteratorID);
652 isl_id_free(UBID);
653
654 return UB;
655}
656
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000657unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
658 isl_id *Annotation = isl_ast_node_get_annotation(For);
659 if (!Annotation)
660 return -1;
661
Tobias Grosserc14582f2013-02-05 18:01:29 +0000662 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000663 if (!Info) {
664 isl_id_free(Annotation);
665 return -1;
666 }
667
668 isl_union_map *Schedule = isl_ast_build_get_schedule(Info->Context);
669 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
670 isl_id_free(Annotation);
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000671 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
672 if (NumberOfIterations == -1)
673 return -1;
674 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000675}
676
Tobias Grossere602a072013-05-07 07:30:56 +0000677void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
678 std::vector<Value *> &IVS,
679 __isl_take isl_id *IteratorID,
680 __isl_take isl_union_map *Schedule) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000681 isl_id *Annotation = isl_ast_node_get_annotation(User);
682 assert(Annotation && "Vector user statement is not annotated");
683
Tobias Grosserc14582f2013-02-05 18:01:29 +0000684 struct IslAstUser *Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000685 assert(Info && "Vector user statement annotation does not contain info");
686
687 isl_id *Id = isl_pw_multi_aff_get_tuple_id(Info->PMA, isl_dim_out);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000688 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000689 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000690 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000691
692 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
693 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
694 isl_map *S = isl_map_from_union_map(Schedule);
695
696 createSubstitutionsVector(isl_pw_multi_aff_copy(Info->PMA),
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000697 isl_ast_build_copy(Info->Context), Stmt, VectorMap,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000698 VLTS, IVS, IteratorID);
699 VectorBlockGenerator::generate(Builder, *Stmt, VectorMap, VLTS, S, P);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000700
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000701 isl_map_free(S);
702 isl_id_free(Annotation);
703 isl_id_free(Id);
704 isl_ast_node_free(User);
705}
706
Tobias Grossere602a072013-05-07 07:30:56 +0000707void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
708 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000709 isl_ast_node *Body = isl_ast_node_for_get_body(For);
710 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
711 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
712 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
713 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000714
715 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000716 Value *ValueInc = ExprBuilder.create(Inc);
717
718 Type *MaxType = ExprBuilder.getType(Iterator);
719 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000720 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
721
722 if (MaxType != ValueLB->getType())
723 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000724 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;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000780 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000781 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000782 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000783 bool Parallel;
784
785 Parallel = isInnermostParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000786
787 Body = isl_ast_node_for_get_body(For);
788
789 // isl_ast_node_for_is_degenerate(For)
790 //
791 // TODO: For degenerated loops we could generate a plain assignment.
792 // However, for now we just reuse the logic for normal loops, which will
793 // create a loop with a single iteration.
794
795 Init = isl_ast_node_for_get_init(For);
796 Inc = isl_ast_node_for_get_inc(For);
797 Iterator = isl_ast_node_for_get_iterator(For);
798 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000799 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000800
801 ValueLB = ExprBuilder.create(Init);
802 ValueUB = ExprBuilder.create(UB);
803 ValueInc = ExprBuilder.create(Inc);
804
805 MaxType = ExprBuilder.getType(Iterator);
806 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
807 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
808 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
809
810 if (MaxType != ValueLB->getType())
811 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
812 if (MaxType != ValueUB->getType())
813 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
814 if (MaxType != ValueInc->getType())
815 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
816
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000817 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, ExitBlock, Predicate,
818 &Annotator, Parallel);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000819 IDToValue[IteratorID] = IV;
820
821 create(Body);
822
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000823 Annotator.End();
824
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000825 IDToValue.erase(IteratorID);
826
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000827 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000828
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
Tobias Grosser42aff302014-01-13 22:29:56 +0000861 DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000862 DT.addNewBlock(ThenBB, CondBB);
863 DT.addNewBlock(ElseBB, CondBB);
864 DT.changeImmediateDominator(MergeBB, CondBB);
865
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000866 LoopInfo &LI = P->getAnalysis<LoopInfo>();
867 Loop *L = LI.getLoopFor(CondBB);
868 if (L) {
869 L->addBasicBlockToLoop(ThenBB, LI.getBase());
870 L->addBasicBlockToLoop(ElseBB, LI.getBase());
871 }
872
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000873 CondBB->getTerminator()->eraseFromParent();
874
875 Builder.SetInsertPoint(CondBB);
876 Value *Predicate = ExprBuilder.create(Cond);
877 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
878 Builder.SetInsertPoint(ThenBB);
879 Builder.CreateBr(MergeBB);
880 Builder.SetInsertPoint(ElseBB);
881 Builder.CreateBr(MergeBB);
882 Builder.SetInsertPoint(ThenBB->begin());
883
884 create(isl_ast_node_if_get_then(If));
885
886 Builder.SetInsertPoint(ElseBB->begin());
887
888 if (isl_ast_node_if_has_else(If))
889 create(isl_ast_node_if_get_else(If));
890
891 Builder.SetInsertPoint(MergeBB->begin());
892
893 isl_ast_node_free(If);
894}
895
Tobias Grossere602a072013-05-07 07:30:56 +0000896void IslNodeBuilder::createSubstitutions(__isl_take isl_pw_multi_aff *PMA,
897 __isl_take isl_ast_build *Context,
898 ScopStmt *Stmt, ValueMapT &VMap,
899 LoopToScevMapT &LTS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000900 for (unsigned i = 0; i < isl_pw_multi_aff_dim(PMA, isl_dim_out); ++i) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000901 isl_pw_aff *Aff;
902 isl_ast_expr *Expr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000903 Value *V;
904
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000905 Aff = isl_pw_multi_aff_get_pw_aff(PMA, i);
906 Expr = isl_ast_build_expr_from_pw_aff(Context, Aff);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000907 V = ExprBuilder.create(Expr);
908
Sebastian Pope039bb12013-03-18 19:09:49 +0000909 ScalarEvolution *SE = Stmt->getParent()->getSE();
910 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
911
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000912 // CreateIntCast can introduce trunc expressions. This is correct, as the
913 // result will always fit into the type of the original induction variable
914 // (because we calculate a value of the original induction variable).
Sebastian Pope039bb12013-03-18 19:09:49 +0000915 const Value *OldIV = Stmt->getInductionVariableForDimension(i);
916 if (OldIV) {
917 V = Builder.CreateIntCast(V, OldIV->getType(), true);
918 VMap[OldIV] = V;
919 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000920 }
921
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000922 isl_pw_multi_aff_free(PMA);
923 isl_ast_build_free(Context);
924}
925
Tobias Grosserc14582f2013-02-05 18:01:29 +0000926void IslNodeBuilder::createSubstitutionsVector(
927 __isl_take isl_pw_multi_aff *PMA, __isl_take isl_ast_build *Context,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000928 ScopStmt *Stmt, VectorValueMapT &VMap, std::vector<LoopToScevMapT> &VLTS,
929 std::vector<Value *> &IVS, __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000930 int i = 0;
931
932 Value *OldValue = IDToValue[IteratorID];
Tobias Grosserc14582f2013-02-05 18:01:29 +0000933 for (std::vector<Value *>::iterator II = IVS.begin(), IE = IVS.end();
934 II != IE; ++II) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000935 IDToValue[IteratorID] = *II;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000936 createSubstitutions(isl_pw_multi_aff_copy(PMA), isl_ast_build_copy(Context),
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000937 Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000938 i++;
939 }
940
941 IDToValue[IteratorID] = OldValue;
942 isl_id_free(IteratorID);
943 isl_pw_multi_aff_free(PMA);
944 isl_ast_build_free(Context);
945}
946
947void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
948 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000949 LoopToScevMapT LTS;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000950 struct IslAstUser *Info;
951 isl_id *Annotation, *Id;
952 ScopStmt *Stmt;
953
954 Annotation = isl_ast_node_get_annotation(User);
955 assert(Annotation && "Scalar user statement is not annotated");
956
Tobias Grosserc14582f2013-02-05 18:01:29 +0000957 Info = (struct IslAstUser *)isl_id_get_user(Annotation);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000958 assert(Info && "Scalar user statement annotation does not contain info");
959
960 Id = isl_pw_multi_aff_get_tuple_id(Info->PMA, isl_dim_out);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000961 Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000962
963 createSubstitutions(isl_pw_multi_aff_copy(Info->PMA),
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000964 isl_ast_build_copy(Info->Context), Stmt, VMap, LTS);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000965
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000966 BlockGenerator::generate(Builder, *Stmt, VMap, LTS, P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000967
968 isl_ast_node_free(User);
969 isl_id_free(Annotation);
970 isl_id_free(Id);
971}
972
973void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
974 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
975
976 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
977 create(isl_ast_node_list_get_ast_node(List, i));
978
979 isl_ast_node_free(Block);
980 isl_ast_node_list_free(List);
981}
982
983void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
984 switch (isl_ast_node_get_type(Node)) {
985 case isl_ast_node_error:
986 llvm_unreachable("code generation error");
987 case isl_ast_node_for:
988 createFor(Node);
989 return;
990 case isl_ast_node_if:
991 createIf(Node);
992 return;
993 case isl_ast_node_user:
994 createUser(Node);
995 return;
996 case isl_ast_node_block:
997 createBlock(Node);
998 return;
999 }
1000
1001 llvm_unreachable("Unknown isl_ast_node type");
1002}
1003
1004void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
1005 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
1006
1007 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
1008 isl_id *Id;
1009 const SCEV *Scev;
1010 IntegerType *T;
1011 Instruction *InsertLocation;
1012
1013 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserc14582f2013-02-05 18:01:29 +00001014 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001015 T = dyn_cast<IntegerType>(Scev->getType());
1016 InsertLocation = --(Builder.GetInsertBlock()->end());
1017 Value *V = Rewriter.expandCodeFor(Scev, T, InsertLocation);
1018 IDToValue[Id] = V;
1019
1020 isl_id_free(Id);
1021 }
1022
1023 isl_set_free(Context);
1024}
1025
1026namespace {
1027class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001028public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001029 static char ID;
1030
1031 IslCodeGeneration() : ScopPass(ID) {}
1032
1033 bool runOnScop(Scop &S) {
1034 IslAstInfo &AstInfo = getAnalysis<IslAstInfo>();
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001035
Tobias Grossere602a072013-05-07 07:30:56 +00001036 assert(!S.getRegion().isTopLevelRegion() &&
1037 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001038
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001039 simplifyRegion(&S, this);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001040
1041 BasicBlock *StartBlock = executeScopConditionally(S, this);
1042 isl_ast_node *Ast = AstInfo.getAst();
Tobias Grosser37c9b8e2014-03-04 14:59:00 +00001043 LoopAnnotator Annotator;
1044 PollyIRBuilder Builder(StartBlock->getContext(), llvm::ConstantFolder(),
1045 polly::IRInserter(Annotator));
1046 Builder.SetInsertPoint(StartBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001047
Tobias Grosser37c9b8e2014-03-04 14:59:00 +00001048 IslNodeBuilder NodeBuilder(Builder, Annotator, this);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +00001049
1050 // Build condition that evaluates at run-time if all assumptions taken
1051 // for the scop hold. If we detect some assumptions do not hold, the
1052 // original code is executed.
1053 Value *V = NodeBuilder.getExprBuilder().create(AstInfo.getRunCondition());
1054 Value *Zero = ConstantInt::get(V->getType(), 0);
1055 V = Builder.CreateICmp(CmpInst::ICMP_NE, Zero, V);
1056 BasicBlock *PrevBB = StartBlock->getUniquePredecessor();
1057 BranchInst *Branch = dyn_cast<BranchInst>(PrevBB->getTerminator());
1058 Branch->setCondition(V);
1059
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001060 NodeBuilder.addParameters(S.getContext());
1061 NodeBuilder.create(Ast);
1062 return true;
1063 }
1064
Tobias Grosserc14582f2013-02-05 18:01:29 +00001065 virtual void printScop(raw_ostream &OS) const {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001066
1067 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +00001068 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001069 AU.addRequired<IslAstInfo>();
1070 AU.addRequired<RegionInfo>();
1071 AU.addRequired<ScalarEvolution>();
1072 AU.addRequired<ScopDetection>();
1073 AU.addRequired<ScopInfo>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001074 AU.addRequired<LoopInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001075
1076 AU.addPreserved<Dependences>();
1077
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001078 AU.addPreserved<LoopInfo>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001079 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001080 AU.addPreserved<IslAstInfo>();
1081 AU.addPreserved<ScopDetection>();
1082 AU.addPreserved<ScalarEvolution>();
1083
1084 // FIXME: We do not yet add regions for the newly generated code to the
1085 // region tree.
1086 AU.addPreserved<RegionInfo>();
1087 AU.addPreserved<TempScopInfo>();
1088 AU.addPreserved<ScopInfo>();
1089 AU.addPreservedID(IndependentBlocksID);
1090 }
1091};
1092}
1093
1094char IslCodeGeneration::ID = 1;
1095
Tobias Grosser7242ad92013-02-22 08:07:06 +00001096Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001097
Tobias Grosser7242ad92013-02-22 08:07:06 +00001098INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
1099 "Polly - Create LLVM-IR from SCoPs", false, false);
1100INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +00001101INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001102INITIALIZE_PASS_DEPENDENCY(LoopInfo);
1103INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1104INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1105INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1106INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
1107 "Polly - Create LLVM-IR from SCoPs", false, false)