1 //===------ IslExprBuilder.cpp ----- Code generate isl AST expressions ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "polly/CodeGen/IslExprBuilder.h"
12 #include "polly/CodeGen/RuntimeDebugBuilder.h"
13 #include "polly/Options.h"
14 #include "polly/ScopInfo.h"
15 #include "polly/Support/GICHelper.h"
16 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
17
18 using namespace llvm;
19 using namespace polly;
20
21 /// Different overflow tracking modes.
22 enum OverflowTrackingChoice {
23 OT_NEVER, ///< Never tack potential overflows.
24 OT_REQUEST, ///< Track potential overflows if requested.
25 OT_ALWAYS ///< Always track potential overflows.
26 };
27
28 static cl::opt<OverflowTrackingChoice> OTMode(
29 "polly-overflow-tracking",
30 cl::desc("Define where potential integer overflows in generated "
31 "expressions should be tracked."),
32 cl::values(clEnumValN(OT_NEVER, "never", "Never track the overflow bit."),
33 clEnumValN(OT_REQUEST, "request",
34 "Track the overflow bit if requested."),
35 clEnumValN(OT_ALWAYS, "always",
36 "Always track the overflow bit.")),
37 cl::Hidden, cl::init(OT_REQUEST), cl::cat(PollyCategory));
38
IslExprBuilder(Scop & S,PollyIRBuilder & Builder,IDToValueTy & IDToValue,ValueMapT & GlobalMap,const DataLayout & DL,ScalarEvolution & SE,DominatorTree & DT,LoopInfo & LI,BasicBlock * StartBlock)39 IslExprBuilder::IslExprBuilder(Scop &S, PollyIRBuilder &Builder,
40 IDToValueTy &IDToValue, ValueMapT &GlobalMap,
41 const DataLayout &DL, ScalarEvolution &SE,
42 DominatorTree &DT, LoopInfo &LI,
43 BasicBlock *StartBlock)
44 : S(S), Builder(Builder), IDToValue(IDToValue), GlobalMap(GlobalMap),
45 DL(DL), SE(SE), DT(DT), LI(LI), StartBlock(StartBlock) {
46 OverflowState = (OTMode == OT_ALWAYS) ? Builder.getFalse() : nullptr;
47 }
48
setTrackOverflow(bool Enable)49 void IslExprBuilder::setTrackOverflow(bool Enable) {
50 // If potential overflows are tracked always or never we ignore requests
51 // to change the behavior.
52 if (OTMode != OT_REQUEST)
53 return;
54
55 if (Enable) {
56 // If tracking should be enabled initialize the OverflowState.
57 OverflowState = Builder.getFalse();
58 } else {
59 // If tracking should be disabled just unset the OverflowState.
60 OverflowState = nullptr;
61 }
62 }
63
getOverflowState() const64 Value *IslExprBuilder::getOverflowState() const {
65 // If the overflow tracking was requested but it is disabled we avoid the
66 // additional nullptr checks at the call sides but instead provide a
67 // meaningful result.
68 if (OTMode == OT_NEVER)
69 return Builder.getFalse();
70 return OverflowState;
71 }
72
hasLargeInts(isl::ast_expr Expr)73 bool IslExprBuilder::hasLargeInts(isl::ast_expr Expr) {
74 enum isl_ast_expr_type Type = isl_ast_expr_get_type(Expr.get());
75
76 if (Type == isl_ast_expr_id)
77 return false;
78
79 if (Type == isl_ast_expr_int) {
80 isl::val Val = Expr.get_val();
81 APInt APValue = APIntFromVal(Val);
82 auto BitWidth = APValue.getBitWidth();
83 return BitWidth >= 64;
84 }
85
86 assert(Type == isl_ast_expr_op && "Expected isl_ast_expr of type operation");
87
88 int NumArgs = isl_ast_expr_get_op_n_arg(Expr.get());
89
90 for (int i = 0; i < NumArgs; i++) {
91 isl::ast_expr Operand = Expr.get_op_arg(i);
92 if (hasLargeInts(Operand))
93 return true;
94 }
95
96 return false;
97 }
98
createBinOp(BinaryOperator::BinaryOps Opc,Value * LHS,Value * RHS,const Twine & Name)99 Value *IslExprBuilder::createBinOp(BinaryOperator::BinaryOps Opc, Value *LHS,
100 Value *RHS, const Twine &Name) {
101 // Handle the plain operation (without overflow tracking) first.
102 if (!OverflowState) {
103 switch (Opc) {
104 case Instruction::Add:
105 return Builder.CreateNSWAdd(LHS, RHS, Name);
106 case Instruction::Sub:
107 return Builder.CreateNSWSub(LHS, RHS, Name);
108 case Instruction::Mul:
109 return Builder.CreateNSWMul(LHS, RHS, Name);
110 default:
111 llvm_unreachable("Unknown binary operator!");
112 }
113 }
114
115 Function *F = nullptr;
116 Module *M = Builder.GetInsertBlock()->getModule();
117 switch (Opc) {
118 case Instruction::Add:
119 F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
120 {LHS->getType()});
121 break;
122 case Instruction::Sub:
123 F = Intrinsic::getDeclaration(M, Intrinsic::ssub_with_overflow,
124 {LHS->getType()});
125 break;
126 case Instruction::Mul:
127 F = Intrinsic::getDeclaration(M, Intrinsic::smul_with_overflow,
128 {LHS->getType()});
129 break;
130 default:
131 llvm_unreachable("No overflow intrinsic for binary operator found!");
132 }
133
134 auto *ResultStruct = Builder.CreateCall(F, {LHS, RHS}, Name);
135 assert(ResultStruct->getType()->isStructTy());
136
137 auto *OverflowFlag =
138 Builder.CreateExtractValue(ResultStruct, 1, Name + ".obit");
139
140 // If all overflows are tracked we do not combine the results as this could
141 // cause dominance problems. Instead we will always keep the last overflow
142 // flag as current state.
143 if (OTMode == OT_ALWAYS)
144 OverflowState = OverflowFlag;
145 else
146 OverflowState =
147 Builder.CreateOr(OverflowState, OverflowFlag, "polly.overflow.state");
148
149 return Builder.CreateExtractValue(ResultStruct, 0, Name + ".res");
150 }
151
createAdd(Value * LHS,Value * RHS,const Twine & Name)152 Value *IslExprBuilder::createAdd(Value *LHS, Value *RHS, const Twine &Name) {
153 return createBinOp(Instruction::Add, LHS, RHS, Name);
154 }
155
createSub(Value * LHS,Value * RHS,const Twine & Name)156 Value *IslExprBuilder::createSub(Value *LHS, Value *RHS, const Twine &Name) {
157 return createBinOp(Instruction::Sub, LHS, RHS, Name);
158 }
159
createMul(Value * LHS,Value * RHS,const Twine & Name)160 Value *IslExprBuilder::createMul(Value *LHS, Value *RHS, const Twine &Name) {
161 return createBinOp(Instruction::Mul, LHS, RHS, Name);
162 }
163
getWidestType(Type * T1,Type * T2)164 Type *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
createOpUnary(__isl_take isl_ast_expr * Expr)173 Value *IslExprBuilder::createOpUnary(__isl_take isl_ast_expr *Expr) {
174 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_minus &&
175 "Unsupported unary operation");
176
177 Value *V;
178 Type *MaxType = getType(Expr);
179 assert(MaxType->isIntegerTy() &&
180 "Unary expressions can only be created for integer types");
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 createSub(ConstantInt::getNullValue(MaxType), V);
190 }
191
createOpNAry(__isl_take isl_ast_expr * Expr)192 Value *IslExprBuilder::createOpNAry(__isl_take isl_ast_expr *Expr) {
193 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");
197
198 CmpInst::Predicate Pred;
199 switch (isl_ast_expr_get_op_type(Expr)) {
200 default:
201 llvm_unreachable("This is not a an n-ary isl ast expression");
202 case isl_ast_op_max:
203 Pred = CmpInst::ICMP_SGT;
204 break;
205 case isl_ast_op_min:
206 Pred = CmpInst::ICMP_SLT;
207 break;
208 }
209
210 Value *V = create(isl_ast_expr_get_op_arg(Expr, 0));
211
212 for (int i = 1; i < isl_ast_expr_get_op_n_arg(Expr); ++i) {
213 Value *OpV = create(isl_ast_expr_get_op_arg(Expr, i));
214 Type *Ty = getWidestType(V->getType(), OpV->getType());
215
216 if (Ty != OpV->getType())
217 OpV = Builder.CreateSExt(OpV, Ty);
218
219 if (Ty != V->getType())
220 V = Builder.CreateSExt(V, Ty);
221
222 Value *Cmp = Builder.CreateICmp(Pred, V, OpV);
223 V = Builder.CreateSelect(Cmp, V, OpV);
224 }
225
226 // TODO: We can truncate the result, if it fits into a smaller type. This can
227 // help in cases where we have larger operands (e.g. i67) but the result is
228 // known to fit into i64. Without the truncation, the larger i67 type may
229 // force all subsequent operations to be performed on a non-native type.
230 isl_ast_expr_free(Expr);
231 return V;
232 }
233
234 std::pair<Value *, Type *>
createAccessAddress(__isl_take isl_ast_expr * Expr)235 IslExprBuilder::createAccessAddress(__isl_take isl_ast_expr *Expr) {
236 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
237 "isl ast expression not of type isl_ast_op");
238 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_access &&
239 "not an access isl ast expression");
240 assert(isl_ast_expr_get_op_n_arg(Expr) >= 1 &&
241 "We need at least two operands to create a member access.");
242
243 Value *Base, *IndexOp, *Access;
244 isl_ast_expr *BaseExpr;
245 isl_id *BaseId;
246
247 BaseExpr = isl_ast_expr_get_op_arg(Expr, 0);
248 BaseId = isl_ast_expr_get_id(BaseExpr);
249 isl_ast_expr_free(BaseExpr);
250
251 const ScopArrayInfo *SAI = nullptr;
252
253 if (PollyDebugPrinting)
254 RuntimeDebugBuilder::createCPUPrinter(Builder, isl_id_get_name(BaseId));
255
256 if (IDToSAI)
257 SAI = (*IDToSAI)[BaseId];
258
259 if (!SAI)
260 SAI = ScopArrayInfo::getFromId(isl::manage(BaseId));
261 else
262 isl_id_free(BaseId);
263
264 assert(SAI && "No ScopArrayInfo found for this isl_id.");
265
266 Base = SAI->getBasePtr();
267
268 if (auto NewBase = GlobalMap.lookup(Base))
269 Base = NewBase;
270
271 assert(Base->getType()->isPointerTy() && "Access base should be a pointer");
272 StringRef BaseName = Base->getName();
273
274 auto PointerTy = PointerType::get(SAI->getElementType(),
275 Base->getType()->getPointerAddressSpace());
276 if (Base->getType() != PointerTy) {
277 Base =
278 Builder.CreateBitCast(Base, PointerTy, "polly.access.cast." + BaseName);
279 }
280
281 if (isl_ast_expr_get_op_n_arg(Expr) == 1) {
282 isl_ast_expr_free(Expr);
283 if (PollyDebugPrinting)
284 RuntimeDebugBuilder::createCPUPrinter(Builder, "\n");
285 return {Base, SAI->getElementType()};
286 }
287
288 IndexOp = nullptr;
289 for (unsigned u = 1, e = isl_ast_expr_get_op_n_arg(Expr); u < e; u++) {
290 Value *NextIndex = create(isl_ast_expr_get_op_arg(Expr, u));
291 assert(NextIndex->getType()->isIntegerTy() &&
292 "Access index should be an integer");
293
294 if (PollyDebugPrinting)
295 RuntimeDebugBuilder::createCPUPrinter(Builder, "[", NextIndex, "]");
296
297 if (!IndexOp) {
298 IndexOp = NextIndex;
299 } else {
300 Type *Ty = getWidestType(NextIndex->getType(), IndexOp->getType());
301
302 if (Ty != NextIndex->getType())
303 NextIndex = Builder.CreateIntCast(NextIndex, Ty, true);
304 if (Ty != IndexOp->getType())
305 IndexOp = Builder.CreateIntCast(IndexOp, Ty, true);
306
307 IndexOp = createAdd(IndexOp, NextIndex, "polly.access.add." + BaseName);
308 }
309
310 // For every but the last dimension multiply the size, for the last
311 // dimension we can exit the loop.
312 if (u + 1 >= e)
313 break;
314
315 const SCEV *DimSCEV = SAI->getDimensionSize(u);
316
317 llvm::ValueToSCEVMapTy Map;
318 for (auto &KV : GlobalMap)
319 Map[KV.first] = SE.getSCEV(KV.second);
320 DimSCEV = SCEVParameterRewriter::rewrite(DimSCEV, SE, Map);
321 Value *DimSize =
322 expandCodeFor(S, SE, DL, "polly", DimSCEV, DimSCEV->getType(),
323 &*Builder.GetInsertPoint(), nullptr,
324 StartBlock->getSinglePredecessor());
325
326 Type *Ty = getWidestType(DimSize->getType(), IndexOp->getType());
327
328 if (Ty != IndexOp->getType())
329 IndexOp = Builder.CreateSExtOrTrunc(IndexOp, Ty,
330 "polly.access.sext." + BaseName);
331 if (Ty != DimSize->getType())
332 DimSize = Builder.CreateSExtOrTrunc(DimSize, Ty,
333 "polly.access.sext." + BaseName);
334 IndexOp = createMul(IndexOp, DimSize, "polly.access.mul." + BaseName);
335 }
336
337 Access = Builder.CreateGEP(SAI->getElementType(), Base, IndexOp,
338 "polly.access." + BaseName);
339
340 if (PollyDebugPrinting)
341 RuntimeDebugBuilder::createCPUPrinter(Builder, "\n");
342 isl_ast_expr_free(Expr);
343 return {Access, SAI->getElementType()};
344 }
345
createOpAccess(__isl_take isl_ast_expr * Expr)346 Value *IslExprBuilder::createOpAccess(__isl_take isl_ast_expr *Expr) {
347 auto Info = createAccessAddress(Expr);
348 assert(Info.first && "Could not create op access address");
349 return Builder.CreateLoad(Info.second, Info.first,
350 Info.first->getName() + ".load");
351 }
352
createOpBin(__isl_take isl_ast_expr * Expr)353 Value *IslExprBuilder::createOpBin(__isl_take isl_ast_expr *Expr) {
354 Value *LHS, *RHS, *Res;
355 Type *MaxType;
356 isl_ast_op_type OpType;
357
358 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
359 "isl ast expression not of type isl_ast_op");
360 assert(isl_ast_expr_get_op_n_arg(Expr) == 2 &&
361 "not a binary isl ast expression");
362
363 OpType = isl_ast_expr_get_op_type(Expr);
364
365 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
366 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
367
368 Type *LHSType = LHS->getType();
369 Type *RHSType = RHS->getType();
370
371 MaxType = getWidestType(LHSType, RHSType);
372
373 // Take the result into account when calculating the widest type.
374 //
375 // For operations such as '+' the result may require a type larger than
376 // the type of the individual operands. For other operations such as '/', the
377 // result type cannot be larger than the type of the individual operand. isl
378 // does not calculate correct types for these operations and we consequently
379 // exclude those operations here.
380 switch (OpType) {
381 case isl_ast_op_pdiv_q:
382 case isl_ast_op_pdiv_r:
383 case isl_ast_op_div:
384 case isl_ast_op_fdiv_q:
385 case isl_ast_op_zdiv_r:
386 // Do nothing
387 break;
388 case isl_ast_op_add:
389 case isl_ast_op_sub:
390 case isl_ast_op_mul:
391 MaxType = getWidestType(MaxType, getType(Expr));
392 break;
393 default:
394 llvm_unreachable("This is no binary isl ast expression");
395 }
396
397 if (MaxType != RHS->getType())
398 RHS = Builder.CreateSExt(RHS, MaxType);
399
400 if (MaxType != LHS->getType())
401 LHS = Builder.CreateSExt(LHS, MaxType);
402
403 switch (OpType) {
404 default:
405 llvm_unreachable("This is no binary isl ast expression");
406 case isl_ast_op_add:
407 Res = createAdd(LHS, RHS);
408 break;
409 case isl_ast_op_sub:
410 Res = createSub(LHS, RHS);
411 break;
412 case isl_ast_op_mul:
413 Res = createMul(LHS, RHS);
414 break;
415 case isl_ast_op_div:
416 Res = Builder.CreateSDiv(LHS, RHS, "pexp.div", true);
417 break;
418 case isl_ast_op_pdiv_q: // Dividend is non-negative
419 Res = Builder.CreateUDiv(LHS, RHS, "pexp.p_div_q");
420 break;
421 case isl_ast_op_fdiv_q: { // Round towards -infty
422 if (auto *Const = dyn_cast<ConstantInt>(RHS)) {
423 auto &Val = Const->getValue();
424 if (Val.isPowerOf2() && Val.isNonNegative()) {
425 Res = Builder.CreateAShr(LHS, Val.ceilLogBase2(), "polly.fdiv_q.shr");
426 break;
427 }
428 }
429 // TODO: Review code and check that this calculation does not yield
430 // incorrect overflow in some edge cases.
431 //
432 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
433 Value *One = ConstantInt::get(MaxType, 1);
434 Value *Zero = ConstantInt::get(MaxType, 0);
435 Value *Sum1 = createSub(LHS, RHS, "pexp.fdiv_q.0");
436 Value *Sum2 = createAdd(Sum1, One, "pexp.fdiv_q.1");
437 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero, "pexp.fdiv_q.2");
438 Value *Dividend =
439 Builder.CreateSelect(isNegative, Sum2, LHS, "pexp.fdiv_q.3");
440 Res = Builder.CreateSDiv(Dividend, RHS, "pexp.fdiv_q.4");
441 break;
442 }
443 case isl_ast_op_pdiv_r: // Dividend is non-negative
444 Res = Builder.CreateURem(LHS, RHS, "pexp.pdiv_r");
445 break;
446
447 case isl_ast_op_zdiv_r: // Result only compared against zero
448 Res = Builder.CreateSRem(LHS, RHS, "pexp.zdiv_r");
449 break;
450 }
451
452 // TODO: We can truncate the result, if it fits into a smaller type. This can
453 // help in cases where we have larger operands (e.g. i67) but the result is
454 // known to fit into i64. Without the truncation, the larger i67 type may
455 // force all subsequent operations to be performed on a non-native type.
456 isl_ast_expr_free(Expr);
457 return Res;
458 }
459
createOpSelect(__isl_take isl_ast_expr * Expr)460 Value *IslExprBuilder::createOpSelect(__isl_take isl_ast_expr *Expr) {
461 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_select &&
462 "Unsupported unary isl ast expression");
463 Value *LHS, *RHS, *Cond;
464 Type *MaxType = getType(Expr);
465
466 Cond = create(isl_ast_expr_get_op_arg(Expr, 0));
467 if (!Cond->getType()->isIntegerTy(1))
468 Cond = Builder.CreateIsNotNull(Cond);
469
470 LHS = create(isl_ast_expr_get_op_arg(Expr, 1));
471 RHS = create(isl_ast_expr_get_op_arg(Expr, 2));
472
473 MaxType = getWidestType(MaxType, LHS->getType());
474 MaxType = getWidestType(MaxType, RHS->getType());
475
476 if (MaxType != RHS->getType())
477 RHS = Builder.CreateSExt(RHS, MaxType);
478
479 if (MaxType != LHS->getType())
480 LHS = Builder.CreateSExt(LHS, MaxType);
481
482 // TODO: Do we want to truncate the result?
483 isl_ast_expr_free(Expr);
484 return Builder.CreateSelect(Cond, LHS, RHS);
485 }
486
createOpICmp(__isl_take isl_ast_expr * Expr)487 Value *IslExprBuilder::createOpICmp(__isl_take isl_ast_expr *Expr) {
488 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
489 "Expected an isl_ast_expr_op expression");
490
491 Value *LHS, *RHS, *Res;
492
493 auto *Op0 = isl_ast_expr_get_op_arg(Expr, 0);
494 auto *Op1 = isl_ast_expr_get_op_arg(Expr, 1);
495 bool HasNonAddressOfOperand =
496 isl_ast_expr_get_type(Op0) != isl_ast_expr_op ||
497 isl_ast_expr_get_type(Op1) != isl_ast_expr_op ||
498 isl_ast_expr_get_op_type(Op0) != isl_ast_op_address_of ||
499 isl_ast_expr_get_op_type(Op1) != isl_ast_op_address_of;
500
501 LHS = create(Op0);
502 RHS = create(Op1);
503
504 auto *LHSTy = LHS->getType();
505 auto *RHSTy = RHS->getType();
506 bool IsPtrType = LHSTy->isPointerTy() || RHSTy->isPointerTy();
507 bool UseUnsignedCmp = IsPtrType && !HasNonAddressOfOperand;
508
509 auto *PtrAsIntTy = Builder.getIntNTy(DL.getPointerSizeInBits());
510 if (LHSTy->isPointerTy())
511 LHS = Builder.CreatePtrToInt(LHS, PtrAsIntTy);
512 if (RHSTy->isPointerTy())
513 RHS = Builder.CreatePtrToInt(RHS, PtrAsIntTy);
514
515 if (LHS->getType() != RHS->getType()) {
516 Type *MaxType = LHS->getType();
517 MaxType = getWidestType(MaxType, RHS->getType());
518
519 if (MaxType != RHS->getType())
520 RHS = Builder.CreateSExt(RHS, MaxType);
521
522 if (MaxType != LHS->getType())
523 LHS = Builder.CreateSExt(LHS, MaxType);
524 }
525
526 isl_ast_op_type OpType = isl_ast_expr_get_op_type(Expr);
527 assert(OpType >= isl_ast_op_eq && OpType <= isl_ast_op_gt &&
528 "Unsupported ICmp isl ast expression");
529 static_assert(isl_ast_op_eq + 4 == isl_ast_op_gt,
530 "Isl ast op type interface changed");
531
532 CmpInst::Predicate Predicates[5][2] = {
533 {CmpInst::ICMP_EQ, CmpInst::ICMP_EQ},
534 {CmpInst::ICMP_SLE, CmpInst::ICMP_ULE},
535 {CmpInst::ICMP_SLT, CmpInst::ICMP_ULT},
536 {CmpInst::ICMP_SGE, CmpInst::ICMP_UGE},
537 {CmpInst::ICMP_SGT, CmpInst::ICMP_UGT},
538 };
539
540 Res = Builder.CreateICmp(Predicates[OpType - isl_ast_op_eq][UseUnsignedCmp],
541 LHS, RHS);
542
543 isl_ast_expr_free(Expr);
544 return Res;
545 }
546
createOpBoolean(__isl_take isl_ast_expr * Expr)547 Value *IslExprBuilder::createOpBoolean(__isl_take isl_ast_expr *Expr) {
548 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
549 "Expected an isl_ast_expr_op expression");
550
551 Value *LHS, *RHS, *Res;
552 isl_ast_op_type OpType;
553
554 OpType = isl_ast_expr_get_op_type(Expr);
555
556 assert((OpType == isl_ast_op_and || OpType == isl_ast_op_or) &&
557 "Unsupported isl_ast_op_type");
558
559 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
560 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
561
562 // Even though the isl pretty printer prints the expressions as 'exp && exp'
563 // or 'exp || exp', we actually code generate the bitwise expressions
564 // 'exp & exp' or 'exp | exp'. This forces the evaluation of both branches,
565 // but it is, due to the use of i1 types, otherwise equivalent. The reason
566 // to go for bitwise operations is, that we assume the reduced control flow
567 // will outweigh the overhead introduced by evaluating unneeded expressions.
568 // The isl code generation currently does not take advantage of the fact that
569 // the expression after an '||' or '&&' is in some cases not evaluated.
570 // Evaluating it anyways does not cause any undefined behaviour.
571 //
572 // TODO: Document in isl itself, that the unconditionally evaluating the
573 // second part of '||' or '&&' expressions is safe.
574 if (!LHS->getType()->isIntegerTy(1))
575 LHS = Builder.CreateIsNotNull(LHS);
576 if (!RHS->getType()->isIntegerTy(1))
577 RHS = Builder.CreateIsNotNull(RHS);
578
579 switch (OpType) {
580 default:
581 llvm_unreachable("Unsupported boolean expression");
582 case isl_ast_op_and:
583 Res = Builder.CreateAnd(LHS, RHS);
584 break;
585 case isl_ast_op_or:
586 Res = Builder.CreateOr(LHS, RHS);
587 break;
588 }
589
590 isl_ast_expr_free(Expr);
591 return Res;
592 }
593
594 Value *
createOpBooleanConditional(__isl_take isl_ast_expr * Expr)595 IslExprBuilder::createOpBooleanConditional(__isl_take isl_ast_expr *Expr) {
596 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
597 "Expected an isl_ast_expr_op expression");
598
599 Value *LHS, *RHS;
600 isl_ast_op_type OpType;
601
602 Function *F = Builder.GetInsertBlock()->getParent();
603 LLVMContext &Context = F->getContext();
604
605 OpType = isl_ast_expr_get_op_type(Expr);
606
607 assert((OpType == isl_ast_op_and_then || OpType == isl_ast_op_or_else) &&
608 "Unsupported isl_ast_op_type");
609
610 auto InsertBB = Builder.GetInsertBlock();
611 auto InsertPoint = Builder.GetInsertPoint();
612 auto NextBB = SplitBlock(InsertBB, &*InsertPoint, &DT, &LI);
613 BasicBlock *CondBB = BasicBlock::Create(Context, "polly.cond", F);
614 LI.changeLoopFor(CondBB, LI.getLoopFor(InsertBB));
615 DT.addNewBlock(CondBB, InsertBB);
616
617 InsertBB->getTerminator()->eraseFromParent();
618 Builder.SetInsertPoint(InsertBB);
619 auto BR = Builder.CreateCondBr(Builder.getTrue(), NextBB, CondBB);
620
621 Builder.SetInsertPoint(CondBB);
622 Builder.CreateBr(NextBB);
623
624 Builder.SetInsertPoint(InsertBB->getTerminator());
625
626 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
627 if (!LHS->getType()->isIntegerTy(1))
628 LHS = Builder.CreateIsNotNull(LHS);
629 auto LeftBB = Builder.GetInsertBlock();
630
631 if (OpType == isl_ast_op_and || OpType == isl_ast_op_and_then)
632 BR->setCondition(Builder.CreateNeg(LHS));
633 else
634 BR->setCondition(LHS);
635
636 Builder.SetInsertPoint(CondBB->getTerminator());
637 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
638 if (!RHS->getType()->isIntegerTy(1))
639 RHS = Builder.CreateIsNotNull(RHS);
640 auto RightBB = Builder.GetInsertBlock();
641
642 Builder.SetInsertPoint(NextBB->getTerminator());
643 auto PHI = Builder.CreatePHI(Builder.getInt1Ty(), 2);
644 PHI->addIncoming(OpType == isl_ast_op_and_then ? Builder.getFalse()
645 : Builder.getTrue(),
646 LeftBB);
647 PHI->addIncoming(RHS, RightBB);
648
649 isl_ast_expr_free(Expr);
650 return PHI;
651 }
652
createOp(__isl_take isl_ast_expr * Expr)653 Value *IslExprBuilder::createOp(__isl_take isl_ast_expr *Expr) {
654 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
655 "Expression not of type isl_ast_expr_op");
656 switch (isl_ast_expr_get_op_type(Expr)) {
657 case isl_ast_op_error:
658 case isl_ast_op_cond:
659 case isl_ast_op_call:
660 case isl_ast_op_member:
661 llvm_unreachable("Unsupported isl ast expression");
662 case isl_ast_op_access:
663 return createOpAccess(Expr);
664 case isl_ast_op_max:
665 case isl_ast_op_min:
666 return createOpNAry(Expr);
667 case isl_ast_op_add:
668 case isl_ast_op_sub:
669 case isl_ast_op_mul:
670 case isl_ast_op_div:
671 case isl_ast_op_fdiv_q: // Round towards -infty
672 case isl_ast_op_pdiv_q: // Dividend is non-negative
673 case isl_ast_op_pdiv_r: // Dividend is non-negative
674 case isl_ast_op_zdiv_r: // Result only compared against zero
675 return createOpBin(Expr);
676 case isl_ast_op_minus:
677 return createOpUnary(Expr);
678 case isl_ast_op_select:
679 return createOpSelect(Expr);
680 case isl_ast_op_and:
681 case isl_ast_op_or:
682 return createOpBoolean(Expr);
683 case isl_ast_op_and_then:
684 case isl_ast_op_or_else:
685 return createOpBooleanConditional(Expr);
686 case isl_ast_op_eq:
687 case isl_ast_op_le:
688 case isl_ast_op_lt:
689 case isl_ast_op_ge:
690 case isl_ast_op_gt:
691 return createOpICmp(Expr);
692 case isl_ast_op_address_of:
693 return createOpAddressOf(Expr);
694 }
695
696 llvm_unreachable("Unsupported isl_ast_expr_op kind.");
697 }
698
createOpAddressOf(__isl_take isl_ast_expr * Expr)699 Value *IslExprBuilder::createOpAddressOf(__isl_take isl_ast_expr *Expr) {
700 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
701 "Expected an isl_ast_expr_op expression.");
702 assert(isl_ast_expr_get_op_n_arg(Expr) == 1 && "Address of should be unary.");
703
704 isl_ast_expr *Op = isl_ast_expr_get_op_arg(Expr, 0);
705 assert(isl_ast_expr_get_type(Op) == isl_ast_expr_op &&
706 "Expected address of operator to be an isl_ast_expr_op expression.");
707 assert(isl_ast_expr_get_op_type(Op) == isl_ast_op_access &&
708 "Expected address of operator to be an access expression.");
709
710 Value *V = createAccessAddress(Op).first;
711
712 isl_ast_expr_free(Expr);
713
714 return V;
715 }
716
createId(__isl_take isl_ast_expr * Expr)717 Value *IslExprBuilder::createId(__isl_take isl_ast_expr *Expr) {
718 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_id &&
719 "Expression not of type isl_ast_expr_ident");
720
721 isl_id *Id;
722 Value *V;
723
724 Id = isl_ast_expr_get_id(Expr);
725
726 assert(IDToValue.count(Id) && "Identifier not found");
727
728 V = IDToValue[Id];
729 if (!V)
730 V = UndefValue::get(getType(Expr));
731
732 if (V->getType()->isPointerTy())
733 V = Builder.CreatePtrToInt(V, Builder.getIntNTy(DL.getPointerSizeInBits()));
734
735 assert(V && "Unknown parameter id found");
736
737 isl_id_free(Id);
738 isl_ast_expr_free(Expr);
739
740 return V;
741 }
742
getType(__isl_keep isl_ast_expr * Expr)743 IntegerType *IslExprBuilder::getType(__isl_keep isl_ast_expr *Expr) {
744 // XXX: We assume i64 is large enough. This is often true, but in general
745 // incorrect. Also, on 32bit architectures, it would be beneficial to
746 // use a smaller type. We can and should directly derive this information
747 // during code generation.
748 return IntegerType::get(Builder.getContext(), 64);
749 }
750
createInt(__isl_take isl_ast_expr * Expr)751 Value *IslExprBuilder::createInt(__isl_take isl_ast_expr *Expr) {
752 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_int &&
753 "Expression not of type isl_ast_expr_int");
754 isl_val *Val;
755 Value *V;
756 APInt APValue;
757 IntegerType *T;
758
759 Val = isl_ast_expr_get_val(Expr);
760 APValue = APIntFromVal(Val);
761
762 auto BitWidth = APValue.getBitWidth();
763 if (BitWidth <= 64)
764 T = getType(Expr);
765 else
766 T = Builder.getIntNTy(BitWidth);
767
768 APValue = APValue.sext(T->getBitWidth());
769 V = ConstantInt::get(T, APValue);
770
771 isl_ast_expr_free(Expr);
772 return V;
773 }
774
create(__isl_take isl_ast_expr * Expr)775 Value *IslExprBuilder::create(__isl_take isl_ast_expr *Expr) {
776 switch (isl_ast_expr_get_type(Expr)) {
777 case isl_ast_expr_error:
778 llvm_unreachable("Code generation error");
779 case isl_ast_expr_op:
780 return createOp(Expr);
781 case isl_ast_expr_id:
782 return createId(Expr);
783 case isl_ast_expr_int:
784 return createInt(Expr);
785 }
786
787 llvm_unreachable("Unexpected enum value");
788 }
789