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 /// @brief 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) >= 2 &&
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 = ScopArrayInfo::getFromId(BaseId);
227   Base = SAI->getBasePtr();
228 
229   if (auto NewBase = GlobalMap.lookup(Base))
230     Base = NewBase;
231 
232   assert(Base->getType()->isPointerTy() && "Access base should be a pointer");
233   StringRef BaseName = Base->getName();
234 
235   auto PointerTy = PointerType::get(SAI->getElementType(),
236                                     Base->getType()->getPointerAddressSpace());
237   if (Base->getType() != PointerTy) {
238     Base =
239         Builder.CreateBitCast(Base, PointerTy, "polly.access.cast." + BaseName);
240   }
241 
242   IndexOp = nullptr;
243   for (unsigned u = 1, e = isl_ast_expr_get_op_n_arg(Expr); u < e; u++) {
244     Value *NextIndex = create(isl_ast_expr_get_op_arg(Expr, u));
245     assert(NextIndex->getType()->isIntegerTy() &&
246            "Access index should be an integer");
247 
248     if (!IndexOp) {
249       IndexOp = NextIndex;
250     } else {
251       Type *Ty = getWidestType(NextIndex->getType(), IndexOp->getType());
252 
253       if (Ty != NextIndex->getType())
254         NextIndex = Builder.CreateIntCast(NextIndex, Ty, true);
255       if (Ty != IndexOp->getType())
256         IndexOp = Builder.CreateIntCast(IndexOp, Ty, true);
257 
258       IndexOp = createAdd(IndexOp, NextIndex, "polly.access.add." + BaseName);
259     }
260 
261     // For every but the last dimension multiply the size, for the last
262     // dimension we can exit the loop.
263     if (u + 1 >= e)
264       break;
265 
266     const SCEV *DimSCEV = SAI->getDimensionSize(u);
267 
268     llvm::ValueToValueMap Map(GlobalMap.begin(), GlobalMap.end());
269     DimSCEV = SCEVParameterRewriter::rewrite(DimSCEV, SE, Map);
270     Value *DimSize =
271         expandCodeFor(S, SE, DL, "polly", DimSCEV, DimSCEV->getType(),
272                       &*Builder.GetInsertPoint());
273 
274     Type *Ty = getWidestType(DimSize->getType(), IndexOp->getType());
275 
276     if (Ty != IndexOp->getType())
277       IndexOp = Builder.CreateSExtOrTrunc(IndexOp, Ty,
278                                           "polly.access.sext." + BaseName);
279     if (Ty != DimSize->getType())
280       DimSize = Builder.CreateSExtOrTrunc(DimSize, Ty,
281                                           "polly.access.sext." + BaseName);
282     IndexOp = createMul(IndexOp, DimSize, "polly.access.mul." + BaseName);
283   }
284 
285   Access = Builder.CreateGEP(Base, IndexOp, "polly.access." + BaseName);
286 
287   isl_ast_expr_free(Expr);
288   return Access;
289 }
290 
291 Value *IslExprBuilder::createOpAccess(isl_ast_expr *Expr) {
292   Value *Addr = createAccessAddress(Expr);
293   assert(Addr && "Could not create op access address");
294   return Builder.CreateLoad(Addr, Addr->getName() + ".load");
295 }
296 
297 Value *IslExprBuilder::createOpBin(__isl_take isl_ast_expr *Expr) {
298   Value *LHS, *RHS, *Res;
299   Type *MaxType;
300   isl_ast_op_type OpType;
301 
302   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
303          "isl ast expression not of type isl_ast_op");
304   assert(isl_ast_expr_get_op_n_arg(Expr) == 2 &&
305          "not a binary isl ast expression");
306 
307   OpType = isl_ast_expr_get_op_type(Expr);
308 
309   LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
310   RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
311 
312   Type *LHSType = LHS->getType();
313   Type *RHSType = RHS->getType();
314 
315   MaxType = getWidestType(LHSType, RHSType);
316 
317   // Take the result into account when calculating the widest type.
318   //
319   // For operations such as '+' the result may require a type larger than
320   // the type of the individual operands. For other operations such as '/', the
321   // result type cannot be larger than the type of the individual operand. isl
322   // does not calculate correct types for these operations and we consequently
323   // exclude those operations here.
324   switch (OpType) {
325   case isl_ast_op_pdiv_q:
326   case isl_ast_op_pdiv_r:
327   case isl_ast_op_div:
328   case isl_ast_op_fdiv_q:
329   case isl_ast_op_zdiv_r:
330     // Do nothing
331     break;
332   case isl_ast_op_add:
333   case isl_ast_op_sub:
334   case isl_ast_op_mul:
335     MaxType = getWidestType(MaxType, getType(Expr));
336     break;
337   default:
338     llvm_unreachable("This is no binary isl ast expression");
339   }
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   switch (OpType) {
348   default:
349     llvm_unreachable("This is no binary isl ast expression");
350   case isl_ast_op_add:
351     Res = createAdd(LHS, RHS);
352     break;
353   case isl_ast_op_sub:
354     Res = createSub(LHS, RHS);
355     break;
356   case isl_ast_op_mul:
357     Res = createMul(LHS, RHS);
358     break;
359   case isl_ast_op_div:
360     Res = Builder.CreateSDiv(LHS, RHS, "pexp.div", true);
361     break;
362   case isl_ast_op_pdiv_q: // Dividend is non-negative
363     Res = Builder.CreateUDiv(LHS, RHS, "pexp.p_div_q");
364     break;
365   case isl_ast_op_fdiv_q: { // Round towards -infty
366     if (auto *Const = dyn_cast<ConstantInt>(RHS)) {
367       auto &Val = Const->getValue();
368       if (Val.isPowerOf2() && Val.isNonNegative()) {
369         Res = Builder.CreateAShr(LHS, Val.ceilLogBase2(), "polly.fdiv_q.shr");
370         break;
371       }
372     }
373     // TODO: Review code and check that this calculation does not yield
374     //       incorrect overflow in some bordercases.
375     //
376     // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
377     Value *One = ConstantInt::get(MaxType, 1);
378     Value *Zero = ConstantInt::get(MaxType, 0);
379     Value *Sum1 = createSub(LHS, RHS, "pexp.fdiv_q.0");
380     Value *Sum2 = createAdd(Sum1, One, "pexp.fdiv_q.1");
381     Value *isNegative = Builder.CreateICmpSLT(LHS, Zero, "pexp.fdiv_q.2");
382     Value *Dividend =
383         Builder.CreateSelect(isNegative, Sum2, LHS, "pexp.fdiv_q.3");
384     Res = Builder.CreateSDiv(Dividend, RHS, "pexp.fdiv_q.4");
385     break;
386   }
387   case isl_ast_op_pdiv_r: // Dividend is non-negative
388     Res = Builder.CreateURem(LHS, RHS, "pexp.pdiv_r");
389     break;
390 
391   case isl_ast_op_zdiv_r: // Result only compared against zero
392     Res = Builder.CreateSRem(LHS, RHS, "pexp.zdiv_r");
393     break;
394   }
395 
396   // TODO: We can truncate the result, if it fits into a smaller type. This can
397   // help in cases where we have larger operands (e.g. i67) but the result is
398   // known to fit into i64. Without the truncation, the larger i67 type may
399   // force all subsequent operations to be performed on a non-native type.
400   isl_ast_expr_free(Expr);
401   return Res;
402 }
403 
404 Value *IslExprBuilder::createOpSelect(__isl_take isl_ast_expr *Expr) {
405   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_select &&
406          "Unsupported unary isl ast expression");
407   Value *LHS, *RHS, *Cond;
408   Type *MaxType = getType(Expr);
409 
410   Cond = create(isl_ast_expr_get_op_arg(Expr, 0));
411   if (!Cond->getType()->isIntegerTy(1))
412     Cond = Builder.CreateIsNotNull(Cond);
413 
414   LHS = create(isl_ast_expr_get_op_arg(Expr, 1));
415   RHS = create(isl_ast_expr_get_op_arg(Expr, 2));
416 
417   MaxType = getWidestType(MaxType, LHS->getType());
418   MaxType = getWidestType(MaxType, RHS->getType());
419 
420   if (MaxType != RHS->getType())
421     RHS = Builder.CreateSExt(RHS, MaxType);
422 
423   if (MaxType != LHS->getType())
424     LHS = Builder.CreateSExt(LHS, MaxType);
425 
426   // TODO: Do we want to truncate the result?
427   isl_ast_expr_free(Expr);
428   return Builder.CreateSelect(Cond, LHS, RHS);
429 }
430 
431 Value *IslExprBuilder::createOpICmp(__isl_take isl_ast_expr *Expr) {
432   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
433          "Expected an isl_ast_expr_op expression");
434 
435   Value *LHS, *RHS, *Res;
436 
437   auto *Op0 = isl_ast_expr_get_op_arg(Expr, 0);
438   auto *Op1 = isl_ast_expr_get_op_arg(Expr, 1);
439   bool HasNonAddressOfOperand =
440       isl_ast_expr_get_type(Op0) != isl_ast_expr_op ||
441       isl_ast_expr_get_type(Op1) != isl_ast_expr_op ||
442       isl_ast_expr_get_op_type(Op0) != isl_ast_op_address_of ||
443       isl_ast_expr_get_op_type(Op1) != isl_ast_op_address_of;
444 
445   LHS = create(Op0);
446   RHS = create(Op1);
447 
448   auto *LHSTy = LHS->getType();
449   auto *RHSTy = RHS->getType();
450   bool IsPtrType = LHSTy->isPointerTy() || RHSTy->isPointerTy();
451   bool UseUnsignedCmp = IsPtrType && !HasNonAddressOfOperand;
452 
453   auto *PtrAsIntTy = Builder.getIntNTy(DL.getPointerSizeInBits());
454   if (LHSTy->isPointerTy())
455     LHS = Builder.CreatePtrToInt(LHS, PtrAsIntTy);
456   if (RHSTy->isPointerTy())
457     RHS = Builder.CreatePtrToInt(RHS, PtrAsIntTy);
458 
459   if (LHS->getType() != RHS->getType()) {
460     Type *MaxType = LHS->getType();
461     MaxType = getWidestType(MaxType, RHS->getType());
462 
463     if (MaxType != RHS->getType())
464       RHS = Builder.CreateSExt(RHS, MaxType);
465 
466     if (MaxType != LHS->getType())
467       LHS = Builder.CreateSExt(LHS, MaxType);
468   }
469 
470   isl_ast_op_type OpType = isl_ast_expr_get_op_type(Expr);
471   assert(OpType >= isl_ast_op_eq && OpType <= isl_ast_op_gt &&
472          "Unsupported ICmp isl ast expression");
473   assert(isl_ast_op_eq + 4 == isl_ast_op_gt &&
474          "Isl ast op type interface changed");
475 
476   CmpInst::Predicate Predicates[5][2] = {
477       {CmpInst::ICMP_EQ, CmpInst::ICMP_EQ},
478       {CmpInst::ICMP_SLE, CmpInst::ICMP_ULE},
479       {CmpInst::ICMP_SLT, CmpInst::ICMP_ULT},
480       {CmpInst::ICMP_SGE, CmpInst::ICMP_UGE},
481       {CmpInst::ICMP_SGT, CmpInst::ICMP_UGT},
482   };
483 
484   Res = Builder.CreateICmp(Predicates[OpType - isl_ast_op_eq][UseUnsignedCmp],
485                            LHS, RHS);
486 
487   isl_ast_expr_free(Expr);
488   return Res;
489 }
490 
491 Value *IslExprBuilder::createOpBoolean(__isl_take isl_ast_expr *Expr) {
492   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
493          "Expected an isl_ast_expr_op expression");
494 
495   Value *LHS, *RHS, *Res;
496   isl_ast_op_type OpType;
497 
498   OpType = isl_ast_expr_get_op_type(Expr);
499 
500   assert((OpType == isl_ast_op_and || OpType == isl_ast_op_or) &&
501          "Unsupported isl_ast_op_type");
502 
503   LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
504   RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
505 
506   // Even though the isl pretty printer prints the expressions as 'exp && exp'
507   // or 'exp || exp', we actually code generate the bitwise expressions
508   // 'exp & exp' or 'exp | exp'. This forces the evaluation of both branches,
509   // but it is, due to the use of i1 types, otherwise equivalent. The reason
510   // to go for bitwise operations is, that we assume the reduced control flow
511   // will outweight the overhead introduced by evaluating unneeded expressions.
512   // The isl code generation currently does not take advantage of the fact that
513   // the expression after an '||' or '&&' is in some cases not evaluated.
514   // Evaluating it anyways does not cause any undefined behaviour.
515   //
516   // TODO: Document in isl itself, that the unconditionally evaluating the
517   // second part of '||' or '&&' expressions is safe.
518   if (!LHS->getType()->isIntegerTy(1))
519     LHS = Builder.CreateIsNotNull(LHS);
520   if (!RHS->getType()->isIntegerTy(1))
521     RHS = Builder.CreateIsNotNull(RHS);
522 
523   switch (OpType) {
524   default:
525     llvm_unreachable("Unsupported boolean expression");
526   case isl_ast_op_and:
527     Res = Builder.CreateAnd(LHS, RHS);
528     break;
529   case isl_ast_op_or:
530     Res = Builder.CreateOr(LHS, RHS);
531     break;
532   }
533 
534   isl_ast_expr_free(Expr);
535   return Res;
536 }
537 
538 Value *
539 IslExprBuilder::createOpBooleanConditional(__isl_take isl_ast_expr *Expr) {
540   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
541          "Expected an isl_ast_expr_op expression");
542 
543   Value *LHS, *RHS;
544   isl_ast_op_type OpType;
545 
546   Function *F = Builder.GetInsertBlock()->getParent();
547   LLVMContext &Context = F->getContext();
548 
549   OpType = isl_ast_expr_get_op_type(Expr);
550 
551   assert((OpType == isl_ast_op_and_then || OpType == isl_ast_op_or_else) &&
552          "Unsupported isl_ast_op_type");
553 
554   auto InsertBB = Builder.GetInsertBlock();
555   auto InsertPoint = Builder.GetInsertPoint();
556   auto NextBB = SplitBlock(InsertBB, &*InsertPoint, &DT, &LI);
557   BasicBlock *CondBB = BasicBlock::Create(Context, "polly.cond", F);
558   LI.changeLoopFor(CondBB, LI.getLoopFor(InsertBB));
559   DT.addNewBlock(CondBB, InsertBB);
560 
561   InsertBB->getTerminator()->eraseFromParent();
562   Builder.SetInsertPoint(InsertBB);
563   auto BR = Builder.CreateCondBr(Builder.getTrue(), NextBB, CondBB);
564 
565   Builder.SetInsertPoint(CondBB);
566   Builder.CreateBr(NextBB);
567 
568   Builder.SetInsertPoint(InsertBB->getTerminator());
569 
570   LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
571   if (!LHS->getType()->isIntegerTy(1))
572     LHS = Builder.CreateIsNotNull(LHS);
573   auto LeftBB = Builder.GetInsertBlock();
574 
575   if (OpType == isl_ast_op_and || OpType == isl_ast_op_and_then)
576     BR->setCondition(Builder.CreateNeg(LHS));
577   else
578     BR->setCondition(LHS);
579 
580   Builder.SetInsertPoint(CondBB->getTerminator());
581   RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
582   if (!RHS->getType()->isIntegerTy(1))
583     RHS = Builder.CreateIsNotNull(RHS);
584   auto RightBB = Builder.GetInsertBlock();
585 
586   Builder.SetInsertPoint(NextBB->getTerminator());
587   auto PHI = Builder.CreatePHI(Builder.getInt1Ty(), 2);
588   PHI->addIncoming(OpType == isl_ast_op_and_then ? Builder.getFalse()
589                                                  : Builder.getTrue(),
590                    LeftBB);
591   PHI->addIncoming(RHS, RightBB);
592 
593   isl_ast_expr_free(Expr);
594   return PHI;
595 }
596 
597 Value *IslExprBuilder::createOp(__isl_take isl_ast_expr *Expr) {
598   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
599          "Expression not of type isl_ast_expr_op");
600   switch (isl_ast_expr_get_op_type(Expr)) {
601   case isl_ast_op_error:
602   case isl_ast_op_cond:
603   case isl_ast_op_call:
604   case isl_ast_op_member:
605     llvm_unreachable("Unsupported isl ast expression");
606   case isl_ast_op_access:
607     return createOpAccess(Expr);
608   case isl_ast_op_max:
609   case isl_ast_op_min:
610     return createOpNAry(Expr);
611   case isl_ast_op_add:
612   case isl_ast_op_sub:
613   case isl_ast_op_mul:
614   case isl_ast_op_div:
615   case isl_ast_op_fdiv_q: // Round towards -infty
616   case isl_ast_op_pdiv_q: // Dividend is non-negative
617   case isl_ast_op_pdiv_r: // Dividend is non-negative
618   case isl_ast_op_zdiv_r: // Result only compared against zero
619     return createOpBin(Expr);
620   case isl_ast_op_minus:
621     return createOpUnary(Expr);
622   case isl_ast_op_select:
623     return createOpSelect(Expr);
624   case isl_ast_op_and:
625   case isl_ast_op_or:
626     return createOpBoolean(Expr);
627   case isl_ast_op_and_then:
628   case isl_ast_op_or_else:
629     return createOpBooleanConditional(Expr);
630   case isl_ast_op_eq:
631   case isl_ast_op_le:
632   case isl_ast_op_lt:
633   case isl_ast_op_ge:
634   case isl_ast_op_gt:
635     return createOpICmp(Expr);
636   case isl_ast_op_address_of:
637     return createOpAddressOf(Expr);
638   }
639 
640   llvm_unreachable("Unsupported isl_ast_expr_op kind.");
641 }
642 
643 Value *IslExprBuilder::createOpAddressOf(__isl_take isl_ast_expr *Expr) {
644   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
645          "Expected an isl_ast_expr_op expression.");
646   assert(isl_ast_expr_get_op_n_arg(Expr) == 1 && "Address of should be unary.");
647 
648   isl_ast_expr *Op = isl_ast_expr_get_op_arg(Expr, 0);
649   assert(isl_ast_expr_get_type(Op) == isl_ast_expr_op &&
650          "Expected address of operator to be an isl_ast_expr_op expression.");
651   assert(isl_ast_expr_get_op_type(Op) == isl_ast_op_access &&
652          "Expected address of operator to be an access expression.");
653 
654   Value *V = createAccessAddress(Op);
655 
656   isl_ast_expr_free(Expr);
657 
658   return V;
659 }
660 
661 Value *IslExprBuilder::createId(__isl_take isl_ast_expr *Expr) {
662   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_id &&
663          "Expression not of type isl_ast_expr_ident");
664 
665   isl_id *Id;
666   Value *V;
667 
668   Id = isl_ast_expr_get_id(Expr);
669 
670   assert(IDToValue.count(Id) && "Identifier not found");
671 
672   V = IDToValue[Id];
673   if (!V)
674     V = UndefValue::get(getType(Expr));
675 
676   if (V->getType()->isPointerTy())
677     V = Builder.CreatePtrToInt(V, Builder.getIntNTy(DL.getPointerSizeInBits()));
678 
679   assert(V && "Unknown parameter id found");
680 
681   isl_id_free(Id);
682   isl_ast_expr_free(Expr);
683 
684   return V;
685 }
686 
687 IntegerType *IslExprBuilder::getType(__isl_keep isl_ast_expr *Expr) {
688   // XXX: We assume i64 is large enough. This is often true, but in general
689   //      incorrect. Also, on 32bit architectures, it would be beneficial to
690   //      use a smaller type. We can and should directly derive this information
691   //      during code generation.
692   return IntegerType::get(Builder.getContext(), 64);
693 }
694 
695 Value *IslExprBuilder::createInt(__isl_take isl_ast_expr *Expr) {
696   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_int &&
697          "Expression not of type isl_ast_expr_int");
698   isl_val *Val;
699   Value *V;
700   APInt APValue;
701   IntegerType *T;
702 
703   Val = isl_ast_expr_get_val(Expr);
704   APValue = APIntFromVal(Val);
705 
706   auto BitWidth = APValue.getBitWidth();
707   if (BitWidth <= 64)
708     T = getType(Expr);
709   else
710     T = Builder.getIntNTy(BitWidth);
711 
712   APValue = APValue.sextOrSelf(T->getBitWidth());
713   V = ConstantInt::get(T, APValue);
714 
715   isl_ast_expr_free(Expr);
716   return V;
717 }
718 
719 Value *IslExprBuilder::create(__isl_take isl_ast_expr *Expr) {
720   switch (isl_ast_expr_get_type(Expr)) {
721   case isl_ast_expr_error:
722     llvm_unreachable("Code generation error");
723   case isl_ast_expr_op:
724     return createOp(Expr);
725   case isl_ast_expr_id:
726     return createId(Expr);
727   case isl_ast_expr_int:
728     return createInt(Expr);
729   }
730 
731   llvm_unreachable("Unexpected enum value");
732 }
733