blob: 12b724c8f7bf4809aaee4523d372d7d76a9df51f [file] [log] [blame]
Johannes Doerfert13c5c642014-07-29 21:06:081//===------ IslExprBuilder.cpp ----- Code generate isl AST expressions ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:563// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Johannes Doerfert13c5c642014-07-29 21:06:086//
7//===----------------------------------------------------------------------===//
8//
9//===----------------------------------------------------------------------===//
10
11#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser1be726a2017-03-18 20:54:4312#include "polly/CodeGen/RuntimeDebugBuilder.h"
Johannes Doerfert404a0f82016-05-12 15:12:4313#include "polly/Options.h"
Johannes Doerfert1a28a892014-10-05 11:32:1814#include "polly/ScopInfo.h"
Johannes Doerfert13c5c642014-07-29 21:06:0815#include "polly/Support/GICHelper.h"
Tobias Grosserb021a4f2015-03-04 18:14:5916#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Johannes Doerfert13c5c642014-07-29 21:06:0817
18using namespace llvm;
19using namespace polly;
20
Tobias Grosserc80d6972016-09-02 06:33:3321/// Different overflow tracking modes.
Johannes Doerfert404a0f82016-05-12 15:12:4322enum OverflowTrackingChoice {
23 OT_NEVER, ///< Never tack potential overflows.
24 OT_REQUEST, ///< Track potential overflows if requested.
25 OT_ALWAYS ///< Always track potential overflows.
26};
27
28static cl::opt<OverflowTrackingChoice> OTMode(
29 "polly-overflow-tracking",
30 cl::desc("Define where potential integer overflows in generated "
31 "expressions should be tracked."),
32 cl::values(clEnumValN(OT_NEVER, "never", "Never track the overflow bit."),
33 clEnumValN(OT_REQUEST, "request",
34 "Track the overflow bit if requested."),
35 clEnumValN(OT_ALWAYS, "always",
Mehdi Amini732afdd2016-10-08 19:41:0636 "Always track the overflow bit.")),
Fangrui Song95a13422022-06-05 08:07:5037 cl::Hidden, cl::init(OT_REQUEST), cl::cat(PollyCategory));
Johannes Doerfert404a0f82016-05-12 15:12:4338
39IslExprBuilder::IslExprBuilder(Scop &S, PollyIRBuilder &Builder,
40 IDToValueTy &IDToValue, ValueMapT &GlobalMap,
41 const DataLayout &DL, ScalarEvolution &SE,
Eli Friedmanacf80062016-11-02 22:32:2342 DominatorTree &DT, LoopInfo &LI,
43 BasicBlock *StartBlock)
Johannes Doerfert404a0f82016-05-12 15:12:4344 : S(S), Builder(Builder), IDToValue(IDToValue), GlobalMap(GlobalMap),
Eli Friedmanacf80062016-11-02 22:32:2345 DL(DL), SE(SE), DT(DT), LI(LI), StartBlock(StartBlock) {
Johannes Doerfert404a0f82016-05-12 15:12:4346 OverflowState = (OTMode == OT_ALWAYS) ? Builder.getFalse() : nullptr;
47}
48
49void IslExprBuilder::setTrackOverflow(bool Enable) {
50 // If potential overflows are tracked always or never we ignore requests
Michael Krusea6d48f52017-06-08 12:06:1551 // to change the behavior.
Johannes Doerfert404a0f82016-05-12 15:12:4352 if (OTMode != OT_REQUEST)
53 return;
54
55 if (Enable) {
56 // If tracking should be enabled initialize the OverflowState.
57 OverflowState = Builder.getFalse();
58 } else {
59 // If tracking should be disabled just unset the OverflowState.
60 OverflowState = nullptr;
61 }
62}
63
64Value *IslExprBuilder::getOverflowState() const {
65 // If the overflow tracking was requested but it is disabled we avoid the
66 // additional nullptr checks at the call sides but instead provide a
67 // meaningful result.
68 if (OTMode == OT_NEVER)
69 return Builder.getFalse();
70 return OverflowState;
71}
72
Tobias Grosser75d133f2017-09-23 15:32:0773bool IslExprBuilder::hasLargeInts(isl::ast_expr Expr) {
74 enum isl_ast_expr_type Type = isl_ast_expr_get_type(Expr.get());
75
76 if (Type == isl_ast_expr_id)
77 return false;
78
79 if (Type == isl_ast_expr_int) {
80 isl::val Val = Expr.get_val();
81 APInt APValue = APIntFromVal(Val);
82 auto BitWidth = APValue.getBitWidth();
83 return BitWidth >= 64;
84 }
85
86 assert(Type == isl_ast_expr_op && "Expected isl_ast_expr of type operation");
87
88 int NumArgs = isl_ast_expr_get_op_n_arg(Expr.get());
89
90 for (int i = 0; i < NumArgs; i++) {
91 isl::ast_expr Operand = Expr.get_op_arg(i);
92 if (hasLargeInts(Operand))
93 return true;
94 }
95
96 return false;
97}
98
Johannes Doerfert404a0f82016-05-12 15:12:4399Value *IslExprBuilder::createBinOp(BinaryOperator::BinaryOps Opc, Value *LHS,
100 Value *RHS, const Twine &Name) {
Tobias Grosser3717aa52016-06-11 19:17:15101 // Handle the plain operation (without overflow tracking) first.
102 if (!OverflowState) {
Johannes Doerfert404a0f82016-05-12 15:12:43103 switch (Opc) {
104 case Instruction::Add:
105 return Builder.CreateNSWAdd(LHS, RHS, Name);
106 case Instruction::Sub:
107 return Builder.CreateNSWSub(LHS, RHS, Name);
108 case Instruction::Mul:
109 return Builder.CreateNSWMul(LHS, RHS, Name);
110 default:
111 llvm_unreachable("Unknown binary operator!");
112 }
113 }
114
115 Function *F = nullptr;
116 Module *M = Builder.GetInsertBlock()->getModule();
117 switch (Opc) {
118 case Instruction::Add:
119 F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow,
120 {LHS->getType()});
121 break;
122 case Instruction::Sub:
123 F = Intrinsic::getDeclaration(M, Intrinsic::ssub_with_overflow,
124 {LHS->getType()});
125 break;
126 case Instruction::Mul:
127 F = Intrinsic::getDeclaration(M, Intrinsic::smul_with_overflow,
128 {LHS->getType()});
129 break;
130 default:
131 llvm_unreachable("No overflow intrinsic for binary operator found!");
132 }
133
134 auto *ResultStruct = Builder.CreateCall(F, {LHS, RHS}, Name);
135 assert(ResultStruct->getType()->isStructTy());
136
137 auto *OverflowFlag =
138 Builder.CreateExtractValue(ResultStruct, 1, Name + ".obit");
139
140 // If all overflows are tracked we do not combine the results as this could
141 // cause dominance problems. Instead we will always keep the last overflow
142 // flag as current state.
143 if (OTMode == OT_ALWAYS)
144 OverflowState = OverflowFlag;
145 else
146 OverflowState =
147 Builder.CreateOr(OverflowState, OverflowFlag, "polly.overflow.state");
148
149 return Builder.CreateExtractValue(ResultStruct, 0, Name + ".res");
150}
151
152Value *IslExprBuilder::createAdd(Value *LHS, Value *RHS, const Twine &Name) {
153 return createBinOp(Instruction::Add, LHS, RHS, Name);
154}
155
156Value *IslExprBuilder::createSub(Value *LHS, Value *RHS, const Twine &Name) {
157 return createBinOp(Instruction::Sub, LHS, RHS, Name);
158}
159
160Value *IslExprBuilder::createMul(Value *LHS, Value *RHS, const Twine &Name) {
161 return createBinOp(Instruction::Mul, LHS, RHS, Name);
162}
163
Tobias Grosser3717aa52016-06-11 19:17:15164Type *IslExprBuilder::getWidestType(Type *T1, Type *T2) {
Johannes Doerfert13c5c642014-07-29 21:06:08165 assert(isa<IntegerType>(T1) && isa<IntegerType>(T2));
166
167 if (T1->getPrimitiveSizeInBits() < T2->getPrimitiveSizeInBits())
168 return T2;
169 else
170 return T1;
171}
172
173Value *IslExprBuilder::createOpUnary(__isl_take isl_ast_expr *Expr) {
174 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_minus &&
175 "Unsupported unary operation");
176
Tobias Grosser3717aa52016-06-11 19:17:15177 Value *V;
178 Type *MaxType = getType(Expr);
179 assert(MaxType->isIntegerTy() &&
Johannes Doerfert0837c2d2015-02-02 15:25:09180 "Unary expressions can only be created for integer types");
Johannes Doerfert13c5c642014-07-29 21:06:08181
Tobias Grosser3717aa52016-06-11 19:17:15182 V = create(isl_ast_expr_get_op_arg(Expr, 0));
183 MaxType = getWidestType(MaxType, V->getType());
184
185 if (MaxType != V->getType())
186 V = Builder.CreateSExt(V, MaxType);
187
Johannes Doerfert13c5c642014-07-29 21:06:08188 isl_ast_expr_free(Expr);
Tobias Grosser3717aa52016-06-11 19:17:15189 return createSub(ConstantInt::getNullValue(MaxType), V);
Johannes Doerfert13c5c642014-07-29 21:06:08190}
191
192Value *IslExprBuilder::createOpNAry(__isl_take isl_ast_expr *Expr) {
193 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
194 "isl ast expression not of type isl_ast_op");
195 assert(isl_ast_expr_get_op_n_arg(Expr) >= 2 &&
196 "We need at least two operands in an n-ary operation");
197
Tobias Grosser43de1782016-06-12 04:49:41198 CmpInst::Predicate Pred;
199 switch (isl_ast_expr_get_op_type(Expr)) {
200 default:
201 llvm_unreachable("This is not a an n-ary isl ast expression");
202 case isl_ast_op_max:
203 Pred = CmpInst::ICMP_SGT;
204 break;
205 case isl_ast_op_min:
206 Pred = CmpInst::ICMP_SLT;
207 break;
208 }
Johannes Doerfert13c5c642014-07-29 21:06:08209
Tobias Grosser43de1782016-06-12 04:49:41210 Value *V = create(isl_ast_expr_get_op_arg(Expr, 0));
Tobias Grosser3717aa52016-06-11 19:17:15211
Tobias Grosser43de1782016-06-12 04:49:41212 for (int i = 1; i < isl_ast_expr_get_op_n_arg(Expr); ++i) {
213 Value *OpV = create(isl_ast_expr_get_op_arg(Expr, i));
Tobias Grosser3717aa52016-06-11 19:17:15214 Type *Ty = getWidestType(V->getType(), OpV->getType());
215
216 if (Ty != OpV->getType())
217 OpV = Builder.CreateSExt(OpV, Ty);
218
219 if (Ty != V->getType())
220 V = Builder.CreateSExt(V, Ty);
221
Tobias Grosser43de1782016-06-12 04:49:41222 Value *Cmp = Builder.CreateICmp(Pred, V, OpV);
223 V = Builder.CreateSelect(Cmp, V, OpV);
Johannes Doerfert13c5c642014-07-29 21:06:08224 }
225
Tobias Grosser3717aa52016-06-11 19:17:15226 // TODO: We can truncate the result, if it fits into a smaller type. This can
227 // help in cases where we have larger operands (e.g. i67) but the result is
228 // known to fit into i64. Without the truncation, the larger i67 type may
229 // force all subsequent operations to be performed on a non-native type.
Johannes Doerfert13c5c642014-07-29 21:06:08230 isl_ast_expr_free(Expr);
231 return V;
232}
233
Nikita Popovff9b37e2021-03-11 16:01:48234std::pair<Value *, Type *>
Michael Krusead84c6f2022-02-16 17:56:25235IslExprBuilder::createAccessAddress(__isl_take isl_ast_expr *Expr) {
Johannes Doerferted878312014-08-03 01:50:50236 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
237 "isl ast expression not of type isl_ast_op");
238 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_access &&
239 "not an access isl ast expression");
Tobias Grosserf919d8b2016-08-04 13:57:29240 assert(isl_ast_expr_get_op_n_arg(Expr) >= 1 &&
Johannes Doerferted878312014-08-03 01:50:50241 "We need at least two operands to create a member access.");
242
Johannes Doerfert1a28a892014-10-05 11:32:18243 Value *Base, *IndexOp, *Access;
244 isl_ast_expr *BaseExpr;
245 isl_id *BaseId;
Johannes Doerferta63b2572014-08-03 01:51:59246
Johannes Doerfert1a28a892014-10-05 11:32:18247 BaseExpr = isl_ast_expr_get_op_arg(Expr, 0);
248 BaseId = isl_ast_expr_get_id(BaseExpr);
249 isl_ast_expr_free(BaseExpr);
250
Tobias Grosser04b909f2016-07-21 13:15:51251 const ScopArrayInfo *SAI = nullptr;
252
Tobias Grosser1be726a2017-03-18 20:54:43253 if (PollyDebugPrinting)
254 RuntimeDebugBuilder::createCPUPrinter(Builder, isl_id_get_name(BaseId));
255
Tobias Grosser04b909f2016-07-21 13:15:51256 if (IDToSAI)
257 SAI = (*IDToSAI)[BaseId];
258
259 if (!SAI)
Tobias Grosser206e9e32017-07-24 16:22:27260 SAI = ScopArrayInfo::getFromId(isl::manage(BaseId));
Tobias Grosser04b909f2016-07-21 13:15:51261 else
262 isl_id_free(BaseId);
263
264 assert(SAI && "No ScopArrayInfo found for this isl_id.");
265
Johannes Doerfert1a28a892014-10-05 11:32:18266 Base = SAI->getBasePtr();
Tobias Grosser0d8874c2015-09-05 10:32:56267
268 if (auto NewBase = GlobalMap.lookup(Base))
269 Base = NewBase;
270
Johannes Doerferted878312014-08-03 01:50:50271 assert(Base->getType()->isPointerTy() && "Access base should be a pointer");
Tobias Grosser314587d2015-01-07 07:43:34272 StringRef BaseName = Base->getName();
Johannes Doerfert1a28a892014-10-05 11:32:18273
Tobias Grosser5db5d2d2015-05-20 11:02:12274 auto PointerTy = PointerType::get(SAI->getElementType(),
275 Base->getType()->getPointerAddressSpace());
276 if (Base->getType() != PointerTy) {
277 Base =
278 Builder.CreateBitCast(Base, PointerTy, "polly.access.cast." + BaseName);
279 }
Johannes Doerferted878312014-08-03 01:50:50280
Tobias Grosserf919d8b2016-08-04 13:57:29281 if (isl_ast_expr_get_op_n_arg(Expr) == 1) {
282 isl_ast_expr_free(Expr);
Tobias Grosser1be726a2017-03-18 20:54:43283 if (PollyDebugPrinting)
284 RuntimeDebugBuilder::createCPUPrinter(Builder, "\n");
Nikita Popovff9b37e2021-03-11 16:01:48285 return {Base, SAI->getElementType()};
Tobias Grosserf919d8b2016-08-04 13:57:29286 }
287
Johannes Doerfert2ef33e92014-10-05 11:33:59288 IndexOp = nullptr;
289 for (unsigned u = 1, e = isl_ast_expr_get_op_n_arg(Expr); u < e; u++) {
290 Value *NextIndex = create(isl_ast_expr_get_op_arg(Expr, u));
291 assert(NextIndex->getType()->isIntegerTy() &&
292 "Access index should be an integer");
293
Tobias Grosser1be726a2017-03-18 20:54:43294 if (PollyDebugPrinting)
295 RuntimeDebugBuilder::createCPUPrinter(Builder, "[", NextIndex, "]");
296
Tobias Grosser3717aa52016-06-11 19:17:15297 if (!IndexOp) {
298 IndexOp = NextIndex;
299 } else {
300 Type *Ty = getWidestType(NextIndex->getType(), IndexOp->getType());
301
302 if (Ty != NextIndex->getType())
303 NextIndex = Builder.CreateIntCast(NextIndex, Ty, true);
304 if (Ty != IndexOp->getType())
305 IndexOp = Builder.CreateIntCast(IndexOp, Ty, true);
306
307 IndexOp = createAdd(IndexOp, NextIndex, "polly.access.add." + BaseName);
308 }
Johannes Doerfert2ef33e92014-10-05 11:33:59309
310 // For every but the last dimension multiply the size, for the last
311 // dimension we can exit the loop.
312 if (u + 1 >= e)
313 break;
314
Tobias Grosser26253842015-11-10 14:24:21315 const SCEV *DimSCEV = SAI->getDimensionSize(u);
Tobias Grosser0d8874c2015-09-05 10:32:56316
Florian Hahn762fbbe2020-09-18 10:40:45317 llvm::ValueToSCEVMapTy Map;
318 for (auto &KV : GlobalMap)
319 Map[KV.first] = SE.getSCEV(KV.second);
Tobias Grosserf4bb7a62015-10-04 10:18:32320 DimSCEV = SCEVParameterRewriter::rewrite(DimSCEV, SE, Map);
Johannes Doerferte69e1142015-08-18 11:56:00321 Value *DimSize =
322 expandCodeFor(S, SE, DL, "polly", DimSCEV, DimSCEV->getType(),
Eli Friedmanacf80062016-11-02 22:32:23323 &*Builder.GetInsertPoint(), nullptr,
324 StartBlock->getSinglePredecessor());
Tobias Grosserc642e9542015-01-13 19:37:59325
Tobias Grosser3717aa52016-06-11 19:17:15326 Type *Ty = getWidestType(DimSize->getType(), IndexOp->getType());
327
328 if (Ty != IndexOp->getType())
329 IndexOp = Builder.CreateSExtOrTrunc(IndexOp, Ty,
330 "polly.access.sext." + BaseName);
331 if (Ty != DimSize->getType())
332 DimSize = Builder.CreateSExtOrTrunc(DimSize, Ty,
333 "polly.access.sext." + BaseName);
Johannes Doerfert404a0f82016-05-12 15:12:43334 IndexOp = createMul(IndexOp, DimSize, "polly.access.mul." + BaseName);
Johannes Doerfert2ef33e92014-10-05 11:33:59335 }
Johannes Doerferted878312014-08-03 01:50:50336
Nikita Popov2c68ecc2021-07-17 20:03:11337 Access = Builder.CreateGEP(SAI->getElementType(), Base, IndexOp,
338 "polly.access." + BaseName);
Johannes Doerferted878312014-08-03 01:50:50339
Tobias Grosser1be726a2017-03-18 20:54:43340 if (PollyDebugPrinting)
341 RuntimeDebugBuilder::createCPUPrinter(Builder, "\n");
Johannes Doerferted878312014-08-03 01:50:50342 isl_ast_expr_free(Expr);
Nikita Popovff9b37e2021-03-11 16:01:48343 return {Access, SAI->getElementType()};
Johannes Doerferted878312014-08-03 01:50:50344}
345
Michael Krusead84c6f2022-02-16 17:56:25346Value *IslExprBuilder::createOpAccess(__isl_take isl_ast_expr *Expr) {
Nikita Popovff9b37e2021-03-11 16:01:48347 auto Info = createAccessAddress(Expr);
348 assert(Info.first && "Could not create op access address");
349 return Builder.CreateLoad(Info.second, Info.first,
350 Info.first->getName() + ".load");
Johannes Doerfertdcb5f1d2014-09-18 11:14:30351}
352
Johannes Doerfert13c5c642014-07-29 21:06:08353Value *IslExprBuilder::createOpBin(__isl_take isl_ast_expr *Expr) {
354 Value *LHS, *RHS, *Res;
Tobias Grosser3717aa52016-06-11 19:17:15355 Type *MaxType;
Johannes Doerfert13c5c642014-07-29 21:06:08356 isl_ast_op_type OpType;
357
358 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
359 "isl ast expression not of type isl_ast_op");
360 assert(isl_ast_expr_get_op_n_arg(Expr) == 2 &&
361 "not a binary isl ast expression");
362
363 OpType = isl_ast_expr_get_op_type(Expr);
364
Johannes Doerfert561d36b2016-04-10 09:50:10365 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
366 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
Johannes Doerfert0837c2d2015-02-02 15:25:09367
Tobias Grosser3717aa52016-06-11 19:17:15368 Type *LHSType = LHS->getType();
369 Type *RHSType = RHS->getType();
370
371 MaxType = getWidestType(LHSType, RHSType);
372
373 // Take the result into account when calculating the widest type.
374 //
375 // For operations such as '+' the result may require a type larger than
376 // the type of the individual operands. For other operations such as '/', the
377 // result type cannot be larger than the type of the individual operand. isl
378 // does not calculate correct types for these operations and we consequently
379 // exclude those operations here.
Johannes Doerfert13c5c642014-07-29 21:06:08380 switch (OpType) {
381 case isl_ast_op_pdiv_q:
382 case isl_ast_op_pdiv_r:
383 case isl_ast_op_div:
384 case isl_ast_op_fdiv_q:
Tobias Grosser13e222c2014-12-07 16:04:29385 case isl_ast_op_zdiv_r:
Tobias Grosser3717aa52016-06-11 19:17:15386 // Do nothing
Johannes Doerfert13c5c642014-07-29 21:06:08387 break;
388 case isl_ast_op_add:
389 case isl_ast_op_sub:
390 case isl_ast_op_mul:
Tobias Grosser3717aa52016-06-11 19:17:15391 MaxType = getWidestType(MaxType, getType(Expr));
Johannes Doerfert13c5c642014-07-29 21:06:08392 break;
393 default:
394 llvm_unreachable("This is no binary isl ast expression");
395 }
396
Tobias Grosser3717aa52016-06-11 19:17:15397 if (MaxType != RHS->getType())
398 RHS = Builder.CreateSExt(RHS, MaxType);
399
400 if (MaxType != LHS->getType())
401 LHS = Builder.CreateSExt(LHS, MaxType);
402
Johannes Doerfert13c5c642014-07-29 21:06:08403 switch (OpType) {
404 default:
405 llvm_unreachable("This is no binary isl ast expression");
406 case isl_ast_op_add:
Johannes Doerfert404a0f82016-05-12 15:12:43407 Res = createAdd(LHS, RHS);
Johannes Doerfert13c5c642014-07-29 21:06:08408 break;
409 case isl_ast_op_sub:
Johannes Doerfert404a0f82016-05-12 15:12:43410 Res = createSub(LHS, RHS);
Johannes Doerfert13c5c642014-07-29 21:06:08411 break;
412 case isl_ast_op_mul:
Johannes Doerfert404a0f82016-05-12 15:12:43413 Res = createMul(LHS, RHS);
Johannes Doerfert13c5c642014-07-29 21:06:08414 break;
415 case isl_ast_op_div:
Tobias Grosser3717aa52016-06-11 19:17:15416 Res = Builder.CreateSDiv(LHS, RHS, "pexp.div", true);
Tobias Grossercdb38e52015-05-29 17:08:19417 break;
Johannes Doerfert13c5c642014-07-29 21:06:08418 case isl_ast_op_pdiv_q: // Dividend is non-negative
Tobias Grosser3717aa52016-06-11 19:17:15419 Res = Builder.CreateUDiv(LHS, RHS, "pexp.p_div_q");
Johannes Doerfert13c5c642014-07-29 21:06:08420 break;
Tobias Grosser3717aa52016-06-11 19:17:15421 case isl_ast_op_fdiv_q: { // Round towards -infty
422 if (auto *Const = dyn_cast<ConstantInt>(RHS)) {
423 auto &Val = Const->getValue();
424 if (Val.isPowerOf2() && Val.isNonNegative()) {
425 Res = Builder.CreateAShr(LHS, Val.ceilLogBase2(), "polly.fdiv_q.shr");
426 break;
427 }
428 }
429 // TODO: Review code and check that this calculation does not yield
Michael Krusea6d48f52017-06-08 12:06:15430 // incorrect overflow in some edge cases.
Tobias Grosser3717aa52016-06-11 19:17:15431 //
432 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
433 Value *One = ConstantInt::get(MaxType, 1);
434 Value *Zero = ConstantInt::get(MaxType, 0);
435 Value *Sum1 = createSub(LHS, RHS, "pexp.fdiv_q.0");
436 Value *Sum2 = createAdd(Sum1, One, "pexp.fdiv_q.1");
437 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero, "pexp.fdiv_q.2");
438 Value *Dividend =
439 Builder.CreateSelect(isNegative, Sum2, LHS, "pexp.fdiv_q.3");
440 Res = Builder.CreateSDiv(Dividend, RHS, "pexp.fdiv_q.4");
Johannes Doerfert13c5c642014-07-29 21:06:08441 break;
Tobias Grosser3717aa52016-06-11 19:17:15442 }
Johannes Doerfert13c5c642014-07-29 21:06:08443 case isl_ast_op_pdiv_r: // Dividend is non-negative
Tobias Grossercdb38e52015-05-29 17:08:19444 Res = Builder.CreateURem(LHS, RHS, "pexp.pdiv_r");
445 break;
Tobias Grosser3717aa52016-06-11 19:17:15446
Tobias Grosser13e222c2014-12-07 16:04:29447 case isl_ast_op_zdiv_r: // Result only compared against zero
Michael Kruse5c527f92016-06-03 18:51:48448 Res = Builder.CreateSRem(LHS, RHS, "pexp.zdiv_r");
Johannes Doerfert13c5c642014-07-29 21:06:08449 break;
450 }
451
Tobias Grosser3717aa52016-06-11 19:17:15452 // TODO: We can truncate the result, if it fits into a smaller type. This can
453 // help in cases where we have larger operands (e.g. i67) but the result is
454 // known to fit into i64. Without the truncation, the larger i67 type may
455 // force all subsequent operations to be performed on a non-native type.
Johannes Doerfert13c5c642014-07-29 21:06:08456 isl_ast_expr_free(Expr);
457 return Res;
458}
459
460Value *IslExprBuilder::createOpSelect(__isl_take isl_ast_expr *Expr) {
461 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_select &&
462 "Unsupported unary isl ast expression");
463 Value *LHS, *RHS, *Cond;
Tobias Grosser3717aa52016-06-11 19:17:15464 Type *MaxType = getType(Expr);
Johannes Doerfert13c5c642014-07-29 21:06:08465
466 Cond = create(isl_ast_expr_get_op_arg(Expr, 0));
Johannes Doerfert219b20e2014-10-07 14:37:59467 if (!Cond->getType()->isIntegerTy(1))
468 Cond = Builder.CreateIsNotNull(Cond);
Johannes Doerfert13c5c642014-07-29 21:06:08469
470 LHS = create(isl_ast_expr_get_op_arg(Expr, 1));
471 RHS = create(isl_ast_expr_get_op_arg(Expr, 2));
472
Tobias Grosser3717aa52016-06-11 19:17:15473 MaxType = getWidestType(MaxType, LHS->getType());
474 MaxType = getWidestType(MaxType, RHS->getType());
475
476 if (MaxType != RHS->getType())
477 RHS = Builder.CreateSExt(RHS, MaxType);
478
479 if (MaxType != LHS->getType())
480 LHS = Builder.CreateSExt(LHS, MaxType);
481
482 // TODO: Do we want to truncate the result?
Johannes Doerfert13c5c642014-07-29 21:06:08483 isl_ast_expr_free(Expr);
484 return Builder.CreateSelect(Cond, LHS, RHS);
485}
486
487Value *IslExprBuilder::createOpICmp(__isl_take isl_ast_expr *Expr) {
488 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
489 "Expected an isl_ast_expr_op expression");
490
491 Value *LHS, *RHS, *Res;
492
Johannes Doerfert561d36b2016-04-10 09:50:10493 auto *Op0 = isl_ast_expr_get_op_arg(Expr, 0);
494 auto *Op1 = isl_ast_expr_get_op_arg(Expr, 1);
495 bool HasNonAddressOfOperand =
496 isl_ast_expr_get_type(Op0) != isl_ast_expr_op ||
497 isl_ast_expr_get_type(Op1) != isl_ast_expr_op ||
498 isl_ast_expr_get_op_type(Op0) != isl_ast_op_address_of ||
499 isl_ast_expr_get_op_type(Op1) != isl_ast_op_address_of;
Johannes Doerfert13c5c642014-07-29 21:06:08500
Johannes Doerfert561d36b2016-04-10 09:50:10501 LHS = create(Op0);
502 RHS = create(Op1);
503
504 auto *LHSTy = LHS->getType();
505 auto *RHSTy = RHS->getType();
506 bool IsPtrType = LHSTy->isPointerTy() || RHSTy->isPointerTy();
507 bool UseUnsignedCmp = IsPtrType && !HasNonAddressOfOperand;
508
509 auto *PtrAsIntTy = Builder.getIntNTy(DL.getPointerSizeInBits());
510 if (LHSTy->isPointerTy())
511 LHS = Builder.CreatePtrToInt(LHS, PtrAsIntTy);
512 if (RHSTy->isPointerTy())
513 RHS = Builder.CreatePtrToInt(RHS, PtrAsIntTy);
Johannes Doerfert13c5c642014-07-29 21:06:08514
Tobias Grosser3717aa52016-06-11 19:17:15515 if (LHS->getType() != RHS->getType()) {
516 Type *MaxType = LHS->getType();
517 MaxType = getWidestType(MaxType, RHS->getType());
518
519 if (MaxType != RHS->getType())
520 RHS = Builder.CreateSExt(RHS, MaxType);
521
522 if (MaxType != LHS->getType())
523 LHS = Builder.CreateSExt(LHS, MaxType);
524 }
Johannes Doerfert13c5c642014-07-29 21:06:08525
Johannes Doerfert5e8de622014-09-18 11:14:07526 isl_ast_op_type OpType = isl_ast_expr_get_op_type(Expr);
527 assert(OpType >= isl_ast_op_eq && OpType <= isl_ast_op_gt &&
528 "Unsupported ICmp isl ast expression");
Kazu Hiratae7774f492021-12-26 22:26:44529 static_assert(isl_ast_op_eq + 4 == isl_ast_op_gt,
530 "Isl ast op type interface changed");
Johannes Doerfert5e8de622014-09-18 11:14:07531
532 CmpInst::Predicate Predicates[5][2] = {
533 {CmpInst::ICMP_EQ, CmpInst::ICMP_EQ},
534 {CmpInst::ICMP_SLE, CmpInst::ICMP_ULE},
535 {CmpInst::ICMP_SLT, CmpInst::ICMP_ULT},
536 {CmpInst::ICMP_SGE, CmpInst::ICMP_UGE},
537 {CmpInst::ICMP_SGT, CmpInst::ICMP_UGT},
538 };
539
Johannes Doerfert561d36b2016-04-10 09:50:10540 Res = Builder.CreateICmp(Predicates[OpType - isl_ast_op_eq][UseUnsignedCmp],
541 LHS, RHS);
Johannes Doerfert5e8de622014-09-18 11:14:07542
Johannes Doerfert13c5c642014-07-29 21:06:08543 isl_ast_expr_free(Expr);
544 return Res;
545}
546
547Value *IslExprBuilder::createOpBoolean(__isl_take isl_ast_expr *Expr) {
548 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
549 "Expected an isl_ast_expr_op expression");
550
551 Value *LHS, *RHS, *Res;
552 isl_ast_op_type OpType;
553
554 OpType = isl_ast_expr_get_op_type(Expr);
555
556 assert((OpType == isl_ast_op_and || OpType == isl_ast_op_or) &&
557 "Unsupported isl_ast_op_type");
558
559 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
560 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
561
562 // Even though the isl pretty printer prints the expressions as 'exp && exp'
563 // or 'exp || exp', we actually code generate the bitwise expressions
564 // 'exp & exp' or 'exp | exp'. This forces the evaluation of both branches,
565 // but it is, due to the use of i1 types, otherwise equivalent. The reason
566 // to go for bitwise operations is, that we assume the reduced control flow
Michael Krusea6d48f52017-06-08 12:06:15567 // will outweigh the overhead introduced by evaluating unneeded expressions.
Johannes Doerfert13c5c642014-07-29 21:06:08568 // The isl code generation currently does not take advantage of the fact that
569 // the expression after an '||' or '&&' is in some cases not evaluated.
570 // Evaluating it anyways does not cause any undefined behaviour.
571 //
572 // TODO: Document in isl itself, that the unconditionally evaluating the
573 // second part of '||' or '&&' expressions is safe.
Johannes Doerfertb164c792014-09-18 11:17:17574 if (!LHS->getType()->isIntegerTy(1))
575 LHS = Builder.CreateIsNotNull(LHS);
576 if (!RHS->getType()->isIntegerTy(1))
577 RHS = Builder.CreateIsNotNull(RHS);
Johannes Doerfert13c5c642014-07-29 21:06:08578
579 switch (OpType) {
580 default:
581 llvm_unreachable("Unsupported boolean expression");
582 case isl_ast_op_and:
583 Res = Builder.CreateAnd(LHS, RHS);
584 break;
585 case isl_ast_op_or:
586 Res = Builder.CreateOr(LHS, RHS);
587 break;
588 }
589
590 isl_ast_expr_free(Expr);
591 return Res;
592}
593
Tobias Grosserb021a4f2015-03-04 18:14:59594Value *
595IslExprBuilder::createOpBooleanConditional(__isl_take isl_ast_expr *Expr) {
596 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
597 "Expected an isl_ast_expr_op expression");
598
599 Value *LHS, *RHS;
600 isl_ast_op_type OpType;
601
602 Function *F = Builder.GetInsertBlock()->getParent();
603 LLVMContext &Context = F->getContext();
604
605 OpType = isl_ast_expr_get_op_type(Expr);
606
607 assert((OpType == isl_ast_op_and_then || OpType == isl_ast_op_or_else) &&
608 "Unsupported isl_ast_op_type");
609
610 auto InsertBB = Builder.GetInsertBlock();
611 auto InsertPoint = Builder.GetInsertPoint();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54612 auto NextBB = SplitBlock(InsertBB, &*InsertPoint, &DT, &LI);
Tobias Grosserb021a4f2015-03-04 18:14:59613 BasicBlock *CondBB = BasicBlock::Create(Context, "polly.cond", F);
614 LI.changeLoopFor(CondBB, LI.getLoopFor(InsertBB));
615 DT.addNewBlock(CondBB, InsertBB);
616
617 InsertBB->getTerminator()->eraseFromParent();
618 Builder.SetInsertPoint(InsertBB);
619 auto BR = Builder.CreateCondBr(Builder.getTrue(), NextBB, CondBB);
620
621 Builder.SetInsertPoint(CondBB);
622 Builder.CreateBr(NextBB);
623
624 Builder.SetInsertPoint(InsertBB->getTerminator());
625
626 LHS = create(isl_ast_expr_get_op_arg(Expr, 0));
627 if (!LHS->getType()->isIntegerTy(1))
628 LHS = Builder.CreateIsNotNull(LHS);
629 auto LeftBB = Builder.GetInsertBlock();
630
631 if (OpType == isl_ast_op_and || OpType == isl_ast_op_and_then)
632 BR->setCondition(Builder.CreateNeg(LHS));
633 else
634 BR->setCondition(LHS);
635
636 Builder.SetInsertPoint(CondBB->getTerminator());
637 RHS = create(isl_ast_expr_get_op_arg(Expr, 1));
638 if (!RHS->getType()->isIntegerTy(1))
639 RHS = Builder.CreateIsNotNull(RHS);
640 auto RightBB = Builder.GetInsertBlock();
641
642 Builder.SetInsertPoint(NextBB->getTerminator());
643 auto PHI = Builder.CreatePHI(Builder.getInt1Ty(), 2);
644 PHI->addIncoming(OpType == isl_ast_op_and_then ? Builder.getFalse()
645 : Builder.getTrue(),
646 LeftBB);
647 PHI->addIncoming(RHS, RightBB);
648
649 isl_ast_expr_free(Expr);
650 return PHI;
651}
652
Johannes Doerfert13c5c642014-07-29 21:06:08653Value *IslExprBuilder::createOp(__isl_take isl_ast_expr *Expr) {
654 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
655 "Expression not of type isl_ast_expr_op");
656 switch (isl_ast_expr_get_op_type(Expr)) {
657 case isl_ast_op_error:
658 case isl_ast_op_cond:
Johannes Doerfert13c5c642014-07-29 21:06:08659 case isl_ast_op_call:
660 case isl_ast_op_member:
Johannes Doerfert13c5c642014-07-29 21:06:08661 llvm_unreachable("Unsupported isl ast expression");
Johannes Doerferted878312014-08-03 01:50:50662 case isl_ast_op_access:
663 return createOpAccess(Expr);
Johannes Doerfert13c5c642014-07-29 21:06:08664 case isl_ast_op_max:
665 case isl_ast_op_min:
666 return createOpNAry(Expr);
667 case isl_ast_op_add:
668 case isl_ast_op_sub:
669 case isl_ast_op_mul:
670 case isl_ast_op_div:
671 case isl_ast_op_fdiv_q: // Round towards -infty
672 case isl_ast_op_pdiv_q: // Dividend is non-negative
673 case isl_ast_op_pdiv_r: // Dividend is non-negative
Tobias Grosser13e222c2014-12-07 16:04:29674 case isl_ast_op_zdiv_r: // Result only compared against zero
Johannes Doerfert13c5c642014-07-29 21:06:08675 return createOpBin(Expr);
676 case isl_ast_op_minus:
677 return createOpUnary(Expr);
678 case isl_ast_op_select:
679 return createOpSelect(Expr);
680 case isl_ast_op_and:
681 case isl_ast_op_or:
682 return createOpBoolean(Expr);
Tobias Grosserb021a4f2015-03-04 18:14:59683 case isl_ast_op_and_then:
684 case isl_ast_op_or_else:
685 return createOpBooleanConditional(Expr);
Johannes Doerfert13c5c642014-07-29 21:06:08686 case isl_ast_op_eq:
687 case isl_ast_op_le:
688 case isl_ast_op_lt:
689 case isl_ast_op_ge:
690 case isl_ast_op_gt:
691 return createOpICmp(Expr);
Johannes Doerfertdcb5f1d2014-09-18 11:14:30692 case isl_ast_op_address_of:
693 return createOpAddressOf(Expr);
Johannes Doerfert13c5c642014-07-29 21:06:08694 }
695
696 llvm_unreachable("Unsupported isl_ast_expr_op kind.");
697}
698
Johannes Doerfertdcb5f1d2014-09-18 11:14:30699Value *IslExprBuilder::createOpAddressOf(__isl_take isl_ast_expr *Expr) {
700 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
701 "Expected an isl_ast_expr_op expression.");
702 assert(isl_ast_expr_get_op_n_arg(Expr) == 1 && "Address of should be unary.");
703
704 isl_ast_expr *Op = isl_ast_expr_get_op_arg(Expr, 0);
705 assert(isl_ast_expr_get_type(Op) == isl_ast_expr_op &&
706 "Expected address of operator to be an isl_ast_expr_op expression.");
707 assert(isl_ast_expr_get_op_type(Op) == isl_ast_op_access &&
708 "Expected address of operator to be an access expression.");
709
Nikita Popovff9b37e2021-03-11 16:01:48710 Value *V = createAccessAddress(Op).first;
Johannes Doerfertdcb5f1d2014-09-18 11:14:30711
712 isl_ast_expr_free(Expr);
713
714 return V;
715}
716
Johannes Doerfert13c5c642014-07-29 21:06:08717Value *IslExprBuilder::createId(__isl_take isl_ast_expr *Expr) {
718 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_id &&
719 "Expression not of type isl_ast_expr_ident");
720
721 isl_id *Id;
722 Value *V;
723
724 Id = isl_ast_expr_get_id(Expr);
725
726 assert(IDToValue.count(Id) && "Identifier not found");
727
728 V = IDToValue[Id];
Johannes Doerfertc4898502015-11-07 19:46:04729 if (!V)
Tobias Grosser3717aa52016-06-11 19:17:15730 V = UndefValue::get(getType(Expr));
Johannes Doerfert13c5c642014-07-29 21:06:08731
Johannes Doerfert561d36b2016-04-10 09:50:10732 if (V->getType()->isPointerTy())
733 V = Builder.CreatePtrToInt(V, Builder.getIntNTy(DL.getPointerSizeInBits()));
734
Tobias Grosser3284f192015-03-10 22:35:43735 assert(V && "Unknown parameter id found");
736
Johannes Doerfert13c5c642014-07-29 21:06:08737 isl_id_free(Id);
738 isl_ast_expr_free(Expr);
739
740 return V;
741}
742
Tobias Grosser3717aa52016-06-11 19:17:15743IntegerType *IslExprBuilder::getType(__isl_keep isl_ast_expr *Expr) {
744 // XXX: We assume i64 is large enough. This is often true, but in general
745 // incorrect. Also, on 32bit architectures, it would be beneficial to
746 // use a smaller type. We can and should directly derive this information
747 // during code generation.
748 return IntegerType::get(Builder.getContext(), 64);
749}
750
Johannes Doerfert13c5c642014-07-29 21:06:08751Value *IslExprBuilder::createInt(__isl_take isl_ast_expr *Expr) {
752 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_int &&
753 "Expression not of type isl_ast_expr_int");
Tobias Grosser3717aa52016-06-11 19:17:15754 isl_val *Val;
755 Value *V;
756 APInt APValue;
757 IntegerType *T;
Johannes Doerfert13c5c642014-07-29 21:06:08758
Tobias Grosser3717aa52016-06-11 19:17:15759 Val = isl_ast_expr_get_val(Expr);
760 APValue = APIntFromVal(Val);
761
762 auto BitWidth = APValue.getBitWidth();
763 if (BitWidth <= 64)
764 T = getType(Expr);
765 else
766 T = Builder.getIntNTy(BitWidth);
767
Jay Foad6bec3e92021-10-06 09:54:07768 APValue = APValue.sext(T->getBitWidth());
Tobias Grosser3717aa52016-06-11 19:17:15769 V = ConstantInt::get(T, APValue);
Johannes Doerfert13c5c642014-07-29 21:06:08770
771 isl_ast_expr_free(Expr);
772 return V;
773}
774
775Value *IslExprBuilder::create(__isl_take isl_ast_expr *Expr) {
776 switch (isl_ast_expr_get_type(Expr)) {
777 case isl_ast_expr_error:
778 llvm_unreachable("Code generation error");
779 case isl_ast_expr_op:
780 return createOp(Expr);
781 case isl_ast_expr_id:
782 return createId(Expr);
783 case isl_ast_expr_int:
784 return createInt(Expr);
785 }
786
787 llvm_unreachable("Unexpected enum value");
788}