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