blob: d39df897ea66efddb37079723af290c1d5859fcb [file] [log] [blame]
Dan Gohman7cac9572010-08-02 23:49:30 +00001//===- ScalarEvolutionsTest.cpp - ScalarEvolution unit tests --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dan Gohman7cac9572010-08-02 23:49:30 +00006//
7//===----------------------------------------------------------------------===//
8
Keno Fischer090f1952017-05-27 03:22:55 +00009#include "llvm/ADT/SmallVector.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000011#include "llvm/Analysis/LoopInfo.h"
Keno Fischer090f1952017-05-27 03:22:55 +000012#include "llvm/Analysis/ScalarEvolutionExpander.h"
13#include "llvm/Analysis/ScalarEvolutionExpressions.h"
14#include "llvm/Analysis/TargetLibraryInfo.h"
Sanjoy Das507dd402016-10-18 17:45:16 +000015#include "llvm/AsmParser/Parser.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Constants.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000017#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/GlobalVariable.h"
Keno Fischer090f1952017-05-27 03:22:55 +000019#include "llvm/IR/IRBuilder.h"
Sanjoy Das507dd402016-10-18 17:45:16 +000020#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000022#include "llvm/IR/LegacyPassManager.h"
Keno Fischer090f1952017-05-27 03:22:55 +000023#include "llvm/IR/Module.h"
Sanjoy Das507dd402016-10-18 17:45:16 +000024#include "llvm/IR/Verifier.h"
25#include "llvm/Support/SourceMgr.h"
Dan Gohman7cac9572010-08-02 23:49:30 +000026#include "gtest/gtest.h"
27
28namespace llvm {
29namespace {
30
Nick Lewycky287682e2011-10-04 06:51:26 +000031// We use this fixture to ensure that we clean up ScalarEvolution before
32// deleting the PassManager.
33class ScalarEvolutionsTest : public testing::Test {
34protected:
Dan Gohman7cac9572010-08-02 23:49:30 +000035 LLVMContext Context;
Nick Lewycky287682e2011-10-04 06:51:26 +000036 Module M;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000037 TargetLibraryInfoImpl TLII;
38 TargetLibraryInfo TLI;
39
Daniel Jasperaec2fa32016-12-19 08:22:17 +000040 std::unique_ptr<AssumptionCache> AC;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000041 std::unique_ptr<DominatorTree> DT;
42 std::unique_ptr<LoopInfo> LI;
43
44 ScalarEvolutionsTest() : M("", Context), TLII(), TLI(TLII) {}
45
46 ScalarEvolution buildSE(Function &F) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +000047 AC.reset(new AssumptionCache(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000048 DT.reset(new DominatorTree(F));
49 LI.reset(new LoopInfo(*DT));
Daniel Jasperaec2fa32016-12-19 08:22:17 +000050 return ScalarEvolution(F, TLI, *AC, *DT, *LI);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000051 }
Sanjoy Das6764b9a2016-11-10 07:56:05 +000052
Sanjoy Das044f9562017-04-14 23:47:53 +000053 void runWithSE(
Sanjoy Dasb1227db2016-12-12 14:57:11 +000054 Module &M, StringRef FuncName,
Sanjoy Das044f9562017-04-14 23:47:53 +000055 function_ref<void(Function &F, LoopInfo &LI, ScalarEvolution &SE)> Test) {
Reid Kleckner30422ee2016-12-12 18:52:32 +000056 auto *F = M.getFunction(FuncName);
57 ASSERT_NE(F, nullptr) << "Could not find " << FuncName;
58 ScalarEvolution SE = buildSE(*F);
Sanjoy Das044f9562017-04-14 23:47:53 +000059 Test(*F, *LI, SE);
Sanjoy Das6764b9a2016-11-10 07:56:05 +000060 }
Nick Lewycky287682e2011-10-04 06:51:26 +000061};
Dan Gohman7cac9572010-08-02 23:49:30 +000062
Nick Lewycky287682e2011-10-04 06:51:26 +000063TEST_F(ScalarEvolutionsTest, SCEVUnknownRAUW) {
Chris Lattner229907c2011-07-18 04:54:35 +000064 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context),
Jay Foadb804a2b2011-07-12 14:06:48 +000065 std::vector<Type *>(), false);
James Y Knight13680222019-02-01 02:28:03 +000066 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
Dan Gohman7cac9572010-08-02 23:49:30 +000067 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
Craig Topper66f09ad2014-06-08 22:29:17 +000068 ReturnInst::Create(Context, nullptr, BB);
Dan Gohman7cac9572010-08-02 23:49:30 +000069
Chris Lattner229907c2011-07-18 04:54:35 +000070 Type *Ty = Type::getInt1Ty(Context);
Dan Gohman7cac9572010-08-02 23:49:30 +000071 Constant *Init = Constant::getNullValue(Ty);
72 Value *V0 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V0");
73 Value *V1 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V1");
74 Value *V2 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V2");
75
Chandler Carruth2f1fd162015-08-17 02:08:17 +000076 ScalarEvolution SE = buildSE(*F);
Dan Gohman7cac9572010-08-02 23:49:30 +000077
78 const SCEV *S0 = SE.getSCEV(V0);
79 const SCEV *S1 = SE.getSCEV(V1);
80 const SCEV *S2 = SE.getSCEV(V2);
81
82 const SCEV *P0 = SE.getAddExpr(S0, S0);
83 const SCEV *P1 = SE.getAddExpr(S1, S1);
84 const SCEV *P2 = SE.getAddExpr(S2, S2);
85
86 const SCEVMulExpr *M0 = cast<SCEVMulExpr>(P0);
87 const SCEVMulExpr *M1 = cast<SCEVMulExpr>(P1);
88 const SCEVMulExpr *M2 = cast<SCEVMulExpr>(P2);
89
90 EXPECT_EQ(cast<SCEVConstant>(M0->getOperand(0))->getValue()->getZExtValue(),
91 2u);
92 EXPECT_EQ(cast<SCEVConstant>(M1->getOperand(0))->getValue()->getZExtValue(),
93 2u);
94 EXPECT_EQ(cast<SCEVConstant>(M2->getOperand(0))->getValue()->getZExtValue(),
95 2u);
96
97 // Before the RAUWs, these are all pointing to separate values.
98 EXPECT_EQ(cast<SCEVUnknown>(M0->getOperand(1))->getValue(), V0);
99 EXPECT_EQ(cast<SCEVUnknown>(M1->getOperand(1))->getValue(), V1);
100 EXPECT_EQ(cast<SCEVUnknown>(M2->getOperand(1))->getValue(), V2);
101
102 // Do some RAUWs.
103 V2->replaceAllUsesWith(V1);
104 V1->replaceAllUsesWith(V0);
105
106 // After the RAUWs, these should all be pointing to V0.
107 EXPECT_EQ(cast<SCEVUnknown>(M0->getOperand(1))->getValue(), V0);
108 EXPECT_EQ(cast<SCEVUnknown>(M1->getOperand(1))->getValue(), V0);
109 EXPECT_EQ(cast<SCEVUnknown>(M2->getOperand(1))->getValue(), V0);
Nick Lewycky287682e2011-10-04 06:51:26 +0000110}
Dan Gohman7cac9572010-08-02 23:49:30 +0000111
Tobias Grosser11332e52016-02-21 17:42:10 +0000112TEST_F(ScalarEvolutionsTest, SimplifiedPHI) {
113 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context),
114 std::vector<Type *>(), false);
James Y Knight13680222019-02-01 02:28:03 +0000115 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
Tobias Grosser11332e52016-02-21 17:42:10 +0000116 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
117 BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
118 BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
119 BranchInst::Create(LoopBB, EntryBB);
120 BranchInst::Create(LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)),
121 LoopBB);
122 ReturnInst::Create(Context, nullptr, ExitBB);
123 auto *Ty = Type::getInt32Ty(Context);
124 auto *PN = PHINode::Create(Ty, 2, "", &*LoopBB->begin());
125 PN->addIncoming(Constant::getNullValue(Ty), EntryBB);
126 PN->addIncoming(UndefValue::get(Ty), LoopBB);
127 ScalarEvolution SE = buildSE(*F);
128 auto *S1 = SE.getSCEV(PN);
129 auto *S2 = SE.getSCEV(PN);
Tobias Grosser946ca0a2016-02-22 07:20:40 +0000130 auto *ZeroConst = SE.getConstant(Ty, 0);
Tobias Grosser11332e52016-02-21 17:42:10 +0000131
132 // At some point, only the first call to getSCEV returned the simplified
133 // SCEVConstant and later calls just returned a SCEVUnknown referencing the
134 // PHI node.
Tobias Grosser946ca0a2016-02-22 07:20:40 +0000135 EXPECT_EQ(S1, ZeroConst);
136 EXPECT_EQ(S1, S2);
Tobias Grosser11332e52016-02-21 17:42:10 +0000137}
138
Wei Mi3076cc32016-09-15 04:06:44 +0000139TEST_F(ScalarEvolutionsTest, ExpandPtrTypeSCEV) {
140 // It is to test the fix for PR30213. It exercises the branch in scev
141 // expansion when the value in ValueOffsetPair is a ptr and the offset
142 // is not divisible by the elem type size of value.
143 auto *I8Ty = Type::getInt8Ty(Context);
144 auto *I8PtrTy = Type::getInt8PtrTy(Context);
145 auto *I32Ty = Type::getInt32Ty(Context);
146 auto *I32PtrTy = Type::getInt32PtrTy(Context);
147 FunctionType *FTy =
148 FunctionType::get(Type::getVoidTy(Context), std::vector<Type *>(), false);
James Y Knight13680222019-02-01 02:28:03 +0000149 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
Wei Mi3076cc32016-09-15 04:06:44 +0000150 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
151 BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
152 BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
153 BranchInst::Create(LoopBB, EntryBB);
154 ReturnInst::Create(Context, nullptr, ExitBB);
155
156 // loop: ; preds = %loop, %entry
157 // %alloca = alloca i32
158 // %gep0 = getelementptr i32, i32* %alloca, i32 1
159 // %bitcast1 = bitcast i32* %gep0 to i8*
160 // %gep1 = getelementptr i8, i8* %bitcast1, i32 1
161 // %gep2 = getelementptr i8, i8* undef, i32 1
162 // %cmp = icmp ult i8* undef, %bitcast1
163 // %select = select i1 %cmp, i8* %gep1, i8* %gep2
164 // %bitcast2 = bitcast i8* %select to i32*
165 // br i1 undef, label %loop, label %exit
166
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000167 const DataLayout &DL = F->getParent()->getDataLayout();
Wei Mi3076cc32016-09-15 04:06:44 +0000168 BranchInst *Br = BranchInst::Create(
169 LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)), LoopBB);
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000170 AllocaInst *Alloca = new AllocaInst(I32Ty, DL.getAllocaAddrSpace(),
171 "alloca", Br);
Wei Mi3076cc32016-09-15 04:06:44 +0000172 ConstantInt *Ci32 = ConstantInt::get(Context, APInt(32, 1));
173 GetElementPtrInst *Gep0 =
174 GetElementPtrInst::Create(I32Ty, Alloca, Ci32, "gep0", Br);
175 CastInst *CastA =
176 CastInst::CreateBitOrPointerCast(Gep0, I8PtrTy, "bitcast1", Br);
177 GetElementPtrInst *Gep1 =
178 GetElementPtrInst::Create(I8Ty, CastA, Ci32, "gep1", Br);
179 GetElementPtrInst *Gep2 = GetElementPtrInst::Create(
180 I8Ty, UndefValue::get(I8PtrTy), Ci32, "gep2", Br);
181 CmpInst *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULT,
182 UndefValue::get(I8PtrTy), CastA, "cmp", Br);
183 SelectInst *Sel = SelectInst::Create(Cmp, Gep1, Gep2, "select", Br);
184 CastInst *CastB =
185 CastInst::CreateBitOrPointerCast(Sel, I32PtrTy, "bitcast2", Br);
186
187 ScalarEvolution SE = buildSE(*F);
188 auto *S = SE.getSCEV(CastB);
189 SCEVExpander Exp(SE, M.getDataLayout(), "expander");
190 Value *V =
191 Exp.expandCodeFor(cast<SCEVAddExpr>(S)->getOperand(1), nullptr, Br);
192
193 // Expect the expansion code contains:
194 // %0 = bitcast i32* %bitcast2 to i8*
195 // %uglygep = getelementptr i8, i8* %0, i64 -1
196 // %1 = bitcast i8* %uglygep to i32*
197 EXPECT_TRUE(isa<BitCastInst>(V));
198 Instruction *Gep = cast<Instruction>(V)->getPrevNode();
199 EXPECT_TRUE(isa<GetElementPtrInst>(Gep));
200 EXPECT_TRUE(isa<ConstantInt>(Gep->getOperand(1)));
201 EXPECT_EQ(cast<ConstantInt>(Gep->getOperand(1))->getSExtValue(), -1);
202 EXPECT_TRUE(isa<BitCastInst>(Gep->getPrevNode()));
203}
204
Sanjoy Dasb53021d2016-10-30 23:52:50 +0000205static Instruction *getInstructionByName(Function &F, StringRef Name) {
206 for (auto &I : instructions(F))
207 if (I.getName() == Name)
208 return &I;
Sanjoy Das507dd402016-10-18 17:45:16 +0000209 llvm_unreachable("Expected to find instruction!");
210}
211
212TEST_F(ScalarEvolutionsTest, CommutativeExprOperandOrder) {
213 LLVMContext C;
214 SMDiagnostic Err;
215 std::unique_ptr<Module> M = parseAssemblyString(
216 "target datalayout = \"e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128\" "
Sanjoy Dasb53021d2016-10-30 23:52:50 +0000217 " "
Sanjoy Das299e6722016-10-30 23:52:56 +0000218 "@var_0 = external global i32, align 4"
219 "@var_1 = external global i32, align 4"
Sanjoy Dasfd080902016-10-31 03:32:45 +0000220 "@var_2 = external global i32, align 4"
Sanjoy Das299e6722016-10-30 23:52:56 +0000221 " "
Sanjoy Das17078692016-10-31 03:32:43 +0000222 "declare i32 @unknown(i32, i32, i32)"
223 " "
Sanjoy Dasb53021d2016-10-30 23:52:50 +0000224 "define void @f_1(i8* nocapture %arr, i32 %n, i32* %A, i32* %B) "
Sanjoy Das507dd402016-10-18 17:45:16 +0000225 " local_unnamed_addr { "
226 "entry: "
227 " %entrycond = icmp sgt i32 %n, 0 "
228 " br i1 %entrycond, label %loop.ph, label %for.end "
229 " "
230 "loop.ph: "
231 " %a = load i32, i32* %A, align 4 "
232 " %b = load i32, i32* %B, align 4 "
233 " %mul = mul nsw i32 %b, %a "
234 " %iv0.init = getelementptr inbounds i8, i8* %arr, i32 %mul "
235 " br label %loop "
236 " "
237 "loop: "
238 " %iv0 = phi i8* [ %iv0.inc, %loop ], [ %iv0.init, %loop.ph ] "
239 " %iv1 = phi i32 [ %iv1.inc, %loop ], [ 0, %loop.ph ] "
240 " %conv = trunc i32 %iv1 to i8 "
241 " store i8 %conv, i8* %iv0, align 1 "
242 " %iv0.inc = getelementptr inbounds i8, i8* %iv0, i32 %b "
243 " %iv1.inc = add nuw nsw i32 %iv1, 1 "
244 " %exitcond = icmp eq i32 %iv1.inc, %n "
245 " br i1 %exitcond, label %for.end.loopexit, label %loop "
246 " "
247 "for.end.loopexit: "
248 " br label %for.end "
249 " "
250 "for.end: "
251 " ret void "
252 "} "
253 " "
Sanjoy Dasb53021d2016-10-30 23:52:50 +0000254 "define void @f_2(i32* %X, i32* %Y, i32* %Z) { "
Sanjoy Das507dd402016-10-18 17:45:16 +0000255 " %x = load i32, i32* %X "
256 " %y = load i32, i32* %Y "
257 " %z = load i32, i32* %Z "
258 " ret void "
Sanjoy Das299e6722016-10-30 23:52:56 +0000259 "} "
260 " "
Sanjoy Das299e6722016-10-30 23:52:56 +0000261 "define void @f_3() { "
262 " %x = load i32, i32* @var_0"
263 " %y = load i32, i32* @var_1"
Sanjoy Dasfd080902016-10-31 03:32:45 +0000264 " %z = load i32, i32* @var_2"
Sanjoy Das299e6722016-10-30 23:52:56 +0000265 " ret void"
266 "} "
Sanjoy Das17078692016-10-31 03:32:43 +0000267 " "
268 "define void @f_4(i32 %a, i32 %b, i32 %c) { "
269 " %x = call i32 @unknown(i32 %a, i32 %b, i32 %c)"
270 " %y = call i32 @unknown(i32 %b, i32 %c, i32 %a)"
271 " %z = call i32 @unknown(i32 %c, i32 %a, i32 %b)"
272 " ret void"
273 "} "
Sanjoy Das299e6722016-10-30 23:52:56 +0000274 ,
Sanjoy Das507dd402016-10-18 17:45:16 +0000275 Err, C);
276
277 assert(M && "Could not parse module?");
278 assert(!verifyModule(*M) && "Must have been well formed!");
279
Sanjoy Das044f9562017-04-14 23:47:53 +0000280 runWithSE(*M, "f_1", [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
Sanjoy Das3d6e3df2016-10-31 03:32:39 +0000281 auto *IV0 = getInstructionByName(F, "iv0");
282 auto *IV0Inc = getInstructionByName(F, "iv0.inc");
Sanjoy Das507dd402016-10-18 17:45:16 +0000283
Sanjoy Das507dd402016-10-18 17:45:16 +0000284 auto *FirstExprForIV0 = SE.getSCEV(IV0);
285 auto *FirstExprForIV0Inc = SE.getSCEV(IV0Inc);
286 auto *SecondExprForIV0 = SE.getSCEV(IV0);
287
288 EXPECT_TRUE(isa<SCEVAddRecExpr>(FirstExprForIV0));
289 EXPECT_TRUE(isa<SCEVAddRecExpr>(FirstExprForIV0Inc));
290 EXPECT_TRUE(isa<SCEVAddRecExpr>(SecondExprForIV0));
Sanjoy Das3d6e3df2016-10-31 03:32:39 +0000291 });
Sanjoy Das507dd402016-10-18 17:45:16 +0000292
Sanjoy Das17078692016-10-31 03:32:43 +0000293 auto CheckCommutativeMulExprs = [&](ScalarEvolution &SE, const SCEV *A,
294 const SCEV *B, const SCEV *C) {
295 EXPECT_EQ(SE.getMulExpr(A, B), SE.getMulExpr(B, A));
296 EXPECT_EQ(SE.getMulExpr(B, C), SE.getMulExpr(C, B));
297 EXPECT_EQ(SE.getMulExpr(A, C), SE.getMulExpr(C, A));
Sanjoy Das507dd402016-10-18 17:45:16 +0000298
Sanjoy Das17078692016-10-31 03:32:43 +0000299 SmallVector<const SCEV *, 3> Ops0 = {A, B, C};
300 SmallVector<const SCEV *, 3> Ops1 = {A, C, B};
301 SmallVector<const SCEV *, 3> Ops2 = {B, A, C};
302 SmallVector<const SCEV *, 3> Ops3 = {B, C, A};
303 SmallVector<const SCEV *, 3> Ops4 = {C, B, A};
304 SmallVector<const SCEV *, 3> Ops5 = {C, A, B};
Sanjoy Das507dd402016-10-18 17:45:16 +0000305
306 auto *Mul0 = SE.getMulExpr(Ops0);
307 auto *Mul1 = SE.getMulExpr(Ops1);
308 auto *Mul2 = SE.getMulExpr(Ops2);
309 auto *Mul3 = SE.getMulExpr(Ops3);
310 auto *Mul4 = SE.getMulExpr(Ops4);
311 auto *Mul5 = SE.getMulExpr(Ops5);
312
Sanjoy Das17078692016-10-31 03:32:43 +0000313 EXPECT_EQ(Mul0, Mul1) << "Expected " << *Mul0 << " == " << *Mul1;
314 EXPECT_EQ(Mul1, Mul2) << "Expected " << *Mul1 << " == " << *Mul2;
315 EXPECT_EQ(Mul2, Mul3) << "Expected " << *Mul2 << " == " << *Mul3;
316 EXPECT_EQ(Mul3, Mul4) << "Expected " << *Mul3 << " == " << *Mul4;
317 EXPECT_EQ(Mul4, Mul5) << "Expected " << *Mul4 << " == " << *Mul5;
318 };
319
Sanjoy Dasfd080902016-10-31 03:32:45 +0000320 for (StringRef FuncName : {"f_2", "f_3", "f_4"})
Sanjoy Das044f9562017-04-14 23:47:53 +0000321 runWithSE(
322 *M, FuncName, [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
323 CheckCommutativeMulExprs(SE, SE.getSCEV(getInstructionByName(F, "x")),
324 SE.getSCEV(getInstructionByName(F, "y")),
325 SE.getSCEV(getInstructionByName(F, "z")));
326 });
Sanjoy Das507dd402016-10-18 17:45:16 +0000327}
328
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000329TEST_F(ScalarEvolutionsTest, CompareSCEVComplexity) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000330 FunctionType *FTy =
331 FunctionType::get(Type::getVoidTy(Context), std::vector<Type *>(), false);
James Y Knight13680222019-02-01 02:28:03 +0000332 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000333 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
334 BasicBlock *LoopBB = BasicBlock::Create(Context, "bb1", F);
335 BranchInst::Create(LoopBB, EntryBB);
336
337 auto *Ty = Type::getInt32Ty(Context);
338 SmallVector<Instruction*, 8> Muls(8), Acc(8), NextAcc(8);
339
340 Acc[0] = PHINode::Create(Ty, 2, "", LoopBB);
341 Acc[1] = PHINode::Create(Ty, 2, "", LoopBB);
342 Acc[2] = PHINode::Create(Ty, 2, "", LoopBB);
343 Acc[3] = PHINode::Create(Ty, 2, "", LoopBB);
344 Acc[4] = PHINode::Create(Ty, 2, "", LoopBB);
345 Acc[5] = PHINode::Create(Ty, 2, "", LoopBB);
346 Acc[6] = PHINode::Create(Ty, 2, "", LoopBB);
347 Acc[7] = PHINode::Create(Ty, 2, "", LoopBB);
348
349 for (int i = 0; i < 20; i++) {
350 Muls[0] = BinaryOperator::CreateMul(Acc[0], Acc[0], "", LoopBB);
351 NextAcc[0] = BinaryOperator::CreateAdd(Muls[0], Acc[4], "", LoopBB);
352 Muls[1] = BinaryOperator::CreateMul(Acc[1], Acc[1], "", LoopBB);
353 NextAcc[1] = BinaryOperator::CreateAdd(Muls[1], Acc[5], "", LoopBB);
354 Muls[2] = BinaryOperator::CreateMul(Acc[2], Acc[2], "", LoopBB);
355 NextAcc[2] = BinaryOperator::CreateAdd(Muls[2], Acc[6], "", LoopBB);
356 Muls[3] = BinaryOperator::CreateMul(Acc[3], Acc[3], "", LoopBB);
357 NextAcc[3] = BinaryOperator::CreateAdd(Muls[3], Acc[7], "", LoopBB);
358
359 Muls[4] = BinaryOperator::CreateMul(Acc[4], Acc[4], "", LoopBB);
360 NextAcc[4] = BinaryOperator::CreateAdd(Muls[4], Acc[0], "", LoopBB);
361 Muls[5] = BinaryOperator::CreateMul(Acc[5], Acc[5], "", LoopBB);
362 NextAcc[5] = BinaryOperator::CreateAdd(Muls[5], Acc[1], "", LoopBB);
363 Muls[6] = BinaryOperator::CreateMul(Acc[6], Acc[6], "", LoopBB);
364 NextAcc[6] = BinaryOperator::CreateAdd(Muls[6], Acc[2], "", LoopBB);
365 Muls[7] = BinaryOperator::CreateMul(Acc[7], Acc[7], "", LoopBB);
366 NextAcc[7] = BinaryOperator::CreateAdd(Muls[7], Acc[3], "", LoopBB);
367 Acc = NextAcc;
368 }
369
370 auto II = LoopBB->begin();
371 for (int i = 0; i < 8; i++) {
372 PHINode *Phi = cast<PHINode>(&*II++);
373 Phi->addIncoming(Acc[i], LoopBB);
374 Phi->addIncoming(UndefValue::get(Ty), EntryBB);
375 }
376
377 BasicBlock *ExitBB = BasicBlock::Create(Context, "bb2", F);
378 BranchInst::Create(LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)),
379 LoopBB);
380
381 Acc[0] = BinaryOperator::CreateAdd(Acc[0], Acc[1], "", ExitBB);
382 Acc[1] = BinaryOperator::CreateAdd(Acc[2], Acc[3], "", ExitBB);
383 Acc[2] = BinaryOperator::CreateAdd(Acc[4], Acc[5], "", ExitBB);
384 Acc[3] = BinaryOperator::CreateAdd(Acc[6], Acc[7], "", ExitBB);
385 Acc[0] = BinaryOperator::CreateAdd(Acc[0], Acc[1], "", ExitBB);
386 Acc[1] = BinaryOperator::CreateAdd(Acc[2], Acc[3], "", ExitBB);
387 Acc[0] = BinaryOperator::CreateAdd(Acc[0], Acc[1], "", ExitBB);
388
389 ReturnInst::Create(Context, nullptr, ExitBB);
390
391 ScalarEvolution SE = buildSE(*F);
392
393 EXPECT_NE(nullptr, SE.getSCEV(Acc[0]));
394}
395
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000396TEST_F(ScalarEvolutionsTest, CompareValueComplexity) {
397 IntegerType *IntPtrTy = M.getDataLayout().getIntPtrType(Context);
398 PointerType *IntPtrPtrTy = IntPtrTy->getPointerTo();
399
400 FunctionType *FTy =
401 FunctionType::get(Type::getVoidTy(Context), {IntPtrTy, IntPtrTy}, false);
James Y Knight13680222019-02-01 02:28:03 +0000402 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000403 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
404
405 Value *X = &*F->arg_begin();
406 Value *Y = &*std::next(F->arg_begin());
407
408 const int ValueDepth = 10;
409 for (int i = 0; i < ValueDepth; i++) {
410 X = new LoadInst(new IntToPtrInst(X, IntPtrPtrTy, "", EntryBB), "",
411 /*isVolatile*/ false, EntryBB);
412 Y = new LoadInst(new IntToPtrInst(Y, IntPtrPtrTy, "", EntryBB), "",
413 /*isVolatile*/ false, EntryBB);
414 }
415
416 auto *MulA = BinaryOperator::CreateMul(X, Y, "", EntryBB);
417 auto *MulB = BinaryOperator::CreateMul(Y, X, "", EntryBB);
418 ReturnInst::Create(Context, nullptr, EntryBB);
419
420 // This test isn't checking for correctness. Today making A and B resolve to
421 // the same SCEV would require deeper searching in CompareValueComplexity,
422 // which will slow down compilation. However, this test can fail (with LLVM's
423 // behavior still being correct) if we ever have a smarter
424 // CompareValueComplexity that is both fast and more accurate.
425
426 ScalarEvolution SE = buildSE(*F);
427 auto *A = SE.getSCEV(MulA);
428 auto *B = SE.getSCEV(MulB);
429 EXPECT_NE(A, B);
430}
431
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000432TEST_F(ScalarEvolutionsTest, SCEVAddExpr) {
433 Type *Ty32 = Type::getInt32Ty(Context);
434 Type *ArgTys[] = {Type::getInt64Ty(Context), Ty32};
435
436 FunctionType *FTy =
437 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
James Y Knight13680222019-02-01 02:28:03 +0000438 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000439
440 Argument *A1 = &*F->arg_begin();
441 Argument *A2 = &*(std::next(F->arg_begin()));
442 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
443
444 Instruction *Trunc = CastInst::CreateTruncOrBitCast(A1, Ty32, "", EntryBB);
445 Instruction *Mul1 = BinaryOperator::CreateMul(Trunc, A2, "", EntryBB);
446 Instruction *Add1 = BinaryOperator::CreateAdd(Mul1, Trunc, "", EntryBB);
447 Mul1 = BinaryOperator::CreateMul(Add1, Trunc, "", EntryBB);
448 Instruction *Add2 = BinaryOperator::CreateAdd(Mul1, Add1, "", EntryBB);
Chandler Carruthcd07efc2017-02-06 21:27:12 +0000449 // FIXME: The size of this is arbitrary and doesn't seem to change the
450 // result, but SCEV will do quadratic work for these so a large number here
451 // will be extremely slow. We should revisit what and how this is testing
452 // SCEV.
453 for (int i = 0; i < 10; i++) {
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000454 Mul1 = BinaryOperator::CreateMul(Add2, Add1, "", EntryBB);
455 Add1 = Add2;
456 Add2 = BinaryOperator::CreateAdd(Mul1, Add1, "", EntryBB);
457 }
458
459 ReturnInst::Create(Context, nullptr, EntryBB);
460 ScalarEvolution SE = buildSE(*F);
461 EXPECT_NE(nullptr, SE.getSCEV(Mul1));
462}
463
Sanjoy Dasb600d3f2017-04-14 15:50:04 +0000464static Instruction &GetInstByName(Function &F, StringRef Name) {
465 for (auto &I : instructions(F))
466 if (I.getName() == Name)
467 return I;
468 llvm_unreachable("Could not find instructions!");
469}
470
471TEST_F(ScalarEvolutionsTest, SCEVNormalization) {
472 LLVMContext C;
473 SMDiagnostic Err;
474 std::unique_ptr<Module> M = parseAssemblyString(
475 "target datalayout = \"e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128\" "
476 " "
477 "@var_0 = external global i32, align 4"
478 "@var_1 = external global i32, align 4"
479 "@var_2 = external global i32, align 4"
480 " "
481 "declare i32 @unknown(i32, i32, i32)"
482 " "
483 "define void @f_1(i8* nocapture %arr, i32 %n, i32* %A, i32* %B) "
484 " local_unnamed_addr { "
485 "entry: "
486 " br label %loop.ph "
487 " "
488 "loop.ph: "
489 " br label %loop "
490 " "
491 "loop: "
492 " %iv0 = phi i32 [ %iv0.inc, %loop ], [ 0, %loop.ph ] "
493 " %iv1 = phi i32 [ %iv1.inc, %loop ], [ -2147483648, %loop.ph ] "
494 " %iv0.inc = add i32 %iv0, 1 "
495 " %iv1.inc = add i32 %iv1, 3 "
496 " br i1 undef, label %for.end.loopexit, label %loop "
497 " "
498 "for.end.loopexit: "
499 " ret void "
500 "} "
Sanjoy Dasbbebcb62017-04-25 00:09:19 +0000501 " "
502 "define void @f_2(i32 %a, i32 %b, i32 %c, i32 %d) "
503 " local_unnamed_addr { "
504 "entry: "
505 " br label %loop_0 "
506 " "
507 "loop_0: "
508 " br i1 undef, label %loop_0, label %loop_1 "
509 " "
510 "loop_1: "
511 " br i1 undef, label %loop_2, label %loop_1 "
512 " "
513 " "
514 "loop_2: "
515 " br i1 undef, label %end, label %loop_2 "
516 " "
517 "end: "
518 " ret void "
519 "} "
Sanjoy Dasb600d3f2017-04-14 15:50:04 +0000520 ,
521 Err, C);
522
523 assert(M && "Could not parse module?");
524 assert(!verifyModule(*M) && "Must have been well formed!");
525
Sanjoy Das044f9562017-04-14 23:47:53 +0000526 runWithSE(*M, "f_1", [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
Sanjoy Dasb600d3f2017-04-14 15:50:04 +0000527 auto &I0 = GetInstByName(F, "iv0");
528 auto &I1 = *I0.getNextNode();
529
530 auto *S0 = cast<SCEVAddRecExpr>(SE.getSCEV(&I0));
531 PostIncLoopSet Loops;
532 Loops.insert(S0->getLoop());
533 auto *N0 = normalizeForPostIncUse(S0, Loops, SE);
534 auto *D0 = denormalizeForPostIncUse(N0, Loops, SE);
535 EXPECT_EQ(S0, D0) << *S0 << " " << *D0;
536
537 auto *S1 = cast<SCEVAddRecExpr>(SE.getSCEV(&I1));
538 Loops.clear();
539 Loops.insert(S1->getLoop());
540 auto *N1 = normalizeForPostIncUse(S1, Loops, SE);
541 auto *D1 = denormalizeForPostIncUse(N1, Loops, SE);
542 EXPECT_EQ(S1, D1) << *S1 << " " << *D1;
543 });
Sanjoy Dasbbebcb62017-04-25 00:09:19 +0000544
545 runWithSE(*M, "f_2", [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
546 auto *L2 = *LI.begin();
547 auto *L1 = *std::next(LI.begin());
548 auto *L0 = *std::next(LI.begin(), 2);
549
550 auto GetAddRec = [&SE](const Loop *L, std::initializer_list<const SCEV *> Ops) {
551 SmallVector<const SCEV *, 4> OpsCopy(Ops);
552 return SE.getAddRecExpr(OpsCopy, L, SCEV::FlagAnyWrap);
553 };
554
555 auto GetAdd = [&SE](std::initializer_list<const SCEV *> Ops) {
556 SmallVector<const SCEV *, 4> OpsCopy(Ops);
557 return SE.getAddExpr(OpsCopy, SCEV::FlagAnyWrap);
558 };
559
560 // We first populate the AddRecs vector with a few "interesting" SCEV
561 // expressions, and then we go through the list and assert that each
562 // expression in it has an invertible normalization.
563
564 std::vector<const SCEV *> Exprs;
565 {
566 const SCEV *V0 = SE.getSCEV(&*F.arg_begin());
567 const SCEV *V1 = SE.getSCEV(&*std::next(F.arg_begin(), 1));
568 const SCEV *V2 = SE.getSCEV(&*std::next(F.arg_begin(), 2));
569 const SCEV *V3 = SE.getSCEV(&*std::next(F.arg_begin(), 3));
570
571 Exprs.push_back(GetAddRec(L0, {V0})); // 0
572 Exprs.push_back(GetAddRec(L0, {V0, V1})); // 1
573 Exprs.push_back(GetAddRec(L0, {V0, V1, V2})); // 2
574 Exprs.push_back(GetAddRec(L0, {V0, V1, V2, V3})); // 3
575
576 Exprs.push_back(
577 GetAddRec(L1, {Exprs[1], Exprs[2], Exprs[3], Exprs[0]})); // 4
578 Exprs.push_back(
579 GetAddRec(L1, {Exprs[1], Exprs[2], Exprs[0], Exprs[3]})); // 5
580 Exprs.push_back(
581 GetAddRec(L1, {Exprs[1], Exprs[3], Exprs[3], Exprs[1]})); // 6
582
583 Exprs.push_back(GetAdd({Exprs[6], Exprs[3], V2})); // 7
584
585 Exprs.push_back(
586 GetAddRec(L2, {Exprs[4], Exprs[3], Exprs[3], Exprs[5]})); // 8
587
588 Exprs.push_back(
589 GetAddRec(L2, {Exprs[4], Exprs[6], Exprs[7], Exprs[3], V0})); // 9
590 }
591
592 std::vector<PostIncLoopSet> LoopSets;
593 for (int i = 0; i < 8; i++) {
594 LoopSets.emplace_back();
595 if (i & 1)
596 LoopSets.back().insert(L0);
597 if (i & 2)
598 LoopSets.back().insert(L1);
599 if (i & 4)
600 LoopSets.back().insert(L2);
601 }
602
603 for (const auto &LoopSet : LoopSets)
604 for (auto *S : Exprs) {
605 {
606 auto *N = llvm::normalizeForPostIncUse(S, LoopSet, SE);
607 auto *D = llvm::denormalizeForPostIncUse(N, LoopSet, SE);
608
609 // Normalization and then denormalizing better give us back the same
610 // value.
611 EXPECT_EQ(S, D) << "S = " << *S << " D = " << *D << " N = " << *N;
612 }
613 {
614 auto *D = llvm::denormalizeForPostIncUse(S, LoopSet, SE);
615 auto *N = llvm::normalizeForPostIncUse(D, LoopSet, SE);
616
617 // Denormalization and then normalizing better give us back the same
618 // value.
619 EXPECT_EQ(S, N) << "S = " << *S << " N = " << *N;
620 }
621 }
622 });
Sanjoy Dasb600d3f2017-04-14 15:50:04 +0000623}
624
Wei Mi8c405332017-04-17 20:40:05 +0000625// Expect the call of getZeroExtendExpr will not cost exponential time.
626TEST_F(ScalarEvolutionsTest, SCEVZeroExtendExpr) {
627 LLVMContext C;
628 SMDiagnostic Err;
629
630 // Generate a function like below:
631 // define void @foo() {
632 // entry:
633 // br label %for.cond
634 //
635 // for.cond:
636 // %0 = phi i64 [ 100, %entry ], [ %dec, %for.inc ]
637 // %cmp = icmp sgt i64 %0, 90
638 // br i1 %cmp, label %for.inc, label %for.cond1
639 //
640 // for.inc:
641 // %dec = add nsw i64 %0, -1
642 // br label %for.cond
643 //
644 // for.cond1:
645 // %1 = phi i64 [ 100, %for.cond ], [ %dec5, %for.inc2 ]
646 // %cmp3 = icmp sgt i64 %1, 90
647 // br i1 %cmp3, label %for.inc2, label %for.cond4
648 //
649 // for.inc2:
650 // %dec5 = add nsw i64 %1, -1
651 // br label %for.cond1
652 //
653 // ......
654 //
655 // for.cond89:
656 // %19 = phi i64 [ 100, %for.cond84 ], [ %dec94, %for.inc92 ]
657 // %cmp93 = icmp sgt i64 %19, 90
658 // br i1 %cmp93, label %for.inc92, label %for.end
659 //
660 // for.inc92:
661 // %dec94 = add nsw i64 %19, -1
662 // br label %for.cond89
663 //
664 // for.end:
665 // %gep = getelementptr i8, i8* null, i64 %dec
666 // %gep6 = getelementptr i8, i8* %gep, i64 %dec5
667 // ......
668 // %gep95 = getelementptr i8, i8* %gep91, i64 %dec94
669 // ret void
670 // }
671 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context), {}, false);
James Y Knight13680222019-02-01 02:28:03 +0000672 Function *F = Function::Create(FTy, Function::ExternalLinkage, "foo", M);
Wei Mi8c405332017-04-17 20:40:05 +0000673
674 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
675 BasicBlock *CondBB = BasicBlock::Create(Context, "for.cond", F);
676 BasicBlock *EndBB = BasicBlock::Create(Context, "for.end", F);
677 BranchInst::Create(CondBB, EntryBB);
678 BasicBlock *PrevBB = EntryBB;
679
680 Type *I64Ty = Type::getInt64Ty(Context);
681 Type *I8Ty = Type::getInt8Ty(Context);
682 Type *I8PtrTy = Type::getInt8PtrTy(Context);
683 Value *Accum = Constant::getNullValue(I8PtrTy);
684 int Iters = 20;
685 for (int i = 0; i < Iters; i++) {
686 BasicBlock *IncBB = BasicBlock::Create(Context, "for.inc", F, EndBB);
687 auto *PN = PHINode::Create(I64Ty, 2, "", CondBB);
688 PN->addIncoming(ConstantInt::get(Context, APInt(64, 100)), PrevBB);
689 auto *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SGT, PN,
690 ConstantInt::get(Context, APInt(64, 90)), "cmp",
691 CondBB);
692 BasicBlock *NextBB;
693 if (i != Iters - 1)
694 NextBB = BasicBlock::Create(Context, "for.cond", F, EndBB);
695 else
696 NextBB = EndBB;
697 BranchInst::Create(IncBB, NextBB, Cmp, CondBB);
698 auto *Dec = BinaryOperator::CreateNSWAdd(
699 PN, ConstantInt::get(Context, APInt(64, -1)), "dec", IncBB);
700 PN->addIncoming(Dec, IncBB);
701 BranchInst::Create(CondBB, IncBB);
702
Max Kazantsev65cb9d72018-11-08 05:07:58 +0000703 Accum = GetElementPtrInst::Create(I8Ty, Accum, PN, "gep", EndBB);
Wei Mi8c405332017-04-17 20:40:05 +0000704
705 PrevBB = CondBB;
706 CondBB = NextBB;
707 }
708 ReturnInst::Create(Context, nullptr, EndBB);
709 ScalarEvolution SE = buildSE(*F);
710 const SCEV *S = SE.getSCEV(Accum);
711 Type *I128Ty = Type::getInt128Ty(Context);
712 SE.getZeroExtendExpr(S, I128Ty);
713}
Keno Fischer090f1952017-05-27 03:22:55 +0000714
715// Make sure that SCEV doesn't introduce illegal ptrtoint/inttoptr instructions
716TEST_F(ScalarEvolutionsTest, SCEVZeroExtendExprNonIntegral) {
717 /*
718 * Create the following code:
719 * func(i64 addrspace(10)* %arg)
720 * top:
721 * br label %L.ph
722 * L.ph:
723 * br label %L
724 * L:
725 * %phi = phi i64 [i64 0, %L.ph], [ %add, %L2 ]
726 * %add = add i64 %phi2, 1
727 * br i1 undef, label %post, label %L2
728 * post:
729 * %gepbase = getelementptr i64 addrspace(10)* %arg, i64 1
730 * #= %gep = getelementptr i64 addrspace(10)* %gepbase, i64 %add =#
731 * ret void
732 *
733 * We will create the appropriate SCEV expression for %gep and expand it,
734 * then check that no inttoptr/ptrtoint instructions got inserted.
735 */
736
737 // Create a module with non-integral pointers in it's datalayout
738 Module NIM("nonintegral", Context);
739 std::string DataLayout = M.getDataLayoutStr();
740 if (!DataLayout.empty())
741 DataLayout += "-";
742 DataLayout += "ni:10";
743 NIM.setDataLayout(DataLayout);
744
745 Type *T_int1 = Type::getInt1Ty(Context);
746 Type *T_int64 = Type::getInt64Ty(Context);
747 Type *T_pint64 = T_int64->getPointerTo(10);
748
749 FunctionType *FTy =
750 FunctionType::get(Type::getVoidTy(Context), {T_pint64}, false);
James Y Knight13680222019-02-01 02:28:03 +0000751 Function *F = Function::Create(FTy, Function::ExternalLinkage, "foo", NIM);
Keno Fischer090f1952017-05-27 03:22:55 +0000752
753 Argument *Arg = &*F->arg_begin();
754
755 BasicBlock *Top = BasicBlock::Create(Context, "top", F);
756 BasicBlock *LPh = BasicBlock::Create(Context, "L.ph", F);
757 BasicBlock *L = BasicBlock::Create(Context, "L", F);
758 BasicBlock *Post = BasicBlock::Create(Context, "post", F);
759
760 IRBuilder<> Builder(Top);
761 Builder.CreateBr(LPh);
762
763 Builder.SetInsertPoint(LPh);
764 Builder.CreateBr(L);
765
766 Builder.SetInsertPoint(L);
767 PHINode *Phi = Builder.CreatePHI(T_int64, 2);
768 Value *Add = Builder.CreateAdd(Phi, ConstantInt::get(T_int64, 1), "add");
769 Builder.CreateCondBr(UndefValue::get(T_int1), L, Post);
770 Phi->addIncoming(ConstantInt::get(T_int64, 0), LPh);
771 Phi->addIncoming(Add, L);
772
773 Builder.SetInsertPoint(Post);
Gor Nishanove5d29112017-05-27 05:24:30 +0000774 Value *GepBase = Builder.CreateGEP(Arg, ConstantInt::get(T_int64, 1));
Keno Fischer090f1952017-05-27 03:22:55 +0000775 Instruction *Ret = Builder.CreateRetVoid();
776
777 ScalarEvolution SE = buildSE(*F);
778 auto *AddRec =
779 SE.getAddRecExpr(SE.getUnknown(GepBase), SE.getConstant(T_int64, 1),
780 LI->getLoopFor(L), SCEV::FlagNUW);
781
782 SCEVExpander Exp(SE, NIM.getDataLayout(), "expander");
783 Exp.disableCanonicalMode();
784 Exp.expandCodeFor(AddRec, T_pint64, Ret);
785
786 // Make sure none of the instructions inserted were inttoptr/ptrtoint.
787 // The verifier will check this.
788 EXPECT_FALSE(verifyFunction(*F, &errs()));
789}
790
Max Kazantsev2cb36532017-08-03 08:41:30 +0000791// Make sure that SCEV invalidates exit limits after invalidating the values it
792// depends on when we forget a loop.
793TEST_F(ScalarEvolutionsTest, SCEVExitLimitForgetLoop) {
794 /*
795 * Create the following code:
796 * func(i64 addrspace(10)* %arg)
797 * top:
798 * br label %L.ph
799 * L.ph:
800 * br label %L
801 * L:
802 * %phi = phi i64 [i64 0, %L.ph], [ %add, %L2 ]
803 * %add = add i64 %phi2, 1
804 * %cond = icmp slt i64 %add, 1000; then becomes 2000.
805 * br i1 %cond, label %post, label %L2
806 * post:
807 * ret void
808 *
809 */
810
811 // Create a module with non-integral pointers in it's datalayout
812 Module NIM("nonintegral", Context);
813 std::string DataLayout = M.getDataLayoutStr();
814 if (!DataLayout.empty())
815 DataLayout += "-";
816 DataLayout += "ni:10";
817 NIM.setDataLayout(DataLayout);
818
819 Type *T_int64 = Type::getInt64Ty(Context);
820 Type *T_pint64 = T_int64->getPointerTo(10);
821
822 FunctionType *FTy =
823 FunctionType::get(Type::getVoidTy(Context), {T_pint64}, false);
James Y Knight13680222019-02-01 02:28:03 +0000824 Function *F = Function::Create(FTy, Function::ExternalLinkage, "foo", NIM);
Max Kazantsev2cb36532017-08-03 08:41:30 +0000825
Max Kazantsev2cb36532017-08-03 08:41:30 +0000826 BasicBlock *Top = BasicBlock::Create(Context, "top", F);
827 BasicBlock *LPh = BasicBlock::Create(Context, "L.ph", F);
828 BasicBlock *L = BasicBlock::Create(Context, "L", F);
829 BasicBlock *Post = BasicBlock::Create(Context, "post", F);
830
831 IRBuilder<> Builder(Top);
832 Builder.CreateBr(LPh);
833
834 Builder.SetInsertPoint(LPh);
835 Builder.CreateBr(L);
836
837 Builder.SetInsertPoint(L);
838 PHINode *Phi = Builder.CreatePHI(T_int64, 2);
839 auto *Add = cast<Instruction>(
840 Builder.CreateAdd(Phi, ConstantInt::get(T_int64, 1), "add"));
841 auto *Limit = ConstantInt::get(T_int64, 1000);
842 auto *Cond = cast<Instruction>(
843 Builder.CreateICmp(ICmpInst::ICMP_SLT, Add, Limit, "cond"));
844 auto *Br = cast<Instruction>(Builder.CreateCondBr(Cond, L, Post));
845 Phi->addIncoming(ConstantInt::get(T_int64, 0), LPh);
846 Phi->addIncoming(Add, L);
847
848 Builder.SetInsertPoint(Post);
849 Builder.CreateRetVoid();
850
851 ScalarEvolution SE = buildSE(*F);
852 auto *Loop = LI->getLoopFor(L);
853 const SCEV *EC = SE.getBackedgeTakenCount(Loop);
854 EXPECT_FALSE(isa<SCEVCouldNotCompute>(EC));
Max Kazantsevba1e70e2017-08-04 05:06:44 +0000855 EXPECT_TRUE(isa<SCEVConstant>(EC));
Max Kazantsev6e724762017-08-04 06:03:51 +0000856 EXPECT_EQ(cast<SCEVConstant>(EC)->getAPInt().getLimitedValue(), 999u);
Max Kazantsev2cb36532017-08-03 08:41:30 +0000857
Sanjoy Dase6b995f2017-10-13 05:50:52 +0000858 // The add recurrence {5,+,1} does not correspond to any PHI in the IR, and
859 // that is relevant to this test.
860 auto *Five = SE.getConstant(APInt(/*numBits=*/64, 5));
861 auto *AR =
862 SE.getAddRecExpr(Five, SE.getOne(T_int64), Loop, SCEV::FlagAnyWrap);
863 const SCEV *ARAtLoopExit = SE.getSCEVAtScope(AR, nullptr);
864 EXPECT_FALSE(isa<SCEVCouldNotCompute>(ARAtLoopExit));
865 EXPECT_TRUE(isa<SCEVConstant>(ARAtLoopExit));
866 EXPECT_EQ(cast<SCEVConstant>(ARAtLoopExit)->getAPInt().getLimitedValue(),
867 1004u);
868
Max Kazantsev2cb36532017-08-03 08:41:30 +0000869 SE.forgetLoop(Loop);
870 Br->eraseFromParent();
871 Cond->eraseFromParent();
872
873 Builder.SetInsertPoint(L);
Benjamin Kramera73b4102017-08-03 15:59:37 +0000874 auto *NewCond = Builder.CreateICmp(
875 ICmpInst::ICMP_SLT, Add, ConstantInt::get(T_int64, 2000), "new.cond");
876 Builder.CreateCondBr(NewCond, L, Post);
Max Kazantsev2cb36532017-08-03 08:41:30 +0000877 const SCEV *NewEC = SE.getBackedgeTakenCount(Loop);
Max Kazantsevba1e70e2017-08-04 05:06:44 +0000878 EXPECT_FALSE(isa<SCEVCouldNotCompute>(NewEC));
879 EXPECT_TRUE(isa<SCEVConstant>(NewEC));
Max Kazantsev6e724762017-08-04 06:03:51 +0000880 EXPECT_EQ(cast<SCEVConstant>(NewEC)->getAPInt().getLimitedValue(), 1999u);
Sanjoy Dase6b995f2017-10-13 05:50:52 +0000881 const SCEV *NewARAtLoopExit = SE.getSCEVAtScope(AR, nullptr);
882 EXPECT_FALSE(isa<SCEVCouldNotCompute>(NewARAtLoopExit));
883 EXPECT_TRUE(isa<SCEVConstant>(NewARAtLoopExit));
884 EXPECT_EQ(cast<SCEVConstant>(NewARAtLoopExit)->getAPInt().getLimitedValue(),
885 2004u);
Max Kazantsev2cb36532017-08-03 08:41:30 +0000886}
887
Sanjoy Das3a5e2522017-10-17 01:03:56 +0000888// Make sure that SCEV invalidates exit limits after invalidating the values it
889// depends on when we forget a value.
890TEST_F(ScalarEvolutionsTest, SCEVExitLimitForgetValue) {
891 /*
892 * Create the following code:
893 * func(i64 addrspace(10)* %arg)
894 * top:
895 * br label %L.ph
896 * L.ph:
897 * %load = load i64 addrspace(10)* %arg
898 * br label %L
899 * L:
900 * %phi = phi i64 [i64 0, %L.ph], [ %add, %L2 ]
901 * %add = add i64 %phi2, 1
902 * %cond = icmp slt i64 %add, %load ; then becomes 2000.
903 * br i1 %cond, label %post, label %L2
904 * post:
905 * ret void
906 *
907 */
908
909 // Create a module with non-integral pointers in it's datalayout
910 Module NIM("nonintegral", Context);
911 std::string DataLayout = M.getDataLayoutStr();
912 if (!DataLayout.empty())
913 DataLayout += "-";
914 DataLayout += "ni:10";
915 NIM.setDataLayout(DataLayout);
916
917 Type *T_int64 = Type::getInt64Ty(Context);
918 Type *T_pint64 = T_int64->getPointerTo(10);
919
920 FunctionType *FTy =
921 FunctionType::get(Type::getVoidTy(Context), {T_pint64}, false);
James Y Knight13680222019-02-01 02:28:03 +0000922 Function *F = Function::Create(FTy, Function::ExternalLinkage, "foo", NIM);
Sanjoy Das3a5e2522017-10-17 01:03:56 +0000923
924 Argument *Arg = &*F->arg_begin();
925
926 BasicBlock *Top = BasicBlock::Create(Context, "top", F);
927 BasicBlock *LPh = BasicBlock::Create(Context, "L.ph", F);
928 BasicBlock *L = BasicBlock::Create(Context, "L", F);
929 BasicBlock *Post = BasicBlock::Create(Context, "post", F);
930
931 IRBuilder<> Builder(Top);
932 Builder.CreateBr(LPh);
933
934 Builder.SetInsertPoint(LPh);
935 auto *Load = cast<Instruction>(Builder.CreateLoad(T_int64, Arg, "load"));
936 Builder.CreateBr(L);
937
938 Builder.SetInsertPoint(L);
939 PHINode *Phi = Builder.CreatePHI(T_int64, 2);
940 auto *Add = cast<Instruction>(
941 Builder.CreateAdd(Phi, ConstantInt::get(T_int64, 1), "add"));
942 auto *Cond = cast<Instruction>(
943 Builder.CreateICmp(ICmpInst::ICMP_SLT, Add, Load, "cond"));
944 auto *Br = cast<Instruction>(Builder.CreateCondBr(Cond, L, Post));
945 Phi->addIncoming(ConstantInt::get(T_int64, 0), LPh);
946 Phi->addIncoming(Add, L);
947
948 Builder.SetInsertPoint(Post);
949 Builder.CreateRetVoid();
950
951 ScalarEvolution SE = buildSE(*F);
952 auto *Loop = LI->getLoopFor(L);
953 const SCEV *EC = SE.getBackedgeTakenCount(Loop);
954 EXPECT_FALSE(isa<SCEVCouldNotCompute>(EC));
955 EXPECT_FALSE(isa<SCEVConstant>(EC));
956
957 SE.forgetValue(Load);
958 Br->eraseFromParent();
959 Cond->eraseFromParent();
960 Load->eraseFromParent();
961
962 Builder.SetInsertPoint(L);
963 auto *NewCond = Builder.CreateICmp(
964 ICmpInst::ICMP_SLT, Add, ConstantInt::get(T_int64, 2000), "new.cond");
965 Builder.CreateCondBr(NewCond, L, Post);
966 const SCEV *NewEC = SE.getBackedgeTakenCount(Loop);
967 EXPECT_FALSE(isa<SCEVCouldNotCompute>(NewEC));
968 EXPECT_TRUE(isa<SCEVConstant>(NewEC));
969 EXPECT_EQ(cast<SCEVConstant>(NewEC)->getAPInt().getLimitedValue(), 1999u);
970}
971
Daniel Neilson3f0e4ad2017-09-05 19:54:03 +0000972TEST_F(ScalarEvolutionsTest, SCEVAddRecFromPHIwithLargeConstants) {
973 // Reference: https://reviews.llvm.org/D37265
974 // Make sure that SCEV does not blow up when constructing an AddRec
975 // with predicates for a phi with the update pattern:
976 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
977 // when either the initial value of the Phi or the InvariantAccum are
978 // constants that are too large to fit in an ix but are zero when truncated to
979 // ix.
980 FunctionType *FTy =
981 FunctionType::get(Type::getVoidTy(Context), std::vector<Type *>(), false);
James Y Knight13680222019-02-01 02:28:03 +0000982 Function *F =
983 Function::Create(FTy, Function::ExternalLinkage, "addrecphitest", M);
Daniel Neilson3f0e4ad2017-09-05 19:54:03 +0000984
985 /*
986 Create IR:
987 entry:
988 br label %loop
989 loop:
990 %0 = phi i64 [-9223372036854775808, %entry], [%3, %loop]
991 %1 = shl i64 %0, 32
992 %2 = ashr exact i64 %1, 32
993 %3 = add i64 %2, -9223372036854775808
994 br i1 undef, label %exit, label %loop
995 exit:
996 ret void
997 */
998 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
999 BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
1000 BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
1001
1002 // entry:
1003 BranchInst::Create(LoopBB, EntryBB);
1004 // loop:
1005 auto *MinInt64 =
1006 ConstantInt::get(Context, APInt(64, 0x8000000000000000U, true));
1007 auto *Int64_32 = ConstantInt::get(Context, APInt(64, 32));
1008 auto *Br = BranchInst::Create(
1009 LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)), LoopBB);
1010 auto *Phi = PHINode::Create(Type::getInt64Ty(Context), 2, "", Br);
1011 auto *Shl = BinaryOperator::CreateShl(Phi, Int64_32, "", Br);
1012 auto *AShr = BinaryOperator::CreateExactAShr(Shl, Int64_32, "", Br);
1013 auto *Add = BinaryOperator::CreateAdd(AShr, MinInt64, "", Br);
1014 Phi->addIncoming(MinInt64, EntryBB);
1015 Phi->addIncoming(Add, LoopBB);
1016 // exit:
1017 ReturnInst::Create(Context, nullptr, ExitBB);
1018
1019 // Make sure that SCEV doesn't blow up
1020 ScalarEvolution SE = buildSE(*F);
1021 SCEVUnionPredicate Preds;
1022 const SCEV *Expr = SE.getSCEV(Phi);
1023 EXPECT_NE(nullptr, Expr);
1024 EXPECT_TRUE(isa<SCEVUnknown>(Expr));
1025 auto Result = SE.createAddRecFromPHIWithCasts(cast<SCEVUnknown>(Expr));
1026}
1027
Daniel Neilson5acfd1d2017-10-11 19:05:14 +00001028TEST_F(ScalarEvolutionsTest, SCEVAddRecFromPHIwithLargeConstantAccum) {
1029 // Make sure that SCEV does not blow up when constructing an AddRec
1030 // with predicates for a phi with the update pattern:
1031 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
1032 // when the InvariantAccum is a constant that is too large to fit in an
1033 // ix but are zero when truncated to ix, and the initial value of the
1034 // phi is not a constant.
1035 Type *Int32Ty = Type::getInt32Ty(Context);
1036 SmallVector<Type *, 1> Types;
1037 Types.push_back(Int32Ty);
1038 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context), Types, false);
James Y Knight13680222019-02-01 02:28:03 +00001039 Function *F =
1040 Function::Create(FTy, Function::ExternalLinkage, "addrecphitest", M);
Daniel Neilson5acfd1d2017-10-11 19:05:14 +00001041
1042 /*
1043 Create IR:
1044 define @addrecphitest(i32)
1045 entry:
1046 br label %loop
1047 loop:
1048 %1 = phi i32 [%0, %entry], [%4, %loop]
1049 %2 = shl i32 %1, 16
1050 %3 = ashr exact i32 %2, 16
1051 %4 = add i32 %3, -2147483648
1052 br i1 undef, label %exit, label %loop
1053 exit:
1054 ret void
1055 */
1056 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
1057 BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
1058 BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
1059
1060 // entry:
1061 BranchInst::Create(LoopBB, EntryBB);
1062 // loop:
1063 auto *MinInt32 = ConstantInt::get(Context, APInt(32, 0x80000000U, true));
1064 auto *Int32_16 = ConstantInt::get(Context, APInt(32, 16));
1065 auto *Br = BranchInst::Create(
1066 LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)), LoopBB);
1067 auto *Phi = PHINode::Create(Int32Ty, 2, "", Br);
1068 auto *Shl = BinaryOperator::CreateShl(Phi, Int32_16, "", Br);
1069 auto *AShr = BinaryOperator::CreateExactAShr(Shl, Int32_16, "", Br);
1070 auto *Add = BinaryOperator::CreateAdd(AShr, MinInt32, "", Br);
1071 auto *Arg = &*(F->arg_begin());
1072 Phi->addIncoming(Arg, EntryBB);
1073 Phi->addIncoming(Add, LoopBB);
1074 // exit:
1075 ReturnInst::Create(Context, nullptr, ExitBB);
1076
1077 // Make sure that SCEV doesn't blow up
1078 ScalarEvolution SE = buildSE(*F);
1079 SCEVUnionPredicate Preds;
1080 const SCEV *Expr = SE.getSCEV(Phi);
1081 EXPECT_NE(nullptr, Expr);
1082 EXPECT_TRUE(isa<SCEVUnknown>(Expr));
1083 auto Result = SE.createAddRecFromPHIWithCasts(cast<SCEVUnknown>(Expr));
1084}
1085
Daniel Neilson1341ac22017-09-22 15:47:57 +00001086TEST_F(ScalarEvolutionsTest, SCEVFoldSumOfTruncs) {
1087 // Verify that the following SCEV gets folded to a zero:
1088 // (-1 * (trunc i64 (-1 * %0) to i32)) + (-1 * (trunc i64 %0 to i32)
1089 Type *ArgTy = Type::getInt64Ty(Context);
1090 Type *Int32Ty = Type::getInt32Ty(Context);
1091 SmallVector<Type *, 1> Types;
1092 Types.push_back(ArgTy);
1093 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context), Types, false);
James Y Knight13680222019-02-01 02:28:03 +00001094 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
Daniel Neilson1341ac22017-09-22 15:47:57 +00001095 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
1096 ReturnInst::Create(Context, nullptr, BB);
1097
1098 ScalarEvolution SE = buildSE(*F);
1099
1100 auto *Arg = &*(F->arg_begin());
1101 const auto *ArgSCEV = SE.getSCEV(Arg);
1102
1103 // Build the SCEV
1104 const auto *A0 = SE.getNegativeSCEV(ArgSCEV);
1105 const auto *A1 = SE.getTruncateExpr(A0, Int32Ty);
1106 const auto *A = SE.getNegativeSCEV(A1);
1107
1108 const auto *B0 = SE.getTruncateExpr(ArgSCEV, Int32Ty);
1109 const auto *B = SE.getNegativeSCEV(B0);
1110
1111 const auto *Expr = SE.getAddExpr(A, B);
Daniel Neilson1341ac22017-09-22 15:47:57 +00001112 // Verify that the SCEV was folded to 0
1113 const auto *ZeroConst = SE.getConstant(Int32Ty, 0);
1114 EXPECT_EQ(Expr, ZeroConst);
1115}
1116
Max Kazantsev87f4a3d2017-11-16 05:10:56 +00001117// Check that we can correctly identify the points at which the SCEV of the
1118// AddRec can be expanded.
1119TEST_F(ScalarEvolutionsTest, SCEVExpanderIsSafeToExpandAt) {
1120 /*
1121 * Create the following code:
1122 * func(i64 addrspace(10)* %arg)
1123 * top:
1124 * br label %L.ph
1125 * L.ph:
1126 * br label %L
1127 * L:
1128 * %phi = phi i64 [i64 0, %L.ph], [ %add, %L2 ]
1129 * %add = add i64 %phi2, 1
1130 * %cond = icmp slt i64 %add, 1000; then becomes 2000.
1131 * br i1 %cond, label %post, label %L2
1132 * post:
1133 * ret void
1134 *
1135 */
1136
1137 // Create a module with non-integral pointers in it's datalayout
1138 Module NIM("nonintegral", Context);
1139 std::string DataLayout = M.getDataLayoutStr();
1140 if (!DataLayout.empty())
1141 DataLayout += "-";
1142 DataLayout += "ni:10";
1143 NIM.setDataLayout(DataLayout);
1144
1145 Type *T_int64 = Type::getInt64Ty(Context);
1146 Type *T_pint64 = T_int64->getPointerTo(10);
1147
1148 FunctionType *FTy =
1149 FunctionType::get(Type::getVoidTy(Context), {T_pint64}, false);
James Y Knight13680222019-02-01 02:28:03 +00001150 Function *F = Function::Create(FTy, Function::ExternalLinkage, "foo", NIM);
Max Kazantsev87f4a3d2017-11-16 05:10:56 +00001151
1152 BasicBlock *Top = BasicBlock::Create(Context, "top", F);
1153 BasicBlock *LPh = BasicBlock::Create(Context, "L.ph", F);
1154 BasicBlock *L = BasicBlock::Create(Context, "L", F);
1155 BasicBlock *Post = BasicBlock::Create(Context, "post", F);
1156
1157 IRBuilder<> Builder(Top);
1158 Builder.CreateBr(LPh);
1159
1160 Builder.SetInsertPoint(LPh);
1161 Builder.CreateBr(L);
1162
1163 Builder.SetInsertPoint(L);
1164 PHINode *Phi = Builder.CreatePHI(T_int64, 2);
1165 auto *Add = cast<Instruction>(
1166 Builder.CreateAdd(Phi, ConstantInt::get(T_int64, 1), "add"));
1167 auto *Limit = ConstantInt::get(T_int64, 1000);
1168 auto *Cond = cast<Instruction>(
1169 Builder.CreateICmp(ICmpInst::ICMP_SLT, Add, Limit, "cond"));
1170 Builder.CreateCondBr(Cond, L, Post);
1171 Phi->addIncoming(ConstantInt::get(T_int64, 0), LPh);
1172 Phi->addIncoming(Add, L);
1173
1174 Builder.SetInsertPoint(Post);
1175 Builder.CreateRetVoid();
1176
1177 ScalarEvolution SE = buildSE(*F);
1178 const SCEV *S = SE.getSCEV(Phi);
1179 EXPECT_TRUE(isa<SCEVAddRecExpr>(S));
1180 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
1181 EXPECT_TRUE(AR->isAffine());
1182 EXPECT_FALSE(isSafeToExpandAt(AR, Top->getTerminator(), SE));
1183 EXPECT_FALSE(isSafeToExpandAt(AR, LPh->getTerminator(), SE));
1184 EXPECT_TRUE(isSafeToExpandAt(AR, L->getTerminator(), SE));
1185 EXPECT_TRUE(isSafeToExpandAt(AR, Post->getTerminator(), SE));
1186}
1187
Serguei Katkovda56a7f2017-12-27 08:26:22 +00001188// Check that SCEV expander does not use the nuw instruction
1189// for expansion.
1190TEST_F(ScalarEvolutionsTest, SCEVExpanderNUW) {
1191 /*
1192 * Create the following code:
1193 * func(i64 %a)
1194 * entry:
1195 * br false, label %exit, label %body
1196 * body:
1197 * %s1 = add i64 %a, -1
1198 * br label %exit
1199 * exit:
1200 * %s = add nuw i64 %a, -1
1201 * ret %s
1202 */
1203
1204 // Create a module.
1205 Module M("SCEVExpanderNUW", Context);
1206
1207 Type *T_int64 = Type::getInt64Ty(Context);
1208
1209 FunctionType *FTy =
1210 FunctionType::get(Type::getVoidTy(Context), { T_int64 }, false);
James Y Knight13680222019-02-01 02:28:03 +00001211 Function *F = Function::Create(FTy, Function::ExternalLinkage, "func", M);
Serguei Katkovda56a7f2017-12-27 08:26:22 +00001212 Argument *Arg = &*F->arg_begin();
1213 ConstantInt *C = ConstantInt::get(Context, APInt(64, -1));
1214
1215 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1216 BasicBlock *Body = BasicBlock::Create(Context, "body", F);
1217 BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1218
1219 IRBuilder<> Builder(Entry);
1220 ConstantInt *Cond = ConstantInt::get(Context, APInt(1, 0));
1221 Builder.CreateCondBr(Cond, Exit, Body);
1222
1223 Builder.SetInsertPoint(Body);
1224 auto *S1 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1225 Builder.CreateBr(Exit);
1226
1227 Builder.SetInsertPoint(Exit);
1228 auto *S2 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1229 S2->setHasNoUnsignedWrap(true);
1230 auto *R = cast<Instruction>(Builder.CreateRetVoid());
1231
1232 ScalarEvolution SE = buildSE(*F);
1233 const SCEV *S = SE.getSCEV(S1);
1234 EXPECT_TRUE(isa<SCEVAddExpr>(S));
1235 SCEVExpander Exp(SE, M.getDataLayout(), "expander");
1236 auto *I = cast<Instruction>(Exp.expandCodeFor(S, nullptr, R));
1237 EXPECT_FALSE(I->hasNoUnsignedWrap());
1238}
1239
1240// Check that SCEV expander does not use the nsw instruction
1241// for expansion.
1242TEST_F(ScalarEvolutionsTest, SCEVExpanderNSW) {
1243 /*
1244 * Create the following code:
1245 * func(i64 %a)
1246 * entry:
1247 * br false, label %exit, label %body
1248 * body:
1249 * %s1 = add i64 %a, -1
1250 * br label %exit
1251 * exit:
1252 * %s = add nsw i64 %a, -1
1253 * ret %s
1254 */
1255
1256 // Create a module.
1257 Module M("SCEVExpanderNSW", Context);
1258
1259 Type *T_int64 = Type::getInt64Ty(Context);
1260
1261 FunctionType *FTy =
1262 FunctionType::get(Type::getVoidTy(Context), { T_int64 }, false);
James Y Knight13680222019-02-01 02:28:03 +00001263 Function *F = Function::Create(FTy, Function::ExternalLinkage, "func", M);
Serguei Katkovda56a7f2017-12-27 08:26:22 +00001264 Argument *Arg = &*F->arg_begin();
1265 ConstantInt *C = ConstantInt::get(Context, APInt(64, -1));
1266
1267 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1268 BasicBlock *Body = BasicBlock::Create(Context, "body", F);
1269 BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1270
1271 IRBuilder<> Builder(Entry);
1272 ConstantInt *Cond = ConstantInt::get(Context, APInt(1, 0));
1273 Builder.CreateCondBr(Cond, Exit, Body);
1274
1275 Builder.SetInsertPoint(Body);
1276 auto *S1 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1277 Builder.CreateBr(Exit);
1278
1279 Builder.SetInsertPoint(Exit);
1280 auto *S2 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1281 S2->setHasNoSignedWrap(true);
1282 auto *R = cast<Instruction>(Builder.CreateRetVoid());
1283
1284 ScalarEvolution SE = buildSE(*F);
1285 const SCEV *S = SE.getSCEV(S1);
1286 EXPECT_TRUE(isa<SCEVAddExpr>(S));
1287 SCEVExpander Exp(SE, M.getDataLayout(), "expander");
1288 auto *I = cast<Instruction>(Exp.expandCodeFor(S, nullptr, R));
1289 EXPECT_FALSE(I->hasNoSignedWrap());
1290}
1291
Serguei Katkov6a7a4c62018-01-09 06:47:14 +00001292// Check that SCEV does not save the SCEV -> V
1293// mapping of SCEV differ from V in NUW flag.
1294TEST_F(ScalarEvolutionsTest, SCEVCacheNUW) {
1295 /*
1296 * Create the following code:
1297 * func(i64 %a)
1298 * entry:
1299 * %s1 = add i64 %a, -1
1300 * %s2 = add nuw i64 %a, -1
1301 * br label %exit
1302 * exit:
1303 * ret %s
1304 */
1305
1306 // Create a module.
1307 Module M("SCEVCacheNUW", Context);
1308
1309 Type *T_int64 = Type::getInt64Ty(Context);
1310
1311 FunctionType *FTy =
1312 FunctionType::get(Type::getVoidTy(Context), { T_int64 }, false);
James Y Knight13680222019-02-01 02:28:03 +00001313 Function *F = Function::Create(FTy, Function::ExternalLinkage, "func", M);
Serguei Katkov6a7a4c62018-01-09 06:47:14 +00001314 Argument *Arg = &*F->arg_begin();
1315 ConstantInt *C = ConstantInt::get(Context, APInt(64, -1));
1316
1317 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1318 BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1319
1320 IRBuilder<> Builder(Entry);
1321 auto *S1 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1322 auto *S2 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1323 S2->setHasNoUnsignedWrap(true);
1324 Builder.CreateBr(Exit);
1325
1326 Builder.SetInsertPoint(Exit);
1327 auto *R = cast<Instruction>(Builder.CreateRetVoid());
1328
1329 ScalarEvolution SE = buildSE(*F);
1330 // Get S2 first to move it to cache.
1331 const SCEV *SC2 = SE.getSCEV(S2);
1332 EXPECT_TRUE(isa<SCEVAddExpr>(SC2));
1333 // Now get S1.
1334 const SCEV *SC1 = SE.getSCEV(S1);
1335 EXPECT_TRUE(isa<SCEVAddExpr>(SC1));
1336 // Expand for S1, it should use S1 not S2 in spite S2
1337 // first in the cache.
1338 SCEVExpander Exp(SE, M.getDataLayout(), "expander");
1339 auto *I = cast<Instruction>(Exp.expandCodeFor(SC1, nullptr, R));
1340 EXPECT_FALSE(I->hasNoUnsignedWrap());
1341}
1342
1343// Check that SCEV does not save the SCEV -> V
1344// mapping of SCEV differ from V in NSW flag.
1345TEST_F(ScalarEvolutionsTest, SCEVCacheNSW) {
1346 /*
1347 * Create the following code:
1348 * func(i64 %a)
1349 * entry:
1350 * %s1 = add i64 %a, -1
1351 * %s2 = add nsw i64 %a, -1
1352 * br label %exit
1353 * exit:
1354 * ret %s
1355 */
1356
1357 // Create a module.
1358 Module M("SCEVCacheNUW", Context);
1359
1360 Type *T_int64 = Type::getInt64Ty(Context);
1361
1362 FunctionType *FTy =
1363 FunctionType::get(Type::getVoidTy(Context), { T_int64 }, false);
James Y Knight13680222019-02-01 02:28:03 +00001364 Function *F = Function::Create(FTy, Function::ExternalLinkage, "func", M);
Serguei Katkov6a7a4c62018-01-09 06:47:14 +00001365 Argument *Arg = &*F->arg_begin();
1366 ConstantInt *C = ConstantInt::get(Context, APInt(64, -1));
1367
1368 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1369 BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1370
1371 IRBuilder<> Builder(Entry);
1372 auto *S1 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1373 auto *S2 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1374 S2->setHasNoSignedWrap(true);
1375 Builder.CreateBr(Exit);
1376
1377 Builder.SetInsertPoint(Exit);
1378 auto *R = cast<Instruction>(Builder.CreateRetVoid());
1379
1380 ScalarEvolution SE = buildSE(*F);
1381 // Get S2 first to move it to cache.
1382 const SCEV *SC2 = SE.getSCEV(S2);
1383 EXPECT_TRUE(isa<SCEVAddExpr>(SC2));
1384 // Now get S1.
1385 const SCEV *SC1 = SE.getSCEV(S1);
1386 EXPECT_TRUE(isa<SCEVAddExpr>(SC1));
1387 // Expand for S1, it should use S1 not S2 in spite S2
1388 // first in the cache.
1389 SCEVExpander Exp(SE, M.getDataLayout(), "expander");
1390 auto *I = cast<Instruction>(Exp.expandCodeFor(SC1, nullptr, R));
1391 EXPECT_FALSE(I->hasNoSignedWrap());
1392}
1393
Max Kazantsev85c98832019-01-21 06:19:50 +00001394// Check logic of SCEV expression size computation.
1395TEST_F(ScalarEvolutionsTest, SCEVComputeExpressionSize) {
1396 /*
1397 * Create the following code:
1398 * void func(i64 %a, i64 %b)
1399 * entry:
1400 * %s1 = add i64 %a, 1
1401 * %s2 = udiv i64 %s1, %b
1402 * br label %exit
1403 * exit:
1404 * ret
1405 */
1406
1407 // Create a module.
1408 Module M("SCEVComputeExpressionSize", Context);
1409
1410 Type *T_int64 = Type::getInt64Ty(Context);
1411
1412 FunctionType *FTy =
1413 FunctionType::get(Type::getVoidTy(Context), { T_int64, T_int64 }, false);
James Y Knight13680222019-02-01 02:28:03 +00001414 Function *F = Function::Create(FTy, Function::ExternalLinkage, "func", M);
Max Kazantsev85c98832019-01-21 06:19:50 +00001415 Argument *A = &*F->arg_begin();
1416 Argument *B = &*std::next(F->arg_begin());
1417 ConstantInt *C = ConstantInt::get(Context, APInt(64, 1));
1418
1419 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1420 BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1421
1422 IRBuilder<> Builder(Entry);
1423 auto *S1 = cast<Instruction>(Builder.CreateAdd(A, C, "s1"));
1424 auto *S2 = cast<Instruction>(Builder.CreateUDiv(S1, B, "s2"));
1425 Builder.CreateBr(Exit);
1426
1427 Builder.SetInsertPoint(Exit);
Max Kazantsev9d45edf2019-01-21 07:27:47 +00001428 Builder.CreateRetVoid();
Max Kazantsev85c98832019-01-21 06:19:50 +00001429
1430 ScalarEvolution SE = buildSE(*F);
1431 // Get S2 first to move it to cache.
1432 const SCEV *AS = SE.getSCEV(A);
1433 const SCEV *BS = SE.getSCEV(B);
1434 const SCEV *CS = SE.getSCEV(C);
1435 const SCEV *S1S = SE.getSCEV(S1);
1436 const SCEV *S2S = SE.getSCEV(S2);
Max Kazantsev9d45edf2019-01-21 07:27:47 +00001437 EXPECT_EQ(AS->getExpressionSize(), 1u);
1438 EXPECT_EQ(BS->getExpressionSize(), 1u);
1439 EXPECT_EQ(CS->getExpressionSize(), 1u);
1440 EXPECT_EQ(S1S->getExpressionSize(), 3u);
1441 EXPECT_EQ(S2S->getExpressionSize(), 5u);
Max Kazantsev85c98832019-01-21 06:19:50 +00001442}
1443
Dan Gohman7cac9572010-08-02 23:49:30 +00001444} // end anonymous namespace
1445} // end namespace llvm