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