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 
14 #include "polly/ScopInfo.h"
15 #include "polly/Support/GICHelper.h"
16 
17 #include "llvm/Analysis/ScalarEvolutionExpander.h"
18 #include "llvm/Support/Debug.h"
19 
20 using namespace llvm;
21 using namespace polly;
22 
23 Type *IslExprBuilder::getWidestType(Type *T1, Type *T2) {
24   assert(isa<IntegerType>(T1) && isa<IntegerType>(T2));
25 
26   if (T1->getPrimitiveSizeInBits() < T2->getPrimitiveSizeInBits())
27     return T2;
28   else
29     return T1;
30 }
31 
32 Value *IslExprBuilder::createOpUnary(__isl_take isl_ast_expr *Expr) {
33   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_minus &&
34          "Unsupported unary operation");
35 
36   Value *V;
37   Type *MaxType = getType(Expr);
38   assert(MaxType->isIntegerTy() &&
39          "Unary expressions can only be created for integer types");
40 
41   V = create(isl_ast_expr_get_op_arg(Expr, 0));
42   MaxType = getWidestType(MaxType, V->getType());
43 
44   if (MaxType != V->getType())
45     V = Builder.CreateSExt(V, MaxType);
46 
47   isl_ast_expr_free(Expr);
48   return Builder.CreateNSWNeg(V);
49 }
50 
51 Value *IslExprBuilder::createOpNAry(__isl_take isl_ast_expr *Expr) {
52   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
53          "isl ast expression not of type isl_ast_op");
54   assert(isl_ast_expr_get_op_n_arg(Expr) >= 2 &&
55          "We need at least two operands in an n-ary operation");
56 
57   Value *V;
58 
59   V = create(isl_ast_expr_get_op_arg(Expr, 0));
60 
61   for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr); ++i) {
62     Value *OpV;
63     OpV = create(isl_ast_expr_get_op_arg(Expr, i));
64 
65     Type *Ty = getWidestType(V->getType(), OpV->getType());
66 
67     if (Ty != OpV->getType())
68       OpV = Builder.CreateSExt(OpV, Ty);
69 
70     if (Ty != V->getType())
71       V = Builder.CreateSExt(V, Ty);
72 
73     switch (isl_ast_expr_get_op_type(Expr)) {
74     default:
75       llvm_unreachable("This is no n-ary isl ast expression");
76 
77     case isl_ast_op_max: {
78       Value *Cmp = Builder.CreateICmpSGT(V, OpV);
79       V = Builder.CreateSelect(Cmp, V, OpV);
80       continue;
81     }
82     case isl_ast_op_min: {
83       Value *Cmp = Builder.CreateICmpSLT(V, OpV);
84       V = Builder.CreateSelect(Cmp, V, OpV);
85       continue;
86     }
87     }
88   }
89 
90   // TODO: We can truncate the result, if it fits into a smaller type. This can
91   // help in cases where we have larger operands (e.g. i67) but the result is
92   // known to fit into i64. Without the truncation, the larger i67 type may
93   // force all subsequent operations to be performed on a non-native type.
94   isl_ast_expr_free(Expr);
95   return V;
96 }
97 
98 Value *IslExprBuilder::createAccessAddress(isl_ast_expr *Expr) {
99   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
100          "isl ast expression not of type isl_ast_op");
101   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_access &&
102          "not an access isl ast expression");
103   assert(isl_ast_expr_get_op_n_arg(Expr) >= 2 &&
104          "We need at least two operands to create a member access.");
105 
106   Value *Base, *IndexOp, *Access;
107   isl_ast_expr *BaseExpr;
108   isl_id *BaseId;
109 
110   BaseExpr = isl_ast_expr_get_op_arg(Expr, 0);
111   BaseId = isl_ast_expr_get_id(BaseExpr);
112   isl_ast_expr_free(BaseExpr);
113 
114   const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(BaseId);
115   Base = SAI->getBasePtr();
116   assert(Base->getType()->isPointerTy() && "Access base should be a pointer");
117   StringRef BaseName = Base->getName();
118 
119   if (Base->getType() != SAI->getType())
120     Base = Builder.CreateBitCast(Base, SAI->getType(),
121                                  "polly.access.cast." + BaseName);
122 
123   IndexOp = nullptr;
124   for (unsigned u = 1, e = isl_ast_expr_get_op_n_arg(Expr); u < e; u++) {
125     Value *NextIndex = create(isl_ast_expr_get_op_arg(Expr, u));
126     assert(NextIndex->getType()->isIntegerTy() &&
127            "Access index should be an integer");
128 
129     if (!IndexOp)
130       IndexOp = NextIndex;
131     else
132       IndexOp =
133           Builder.CreateAdd(IndexOp, NextIndex, "polly.access.add." + BaseName);
134 
135     // For every but the last dimension multiply the size, for the last
136     // dimension we can exit the loop.
137     if (u + 1 >= e)
138       break;
139 
140     const SCEV *DimSCEV = SAI->getDimensionSize(u - 1);
141     Value *DimSize = Expander.expandCodeFor(DimSCEV, DimSCEV->getType(),
142                                             Builder.GetInsertPoint());
143 
144     Type *Ty = getWidestType(DimSize->getType(), IndexOp->getType());
145 
146     if (Ty != IndexOp->getType())
147       IndexOp = Builder.CreateSExtOrTrunc(IndexOp, Ty,
148                                           "polly.access.sext." + BaseName);
149 
150     IndexOp =
151         Builder.CreateMul(IndexOp, DimSize, "polly.access.mul." + BaseName);
152   }
153 
154   Access = Builder.CreateGEP(Base, IndexOp, "polly.access." + BaseName);
155 
156   isl_ast_expr_free(Expr);
157   return Access;
158 }
159 
160 Value *IslExprBuilder::createOpAccess(isl_ast_expr *Expr) {
161   Value *Addr = createAccessAddress(Expr);
162   assert(Addr && "Could not create op access address");
163   return Builder.CreateLoad(Addr, Addr->getName() + ".load");
164 }
165 
166 Value *IslExprBuilder::createOpBin(__isl_take isl_ast_expr *Expr) {
167   Value *LHS, *RHS, *Res;
168   Type *MaxType;
169   isl_ast_expr *LOp, *ROp;
170   isl_ast_op_type OpType;
171 
172   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
173          "isl ast expression not of type isl_ast_op");
174   assert(isl_ast_expr_get_op_n_arg(Expr) == 2 &&
175          "not a binary isl ast expression");
176 
177   OpType = isl_ast_expr_get_op_type(Expr);
178 
179   LOp = isl_ast_expr_get_op_arg(Expr, 0);
180   ROp = isl_ast_expr_get_op_arg(Expr, 1);
181 
182   // Catch the special case ((-<pointer>) + <pointer>) which is for
183   // isl the same as (<pointer> - <pointer>). We have to treat it here because
184   // there is no valid semantics for the (-<pointer>) expression, hence in
185   // createOpUnary such an expression will trigger a crash.
186   // FIXME: The same problem can now be triggered by a subexpression of the LHS,
187   //        however it is much less likely.
188   if (OpType == isl_ast_op_add &&
189       isl_ast_expr_get_type(LOp) == isl_ast_expr_op &&
190       isl_ast_expr_get_op_type(LOp) == isl_ast_op_minus) {
191     // Change the binary addition to a substraction.
192     OpType = isl_ast_op_sub;
193 
194     // Extract the unary operand of the LHS.
195     auto *LOpOp = isl_ast_expr_get_op_arg(LOp, 0);
196     isl_ast_expr_free(LOp);
197 
198     // Swap the unary operand of the LHS and the RHS.
199     LOp = ROp;
200     ROp = LOpOp;
201   }
202 
203   LHS = create(LOp);
204   RHS = create(ROp);
205 
206   Type *LHSType = LHS->getType();
207   Type *RHSType = RHS->getType();
208 
209   // Handle <pointer> - <pointer>
210   if (LHSType->isPointerTy() && RHSType->isPointerTy()) {
211     isl_ast_expr_free(Expr);
212     assert(OpType == isl_ast_op_sub && "Substraction is the only valid binary "
213                                        "pointer <-> pointer operation.");
214 
215     return Builder.CreatePtrDiff(LHS, RHS);
216   }
217 
218   // Handle <pointer> +/- <integer> and <integer> +/- <pointer>
219   if (LHSType->isPointerTy() || RHSType->isPointerTy()) {
220     isl_ast_expr_free(Expr);
221 
222     assert((LHSType->isIntegerTy() || RHSType->isIntegerTy()) &&
223            "Arithmetic operations might only performed on one but not two "
224            "pointer types.");
225 
226     if (LHSType->isIntegerTy())
227       std::swap(LHS, RHS);
228 
229     switch (OpType) {
230     default:
231       llvm_unreachable(
232           "Only additive binary operations are allowed on pointer types.");
233     case isl_ast_op_sub:
234       RHS = Builder.CreateNeg(RHS);
235     // Fall through
236     case isl_ast_op_add:
237       return Builder.CreateGEP(LHS, RHS);
238     }
239   }
240 
241   MaxType = getWidestType(LHSType, RHSType);
242 
243   // Take the result into account when calculating the widest type.
244   //
245   // For operations such as '+' the result may require a type larger than
246   // the type of the individual operands. For other operations such as '/', the
247   // result type cannot be larger than the type of the individual operand. isl
248   // does not calculate correct types for these operations and we consequently
249   // exclude those operations here.
250   switch (OpType) {
251   case isl_ast_op_pdiv_q:
252   case isl_ast_op_pdiv_r:
253   case isl_ast_op_div:
254   case isl_ast_op_fdiv_q:
255   case isl_ast_op_zdiv_r:
256     // Do nothing
257     break;
258   case isl_ast_op_add:
259   case isl_ast_op_sub:
260   case isl_ast_op_mul:
261     MaxType = getWidestType(MaxType, getType(Expr));
262     break;
263   default:
264     llvm_unreachable("This is no binary isl ast expression");
265   }
266 
267   if (MaxType != RHS->getType())
268     RHS = Builder.CreateSExt(RHS, MaxType);
269 
270   if (MaxType != LHS->getType())
271     LHS = Builder.CreateSExt(LHS, MaxType);
272 
273   switch (OpType) {
274   default:
275     llvm_unreachable("This is no binary isl ast expression");
276   case isl_ast_op_add:
277     Res = Builder.CreateNSWAdd(LHS, RHS);
278     break;
279   case isl_ast_op_sub:
280     Res = Builder.CreateNSWSub(LHS, RHS);
281     break;
282   case isl_ast_op_mul:
283     Res = Builder.CreateNSWMul(LHS, RHS);
284     break;
285   case isl_ast_op_div:
286   case isl_ast_op_pdiv_q: // Dividend is non-negative
287     Res = Builder.CreateSDiv(LHS, RHS);
288     break;
289   case isl_ast_op_fdiv_q: { // Round towards -infty
290     // TODO: Review code and check that this calculation does not yield
291     //       incorrect overflow in some bordercases.
292     //
293     // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
294     Value *One = ConstantInt::get(MaxType, 1);
295     Value *Zero = ConstantInt::get(MaxType, 0);
296     Value *Sum1 = Builder.CreateSub(LHS, RHS);
297     Value *Sum2 = Builder.CreateAdd(Sum1, One);
298     Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
299     Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
300     Res = Builder.CreateSDiv(Dividend, RHS);
301     break;
302   }
303   case isl_ast_op_pdiv_r: // Dividend is non-negative
304   case isl_ast_op_zdiv_r: // Result only compared against zero
305     Res = Builder.CreateSRem(LHS, RHS);
306     break;
307   }
308 
309   // TODO: We can truncate the result, if it fits into a smaller type. This can
310   // help in cases where we have larger operands (e.g. i67) but the result is
311   // known to fit into i64. Without the truncation, the larger i67 type may
312   // force all subsequent operations to be performed on a non-native type.
313   isl_ast_expr_free(Expr);
314   return Res;
315 }
316 
317 Value *IslExprBuilder::createOpSelect(__isl_take isl_ast_expr *Expr) {
318   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_select &&
319          "Unsupported unary isl ast expression");
320   Value *LHS, *RHS, *Cond;
321   Type *MaxType = getType(Expr);
322 
323   Cond = create(isl_ast_expr_get_op_arg(Expr, 0));
324   if (!Cond->getType()->isIntegerTy(1))
325     Cond = Builder.CreateIsNotNull(Cond);
326 
327   LHS = create(isl_ast_expr_get_op_arg(Expr, 1));
328   RHS = create(isl_ast_expr_get_op_arg(Expr, 2));
329 
330   MaxType = getWidestType(MaxType, LHS->getType());
331   MaxType = getWidestType(MaxType, RHS->getType());
332 
333   if (MaxType != RHS->getType())
334     RHS = Builder.CreateSExt(RHS, MaxType);
335 
336   if (MaxType != LHS->getType())
337     LHS = Builder.CreateSExt(LHS, MaxType);
338 
339   // TODO: Do we want to truncate the result?
340   isl_ast_expr_free(Expr);
341   return Builder.CreateSelect(Cond, LHS, RHS);
342 }
343 
344 Value *IslExprBuilder::createOpICmp(__isl_take isl_ast_expr *Expr) {
345   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
346          "Expected an isl_ast_expr_op expression");
347 
348   Value *LHS, *RHS, *Res;
349 
350   LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
351   RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
352 
353   bool IsPtrType =
354       LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy();
355 
356   if (LHS->getType() != RHS->getType()) {
357     if (IsPtrType) {
358       Type *I8PtrTy = Builder.getInt8PtrTy();
359       if (!LHS->getType()->isPointerTy())
360         LHS = Builder.CreateIntToPtr(LHS, I8PtrTy);
361       if (!RHS->getType()->isPointerTy())
362         RHS = Builder.CreateIntToPtr(RHS, I8PtrTy);
363       if (LHS->getType() != I8PtrTy)
364         LHS = Builder.CreateBitCast(LHS, I8PtrTy);
365       if (RHS->getType() != I8PtrTy)
366         RHS = Builder.CreateBitCast(RHS, I8PtrTy);
367     } else {
368       Type *MaxType = LHS->getType();
369       MaxType = getWidestType(MaxType, RHS->getType());
370 
371       if (MaxType != RHS->getType())
372         RHS = Builder.CreateSExt(RHS, MaxType);
373 
374       if (MaxType != LHS->getType())
375         LHS = Builder.CreateSExt(LHS, MaxType);
376     }
377   }
378 
379   isl_ast_op_type OpType = isl_ast_expr_get_op_type(Expr);
380   assert(OpType >= isl_ast_op_eq && OpType <= isl_ast_op_gt &&
381          "Unsupported ICmp isl ast expression");
382   assert(isl_ast_op_eq + 4 == isl_ast_op_gt &&
383          "Isl ast op type interface changed");
384 
385   CmpInst::Predicate Predicates[5][2] = {
386       {CmpInst::ICMP_EQ, CmpInst::ICMP_EQ},
387       {CmpInst::ICMP_SLE, CmpInst::ICMP_ULE},
388       {CmpInst::ICMP_SLT, CmpInst::ICMP_ULT},
389       {CmpInst::ICMP_SGE, CmpInst::ICMP_UGE},
390       {CmpInst::ICMP_SGT, CmpInst::ICMP_UGT},
391   };
392 
393   Res = Builder.CreateICmp(Predicates[OpType - isl_ast_op_eq][IsPtrType], LHS,
394                            RHS);
395 
396   isl_ast_expr_free(Expr);
397   return Res;
398 }
399 
400 Value *IslExprBuilder::createOpBoolean(__isl_take isl_ast_expr *Expr) {
401   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
402          "Expected an isl_ast_expr_op expression");
403 
404   Value *LHS, *RHS, *Res;
405   isl_ast_op_type OpType;
406 
407   OpType = isl_ast_expr_get_op_type(Expr);
408 
409   assert((OpType == isl_ast_op_and || OpType == isl_ast_op_or) &&
410          "Unsupported isl_ast_op_type");
411 
412   LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
413   RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
414 
415   // Even though the isl pretty printer prints the expressions as 'exp && exp'
416   // or 'exp || exp', we actually code generate the bitwise expressions
417   // 'exp & exp' or 'exp | exp'. This forces the evaluation of both branches,
418   // but it is, due to the use of i1 types, otherwise equivalent. The reason
419   // to go for bitwise operations is, that we assume the reduced control flow
420   // will outweight the overhead introduced by evaluating unneeded expressions.
421   // The isl code generation currently does not take advantage of the fact that
422   // the expression after an '||' or '&&' is in some cases not evaluated.
423   // Evaluating it anyways does not cause any undefined behaviour.
424   //
425   // TODO: Document in isl itself, that the unconditionally evaluating the
426   // second part of '||' or '&&' expressions is safe.
427   if (!LHS->getType()->isIntegerTy(1))
428     LHS = Builder.CreateIsNotNull(LHS);
429   if (!RHS->getType()->isIntegerTy(1))
430     RHS = Builder.CreateIsNotNull(RHS);
431 
432   switch (OpType) {
433   default:
434     llvm_unreachable("Unsupported boolean expression");
435   case isl_ast_op_and:
436     Res = Builder.CreateAnd(LHS, RHS);
437     break;
438   case isl_ast_op_or:
439     Res = Builder.CreateOr(LHS, RHS);
440     break;
441   }
442 
443   isl_ast_expr_free(Expr);
444   return Res;
445 }
446 
447 Value *IslExprBuilder::createOp(__isl_take isl_ast_expr *Expr) {
448   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
449          "Expression not of type isl_ast_expr_op");
450   switch (isl_ast_expr_get_op_type(Expr)) {
451   case isl_ast_op_error:
452   case isl_ast_op_cond:
453   case isl_ast_op_and_then:
454   case isl_ast_op_or_else:
455   case isl_ast_op_call:
456   case isl_ast_op_member:
457     llvm_unreachable("Unsupported isl ast expression");
458   case isl_ast_op_access:
459     return createOpAccess(Expr);
460   case isl_ast_op_max:
461   case isl_ast_op_min:
462     return createOpNAry(Expr);
463   case isl_ast_op_add:
464   case isl_ast_op_sub:
465   case isl_ast_op_mul:
466   case isl_ast_op_div:
467   case isl_ast_op_fdiv_q: // Round towards -infty
468   case isl_ast_op_pdiv_q: // Dividend is non-negative
469   case isl_ast_op_pdiv_r: // Dividend is non-negative
470   case isl_ast_op_zdiv_r: // Result only compared against zero
471     return createOpBin(Expr);
472   case isl_ast_op_minus:
473     return createOpUnary(Expr);
474   case isl_ast_op_select:
475     return createOpSelect(Expr);
476   case isl_ast_op_and:
477   case isl_ast_op_or:
478     return createOpBoolean(Expr);
479   case isl_ast_op_eq:
480   case isl_ast_op_le:
481   case isl_ast_op_lt:
482   case isl_ast_op_ge:
483   case isl_ast_op_gt:
484     return createOpICmp(Expr);
485   case isl_ast_op_address_of:
486     return createOpAddressOf(Expr);
487   }
488 
489   llvm_unreachable("Unsupported isl_ast_expr_op kind.");
490 }
491 
492 Value *IslExprBuilder::createOpAddressOf(__isl_take isl_ast_expr *Expr) {
493   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
494          "Expected an isl_ast_expr_op expression.");
495   assert(isl_ast_expr_get_op_n_arg(Expr) == 1 && "Address of should be unary.");
496 
497   isl_ast_expr *Op = isl_ast_expr_get_op_arg(Expr, 0);
498   assert(isl_ast_expr_get_type(Op) == isl_ast_expr_op &&
499          "Expected address of operator to be an isl_ast_expr_op expression.");
500   assert(isl_ast_expr_get_op_type(Op) == isl_ast_op_access &&
501          "Expected address of operator to be an access expression.");
502 
503   Value *V = createAccessAddress(Op);
504 
505   isl_ast_expr_free(Expr);
506 
507   return V;
508 }
509 
510 Value *IslExprBuilder::createId(__isl_take isl_ast_expr *Expr) {
511   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_id &&
512          "Expression not of type isl_ast_expr_ident");
513 
514   isl_id *Id;
515   Value *V;
516 
517   Id = isl_ast_expr_get_id(Expr);
518 
519   assert(IDToValue.count(Id) && "Identifier not found");
520 
521   V = IDToValue[Id];
522 
523   isl_id_free(Id);
524   isl_ast_expr_free(Expr);
525 
526   return V;
527 }
528 
529 IntegerType *IslExprBuilder::getType(__isl_keep isl_ast_expr *Expr) {
530   // XXX: We assume i64 is large enough. This is often true, but in general
531   //      incorrect. Also, on 32bit architectures, it would be beneficial to
532   //      use a smaller type. We can and should directly derive this information
533   //      during code generation.
534   return IntegerType::get(Builder.getContext(), 64);
535 }
536 
537 Value *IslExprBuilder::createInt(__isl_take isl_ast_expr *Expr) {
538   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_int &&
539          "Expression not of type isl_ast_expr_int");
540   isl_val *Val;
541   Value *V;
542   APInt APValue;
543   IntegerType *T;
544 
545   Val = isl_ast_expr_get_val(Expr);
546   APValue = APIntFromVal(Val);
547   T = getType(Expr);
548   APValue = APValue.sextOrSelf(T->getBitWidth());
549   V = ConstantInt::get(T, APValue);
550 
551   isl_ast_expr_free(Expr);
552   return V;
553 }
554 
555 Value *IslExprBuilder::create(__isl_take isl_ast_expr *Expr) {
556   switch (isl_ast_expr_get_type(Expr)) {
557   case isl_ast_expr_error:
558     llvm_unreachable("Code generation error");
559   case isl_ast_expr_op:
560     return createOp(Expr);
561   case isl_ast_expr_id:
562     return createId(Expr);
563   case isl_ast_expr_int:
564     return createInt(Expr);
565   }
566 
567   llvm_unreachable("Unexpected enum value");
568 }
569