1 //===- llvm/unittest/IR/InstructionsTest.cpp - Instructions unit tests ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/IR/Instructions.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/Analysis/ValueTracking.h"
13 #include "llvm/IR/BasicBlock.h"
14 #include "llvm/IR/Constants.h"
15 #include "llvm/IR/DataLayout.h"
16 #include "llvm/IR/DerivedTypes.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/MDBuilder.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/NoFolder.h"
23 #include "llvm/IR/Operator.h"
24 #include "gmock/gmock-matchers.h"
25 #include "gtest/gtest.h"
26 #include <memory>
27 
28 namespace llvm {
29 namespace {
30 
31 TEST(InstructionsTest, ReturnInst) {
32   LLVMContext C;
33 
34   // test for PR6589
35   const ReturnInst* r0 = ReturnInst::Create(C);
36   EXPECT_EQ(r0->getNumOperands(), 0U);
37   EXPECT_EQ(r0->op_begin(), r0->op_end());
38 
39   IntegerType* Int1 = IntegerType::get(C, 1);
40   Constant* One = ConstantInt::get(Int1, 1, true);
41   const ReturnInst* r1 = ReturnInst::Create(C, One);
42   EXPECT_EQ(1U, r1->getNumOperands());
43   User::const_op_iterator b(r1->op_begin());
44   EXPECT_NE(r1->op_end(), b);
45   EXPECT_EQ(One, *b);
46   EXPECT_EQ(One, r1->getOperand(0));
47   ++b;
48   EXPECT_EQ(r1->op_end(), b);
49 
50   // clean up
51   delete r0;
52   delete r1;
53 }
54 
55 // Test fixture that provides a module and a single function within it. Useful
56 // for tests that need to refer to the function in some way.
57 class ModuleWithFunctionTest : public testing::Test {
58 protected:
59   ModuleWithFunctionTest() : M(new Module("MyModule", Ctx)) {
60     FArgTypes.push_back(Type::getInt8Ty(Ctx));
61     FArgTypes.push_back(Type::getInt32Ty(Ctx));
62     FArgTypes.push_back(Type::getInt64Ty(Ctx));
63     FunctionType *FTy =
64         FunctionType::get(Type::getVoidTy(Ctx), FArgTypes, false);
65     F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
66   }
67 
68   LLVMContext Ctx;
69   std::unique_ptr<Module> M;
70   SmallVector<Type *, 3> FArgTypes;
71   Function *F;
72 };
73 
74 TEST_F(ModuleWithFunctionTest, CallInst) {
75   Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20),
76                    ConstantInt::get(Type::getInt32Ty(Ctx), 9999),
77                    ConstantInt::get(Type::getInt64Ty(Ctx), 42)};
78   std::unique_ptr<CallInst> Call(CallInst::Create(F, Args));
79 
80   // Make sure iteration over a call's arguments works as expected.
81   unsigned Idx = 0;
82   for (Value *Arg : Call->arg_operands()) {
83     EXPECT_EQ(FArgTypes[Idx], Arg->getType());
84     EXPECT_EQ(Call->getArgOperand(Idx)->getType(), Arg->getType());
85     Idx++;
86   }
87 }
88 
89 TEST_F(ModuleWithFunctionTest, InvokeInst) {
90   BasicBlock *BB1 = BasicBlock::Create(Ctx, "", F);
91   BasicBlock *BB2 = BasicBlock::Create(Ctx, "", F);
92 
93   Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20),
94                    ConstantInt::get(Type::getInt32Ty(Ctx), 9999),
95                    ConstantInt::get(Type::getInt64Ty(Ctx), 42)};
96   std::unique_ptr<InvokeInst> Invoke(InvokeInst::Create(F, BB1, BB2, Args));
97 
98   // Make sure iteration over invoke's arguments works as expected.
99   unsigned Idx = 0;
100   for (Value *Arg : Invoke->arg_operands()) {
101     EXPECT_EQ(FArgTypes[Idx], Arg->getType());
102     EXPECT_EQ(Invoke->getArgOperand(Idx)->getType(), Arg->getType());
103     Idx++;
104   }
105 }
106 
107 TEST(InstructionsTest, BranchInst) {
108   LLVMContext C;
109 
110   // Make a BasicBlocks
111   BasicBlock* bb0 = BasicBlock::Create(C);
112   BasicBlock* bb1 = BasicBlock::Create(C);
113 
114   // Mandatory BranchInst
115   const BranchInst* b0 = BranchInst::Create(bb0);
116 
117   EXPECT_TRUE(b0->isUnconditional());
118   EXPECT_FALSE(b0->isConditional());
119   EXPECT_EQ(1U, b0->getNumSuccessors());
120 
121   // check num operands
122   EXPECT_EQ(1U, b0->getNumOperands());
123 
124   EXPECT_NE(b0->op_begin(), b0->op_end());
125   EXPECT_EQ(b0->op_end(), std::next(b0->op_begin()));
126 
127   EXPECT_EQ(b0->op_end(), std::next(b0->op_begin()));
128 
129   IntegerType* Int1 = IntegerType::get(C, 1);
130   Constant* One = ConstantInt::get(Int1, 1, true);
131 
132   // Conditional BranchInst
133   BranchInst* b1 = BranchInst::Create(bb0, bb1, One);
134 
135   EXPECT_FALSE(b1->isUnconditional());
136   EXPECT_TRUE(b1->isConditional());
137   EXPECT_EQ(2U, b1->getNumSuccessors());
138 
139   // check num operands
140   EXPECT_EQ(3U, b1->getNumOperands());
141 
142   User::const_op_iterator b(b1->op_begin());
143 
144   // check COND
145   EXPECT_NE(b, b1->op_end());
146   EXPECT_EQ(One, *b);
147   EXPECT_EQ(One, b1->getOperand(0));
148   EXPECT_EQ(One, b1->getCondition());
149   ++b;
150 
151   // check ELSE
152   EXPECT_EQ(bb1, *b);
153   EXPECT_EQ(bb1, b1->getOperand(1));
154   EXPECT_EQ(bb1, b1->getSuccessor(1));
155   ++b;
156 
157   // check THEN
158   EXPECT_EQ(bb0, *b);
159   EXPECT_EQ(bb0, b1->getOperand(2));
160   EXPECT_EQ(bb0, b1->getSuccessor(0));
161   ++b;
162 
163   EXPECT_EQ(b1->op_end(), b);
164 
165   // clean up
166   delete b0;
167   delete b1;
168 
169   delete bb0;
170   delete bb1;
171 }
172 
173 TEST(InstructionsTest, CastInst) {
174   LLVMContext C;
175 
176   Type *Int8Ty = Type::getInt8Ty(C);
177   Type *Int16Ty = Type::getInt16Ty(C);
178   Type *Int32Ty = Type::getInt32Ty(C);
179   Type *Int64Ty = Type::getInt64Ty(C);
180   Type *V8x8Ty = VectorType::get(Int8Ty, 8);
181   Type *V8x64Ty = VectorType::get(Int64Ty, 8);
182   Type *X86MMXTy = Type::getX86_MMXTy(C);
183 
184   Type *HalfTy = Type::getHalfTy(C);
185   Type *FloatTy = Type::getFloatTy(C);
186   Type *DoubleTy = Type::getDoubleTy(C);
187 
188   Type *V2Int32Ty = VectorType::get(Int32Ty, 2);
189   Type *V2Int64Ty = VectorType::get(Int64Ty, 2);
190   Type *V4Int16Ty = VectorType::get(Int16Ty, 4);
191 
192   Type *Int32PtrTy = PointerType::get(Int32Ty, 0);
193   Type *Int64PtrTy = PointerType::get(Int64Ty, 0);
194 
195   Type *Int32PtrAS1Ty = PointerType::get(Int32Ty, 1);
196   Type *Int64PtrAS1Ty = PointerType::get(Int64Ty, 1);
197 
198   Type *V2Int32PtrAS1Ty = VectorType::get(Int32PtrAS1Ty, 2);
199   Type *V2Int64PtrAS1Ty = VectorType::get(Int64PtrAS1Ty, 2);
200   Type *V4Int32PtrAS1Ty = VectorType::get(Int32PtrAS1Ty, 4);
201   Type *V4Int64PtrAS1Ty = VectorType::get(Int64PtrAS1Ty, 4);
202 
203   Type *V2Int64PtrTy = VectorType::get(Int64PtrTy, 2);
204   Type *V2Int32PtrTy = VectorType::get(Int32PtrTy, 2);
205   Type *V4Int32PtrTy = VectorType::get(Int32PtrTy, 4);
206 
207   const Constant* c8 = Constant::getNullValue(V8x8Ty);
208   const Constant* c64 = Constant::getNullValue(V8x64Ty);
209 
210   const Constant *v2ptr32 = Constant::getNullValue(V2Int32PtrTy);
211 
212   EXPECT_TRUE(CastInst::isCastable(V8x8Ty, X86MMXTy));
213   EXPECT_TRUE(CastInst::isCastable(X86MMXTy, V8x8Ty));
214   EXPECT_FALSE(CastInst::isCastable(Int64Ty, X86MMXTy));
215   EXPECT_TRUE(CastInst::isCastable(V8x64Ty, V8x8Ty));
216   EXPECT_TRUE(CastInst::isCastable(V8x8Ty, V8x64Ty));
217   EXPECT_EQ(CastInst::Trunc, CastInst::getCastOpcode(c64, true, V8x8Ty, true));
218   EXPECT_EQ(CastInst::SExt, CastInst::getCastOpcode(c8, true, V8x64Ty, true));
219 
220   EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, X86MMXTy));
221   EXPECT_FALSE(CastInst::isBitCastable(X86MMXTy, V8x8Ty));
222   EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, X86MMXTy));
223   EXPECT_FALSE(CastInst::isBitCastable(V8x64Ty, V8x8Ty));
224   EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, V8x64Ty));
225 
226   // Check address space casts are rejected since we don't know the sizes here
227   EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, Int32PtrAS1Ty));
228   EXPECT_FALSE(CastInst::isBitCastable(Int32PtrAS1Ty, Int32PtrTy));
229   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, V2Int32PtrAS1Ty));
230   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int32PtrTy));
231   EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int64PtrAS1Ty));
232   EXPECT_TRUE(CastInst::isCastable(V2Int32PtrAS1Ty, V2Int32PtrTy));
233   EXPECT_EQ(CastInst::AddrSpaceCast, CastInst::getCastOpcode(v2ptr32, true,
234                                                              V2Int32PtrAS1Ty,
235                                                              true));
236 
237   // Test mismatched number of elements for pointers
238   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int64PtrAS1Ty));
239   EXPECT_FALSE(CastInst::isBitCastable(V4Int64PtrAS1Ty, V2Int32PtrAS1Ty));
240   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int32PtrAS1Ty));
241   EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, V2Int32PtrTy));
242   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, Int32PtrTy));
243 
244   EXPECT_TRUE(CastInst::isBitCastable(Int32PtrTy, Int64PtrTy));
245   EXPECT_FALSE(CastInst::isBitCastable(DoubleTy, FloatTy));
246   EXPECT_FALSE(CastInst::isBitCastable(FloatTy, DoubleTy));
247   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy));
248   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy));
249   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, Int32Ty));
250   EXPECT_TRUE(CastInst::isBitCastable(Int16Ty, HalfTy));
251   EXPECT_TRUE(CastInst::isBitCastable(Int32Ty, FloatTy));
252   EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, Int64Ty));
253 
254   EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, V4Int16Ty));
255   EXPECT_FALSE(CastInst::isBitCastable(Int32Ty, Int64Ty));
256   EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, Int32Ty));
257 
258   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, Int64Ty));
259   EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, V2Int32PtrTy));
260   EXPECT_TRUE(CastInst::isBitCastable(V2Int64PtrTy, V2Int32PtrTy));
261   EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrTy, V2Int64PtrTy));
262   EXPECT_FALSE(CastInst::isBitCastable(V2Int32Ty, V2Int64Ty));
263   EXPECT_FALSE(CastInst::isBitCastable(V2Int64Ty, V2Int32Ty));
264 
265 
266   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
267                                      Constant::getNullValue(V4Int32PtrTy),
268                                      V2Int32PtrTy));
269   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
270                                      Constant::getNullValue(V2Int32PtrTy),
271                                      V4Int32PtrTy));
272 
273   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
274                                      Constant::getNullValue(V4Int32PtrAS1Ty),
275                                      V2Int32PtrTy));
276   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
277                                      Constant::getNullValue(V2Int32PtrTy),
278                                      V4Int32PtrAS1Ty));
279 
280 
281   // Check that assertion is not hit when creating a cast with a vector of
282   // pointers
283   // First form
284   BasicBlock *BB = BasicBlock::Create(C);
285   Constant *NullV2I32Ptr = Constant::getNullValue(V2Int32PtrTy);
286   auto Inst1 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty, "foo", BB);
287 
288   // Second form
289   auto Inst2 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty);
290 
291   delete Inst2;
292   Inst1->eraseFromParent();
293   delete BB;
294 }
295 
296 TEST(InstructionsTest, VectorGep) {
297   LLVMContext C;
298 
299   // Type Definitions
300   Type *I8Ty = IntegerType::get(C, 8);
301   Type *I32Ty = IntegerType::get(C, 32);
302   PointerType *Ptri8Ty = PointerType::get(I8Ty, 0);
303   PointerType *Ptri32Ty = PointerType::get(I32Ty, 0);
304 
305   VectorType *V2xi8PTy = VectorType::get(Ptri8Ty, 2);
306   VectorType *V2xi32PTy = VectorType::get(Ptri32Ty, 2);
307 
308   // Test different aspects of the vector-of-pointers type
309   // and GEPs which use this type.
310   ConstantInt *Ci32a = ConstantInt::get(C, APInt(32, 1492));
311   ConstantInt *Ci32b = ConstantInt::get(C, APInt(32, 1948));
312   std::vector<Constant*> ConstVa(2, Ci32a);
313   std::vector<Constant*> ConstVb(2, Ci32b);
314   Constant *C2xi32a = ConstantVector::get(ConstVa);
315   Constant *C2xi32b = ConstantVector::get(ConstVb);
316 
317   CastInst *PtrVecA = new IntToPtrInst(C2xi32a, V2xi32PTy);
318   CastInst *PtrVecB = new IntToPtrInst(C2xi32b, V2xi32PTy);
319 
320   ICmpInst *ICmp0 = new ICmpInst(ICmpInst::ICMP_SGT, PtrVecA, PtrVecB);
321   ICmpInst *ICmp1 = new ICmpInst(ICmpInst::ICMP_ULT, PtrVecA, PtrVecB);
322   EXPECT_NE(ICmp0, ICmp1); // suppress warning.
323 
324   BasicBlock* BB0 = BasicBlock::Create(C);
325   // Test InsertAtEnd ICmpInst constructor.
326   ICmpInst *ICmp2 = new ICmpInst(*BB0, ICmpInst::ICMP_SGE, PtrVecA, PtrVecB);
327   EXPECT_NE(ICmp0, ICmp2); // suppress warning.
328 
329   GetElementPtrInst *Gep0 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32a);
330   GetElementPtrInst *Gep1 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32b);
331   GetElementPtrInst *Gep2 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32a);
332   GetElementPtrInst *Gep3 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32b);
333 
334   CastInst *BTC0 = new BitCastInst(Gep0, V2xi8PTy);
335   CastInst *BTC1 = new BitCastInst(Gep1, V2xi8PTy);
336   CastInst *BTC2 = new BitCastInst(Gep2, V2xi8PTy);
337   CastInst *BTC3 = new BitCastInst(Gep3, V2xi8PTy);
338 
339   Value *S0 = BTC0->stripPointerCasts();
340   Value *S1 = BTC1->stripPointerCasts();
341   Value *S2 = BTC2->stripPointerCasts();
342   Value *S3 = BTC3->stripPointerCasts();
343 
344   EXPECT_NE(S0, Gep0);
345   EXPECT_NE(S1, Gep1);
346   EXPECT_NE(S2, Gep2);
347   EXPECT_NE(S3, Gep3);
348 
349   int64_t Offset;
350   DataLayout TD("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f3"
351                 "2:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-s:64:64-f80"
352                 ":128:128-n8:16:32:64-S128");
353   // Make sure we don't crash
354   GetPointerBaseWithConstantOffset(Gep0, Offset, TD);
355   GetPointerBaseWithConstantOffset(Gep1, Offset, TD);
356   GetPointerBaseWithConstantOffset(Gep2, Offset, TD);
357   GetPointerBaseWithConstantOffset(Gep3, Offset, TD);
358 
359   // Gep of Geps
360   GetElementPtrInst *GepII0 = GetElementPtrInst::Create(I32Ty, Gep0, C2xi32b);
361   GetElementPtrInst *GepII1 = GetElementPtrInst::Create(I32Ty, Gep1, C2xi32a);
362   GetElementPtrInst *GepII2 = GetElementPtrInst::Create(I32Ty, Gep2, C2xi32b);
363   GetElementPtrInst *GepII3 = GetElementPtrInst::Create(I32Ty, Gep3, C2xi32a);
364 
365   EXPECT_EQ(GepII0->getNumIndices(), 1u);
366   EXPECT_EQ(GepII1->getNumIndices(), 1u);
367   EXPECT_EQ(GepII2->getNumIndices(), 1u);
368   EXPECT_EQ(GepII3->getNumIndices(), 1u);
369 
370   EXPECT_FALSE(GepII0->hasAllZeroIndices());
371   EXPECT_FALSE(GepII1->hasAllZeroIndices());
372   EXPECT_FALSE(GepII2->hasAllZeroIndices());
373   EXPECT_FALSE(GepII3->hasAllZeroIndices());
374 
375   delete GepII0;
376   delete GepII1;
377   delete GepII2;
378   delete GepII3;
379 
380   delete BTC0;
381   delete BTC1;
382   delete BTC2;
383   delete BTC3;
384 
385   delete Gep0;
386   delete Gep1;
387   delete Gep2;
388   delete Gep3;
389 
390   ICmp2->eraseFromParent();
391   delete BB0;
392 
393   delete ICmp0;
394   delete ICmp1;
395   delete PtrVecA;
396   delete PtrVecB;
397 }
398 
399 TEST(InstructionsTest, FPMathOperator) {
400   LLVMContext Context;
401   IRBuilder<> Builder(Context);
402   MDBuilder MDHelper(Context);
403   Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
404   MDNode *MD1 = MDHelper.createFPMath(1.0);
405   Value *V1 = Builder.CreateFAdd(I, I, "", MD1);
406   EXPECT_TRUE(isa<FPMathOperator>(V1));
407   FPMathOperator *O1 = cast<FPMathOperator>(V1);
408   EXPECT_EQ(O1->getFPAccuracy(), 1.0);
409   V1->deleteValue();
410   I->deleteValue();
411 }
412 
413 
414 TEST(InstructionsTest, isEliminableCastPair) {
415   LLVMContext C;
416 
417   Type* Int16Ty = Type::getInt16Ty(C);
418   Type* Int32Ty = Type::getInt32Ty(C);
419   Type* Int64Ty = Type::getInt64Ty(C);
420   Type* Int64PtrTy = Type::getInt64PtrTy(C);
421 
422   // Source and destination pointers have same size -> bitcast.
423   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
424                                            CastInst::IntToPtr,
425                                            Int64PtrTy, Int64Ty, Int64PtrTy,
426                                            Int32Ty, nullptr, Int32Ty),
427             CastInst::BitCast);
428 
429   // Source and destination have unknown sizes, but the same address space and
430   // the intermediate int is the maximum pointer size -> bitcast
431   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
432                                            CastInst::IntToPtr,
433                                            Int64PtrTy, Int64Ty, Int64PtrTy,
434                                            nullptr, nullptr, nullptr),
435             CastInst::BitCast);
436 
437   // Source and destination have unknown sizes, but the same address space and
438   // the intermediate int is not the maximum pointer size -> nothing
439   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
440                                            CastInst::IntToPtr,
441                                            Int64PtrTy, Int32Ty, Int64PtrTy,
442                                            nullptr, nullptr, nullptr),
443             0U);
444 
445   // Middle pointer big enough -> bitcast.
446   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
447                                            CastInst::PtrToInt,
448                                            Int64Ty, Int64PtrTy, Int64Ty,
449                                            nullptr, Int64Ty, nullptr),
450             CastInst::BitCast);
451 
452   // Middle pointer too small -> fail.
453   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
454                                            CastInst::PtrToInt,
455                                            Int64Ty, Int64PtrTy, Int64Ty,
456                                            nullptr, Int32Ty, nullptr),
457             0U);
458 
459   // Test that we don't eliminate bitcasts between different address spaces,
460   // or if we don't have available pointer size information.
461   DataLayout DL("e-p:32:32:32-p1:16:16:16-p2:64:64:64-i1:8:8-i8:8:8-i16:16:16"
462                 "-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64"
463                 "-v128:128:128-a:0:64-s:64:64-f80:128:128-n8:16:32:64-S128");
464 
465   Type* Int64PtrTyAS1 = Type::getInt64PtrTy(C, 1);
466   Type* Int64PtrTyAS2 = Type::getInt64PtrTy(C, 2);
467 
468   IntegerType *Int16SizePtr = DL.getIntPtrType(C, 1);
469   IntegerType *Int64SizePtr = DL.getIntPtrType(C, 2);
470 
471   // Cannot simplify inttoptr, addrspacecast
472   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
473                                            CastInst::AddrSpaceCast,
474                                            Int16Ty, Int64PtrTyAS1, Int64PtrTyAS2,
475                                            nullptr, Int16SizePtr, Int64SizePtr),
476             0U);
477 
478   // Cannot simplify addrspacecast, ptrtoint
479   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::AddrSpaceCast,
480                                            CastInst::PtrToInt,
481                                            Int64PtrTyAS1, Int64PtrTyAS2, Int16Ty,
482                                            Int64SizePtr, Int16SizePtr, nullptr),
483             0U);
484 
485   // Pass since the bitcast address spaces are the same
486   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
487                                            CastInst::BitCast,
488                                            Int16Ty, Int64PtrTyAS1, Int64PtrTyAS1,
489                                            nullptr, nullptr, nullptr),
490             CastInst::IntToPtr);
491 
492 }
493 
494 TEST(InstructionsTest, CloneCall) {
495   LLVMContext C;
496   Type *Int32Ty = Type::getInt32Ty(C);
497   Type *ArgTys[] = {Int32Ty, Int32Ty, Int32Ty};
498   Type *FnTy = FunctionType::get(Int32Ty, ArgTys, /*isVarArg=*/false);
499   Value *Callee = Constant::getNullValue(FnTy->getPointerTo());
500   Value *Args[] = {
501     ConstantInt::get(Int32Ty, 1),
502     ConstantInt::get(Int32Ty, 2),
503     ConstantInt::get(Int32Ty, 3)
504   };
505   std::unique_ptr<CallInst> Call(CallInst::Create(Callee, Args, "result"));
506 
507   // Test cloning the tail call kind.
508   CallInst::TailCallKind Kinds[] = {CallInst::TCK_None, CallInst::TCK_Tail,
509                                     CallInst::TCK_MustTail};
510   for (CallInst::TailCallKind TCK : Kinds) {
511     Call->setTailCallKind(TCK);
512     std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone()));
513     EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind());
514   }
515   Call->setTailCallKind(CallInst::TCK_None);
516 
517   // Test cloning an attribute.
518   {
519     AttrBuilder AB;
520     AB.addAttribute(Attribute::ReadOnly);
521     Call->setAttributes(
522         AttributeList::get(C, AttributeList::FunctionIndex, AB));
523     std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone()));
524     EXPECT_TRUE(Clone->onlyReadsMemory());
525   }
526 }
527 
528 TEST(InstructionsTest, AlterCallBundles) {
529   LLVMContext C;
530   Type *Int32Ty = Type::getInt32Ty(C);
531   Type *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
532   Value *Callee = Constant::getNullValue(FnTy->getPointerTo());
533   Value *Args[] = {ConstantInt::get(Int32Ty, 42)};
534   OperandBundleDef OldBundle("before", UndefValue::get(Int32Ty));
535   std::unique_ptr<CallInst> Call(
536       CallInst::Create(Callee, Args, OldBundle, "result"));
537   Call->setTailCallKind(CallInst::TailCallKind::TCK_NoTail);
538   AttrBuilder AB;
539   AB.addAttribute(Attribute::Cold);
540   Call->setAttributes(AttributeList::get(C, AttributeList::FunctionIndex, AB));
541   Call->setDebugLoc(DebugLoc(MDNode::get(C, None)));
542 
543   OperandBundleDef NewBundle("after", ConstantInt::get(Int32Ty, 7));
544   std::unique_ptr<CallInst> Clone(CallInst::Create(Call.get(), NewBundle));
545   EXPECT_EQ(Call->getNumArgOperands(), Clone->getNumArgOperands());
546   EXPECT_EQ(Call->getArgOperand(0), Clone->getArgOperand(0));
547   EXPECT_EQ(Call->getCallingConv(), Clone->getCallingConv());
548   EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind());
549   EXPECT_TRUE(Clone->hasFnAttr(Attribute::AttrKind::Cold));
550   EXPECT_EQ(Call->getDebugLoc(), Clone->getDebugLoc());
551   EXPECT_EQ(Clone->getNumOperandBundles(), 1U);
552   EXPECT_TRUE(Clone->getOperandBundle("after").hasValue());
553 }
554 
555 TEST(InstructionsTest, AlterInvokeBundles) {
556   LLVMContext C;
557   Type *Int32Ty = Type::getInt32Ty(C);
558   Type *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
559   Value *Callee = Constant::getNullValue(FnTy->getPointerTo());
560   Value *Args[] = {ConstantInt::get(Int32Ty, 42)};
561   std::unique_ptr<BasicBlock> NormalDest(BasicBlock::Create(C));
562   std::unique_ptr<BasicBlock> UnwindDest(BasicBlock::Create(C));
563   OperandBundleDef OldBundle("before", UndefValue::get(Int32Ty));
564   std::unique_ptr<InvokeInst> Invoke(InvokeInst::Create(
565       Callee, NormalDest.get(), UnwindDest.get(), Args, OldBundle, "result"));
566   AttrBuilder AB;
567   AB.addAttribute(Attribute::Cold);
568   Invoke->setAttributes(
569       AttributeList::get(C, AttributeList::FunctionIndex, AB));
570   Invoke->setDebugLoc(DebugLoc(MDNode::get(C, None)));
571 
572   OperandBundleDef NewBundle("after", ConstantInt::get(Int32Ty, 7));
573   std::unique_ptr<InvokeInst> Clone(
574       InvokeInst::Create(Invoke.get(), NewBundle));
575   EXPECT_EQ(Invoke->getNormalDest(), Clone->getNormalDest());
576   EXPECT_EQ(Invoke->getUnwindDest(), Clone->getUnwindDest());
577   EXPECT_EQ(Invoke->getNumArgOperands(), Clone->getNumArgOperands());
578   EXPECT_EQ(Invoke->getArgOperand(0), Clone->getArgOperand(0));
579   EXPECT_EQ(Invoke->getCallingConv(), Clone->getCallingConv());
580   EXPECT_TRUE(Clone->hasFnAttr(Attribute::AttrKind::Cold));
581   EXPECT_EQ(Invoke->getDebugLoc(), Clone->getDebugLoc());
582   EXPECT_EQ(Clone->getNumOperandBundles(), 1U);
583   EXPECT_TRUE(Clone->getOperandBundle("after").hasValue());
584 }
585 
586 TEST_F(ModuleWithFunctionTest, DropPoisonGeneratingFlags) {
587   auto *OnlyBB = BasicBlock::Create(Ctx, "bb", F);
588   auto *Arg0 = &*F->arg_begin();
589 
590   IRBuilder<NoFolder> B(Ctx);
591   B.SetInsertPoint(OnlyBB);
592 
593   {
594     auto *UI =
595         cast<Instruction>(B.CreateUDiv(Arg0, Arg0, "", /*isExact*/ true));
596     ASSERT_TRUE(UI->isExact());
597     UI->dropPoisonGeneratingFlags();
598     ASSERT_FALSE(UI->isExact());
599   }
600 
601   {
602     auto *ShrI =
603         cast<Instruction>(B.CreateLShr(Arg0, Arg0, "", /*isExact*/ true));
604     ASSERT_TRUE(ShrI->isExact());
605     ShrI->dropPoisonGeneratingFlags();
606     ASSERT_FALSE(ShrI->isExact());
607   }
608 
609   {
610     auto *AI = cast<Instruction>(
611         B.CreateAdd(Arg0, Arg0, "", /*HasNUW*/ true, /*HasNSW*/ false));
612     ASSERT_TRUE(AI->hasNoUnsignedWrap());
613     AI->dropPoisonGeneratingFlags();
614     ASSERT_FALSE(AI->hasNoUnsignedWrap());
615     ASSERT_FALSE(AI->hasNoSignedWrap());
616   }
617 
618   {
619     auto *SI = cast<Instruction>(
620         B.CreateAdd(Arg0, Arg0, "", /*HasNUW*/ false, /*HasNSW*/ true));
621     ASSERT_TRUE(SI->hasNoSignedWrap());
622     SI->dropPoisonGeneratingFlags();
623     ASSERT_FALSE(SI->hasNoUnsignedWrap());
624     ASSERT_FALSE(SI->hasNoSignedWrap());
625   }
626 
627   {
628     auto *ShlI = cast<Instruction>(
629         B.CreateShl(Arg0, Arg0, "", /*HasNUW*/ true, /*HasNSW*/ true));
630     ASSERT_TRUE(ShlI->hasNoSignedWrap());
631     ASSERT_TRUE(ShlI->hasNoUnsignedWrap());
632     ShlI->dropPoisonGeneratingFlags();
633     ASSERT_FALSE(ShlI->hasNoUnsignedWrap());
634     ASSERT_FALSE(ShlI->hasNoSignedWrap());
635   }
636 
637   {
638     Value *GEPBase = Constant::getNullValue(B.getInt8PtrTy());
639     auto *GI = cast<GetElementPtrInst>(B.CreateInBoundsGEP(GEPBase, {Arg0}));
640     ASSERT_TRUE(GI->isInBounds());
641     GI->dropPoisonGeneratingFlags();
642     ASSERT_FALSE(GI->isInBounds());
643   }
644 }
645 
646 TEST(InstructionsTest, GEPIndices) {
647   LLVMContext Context;
648   IRBuilder<NoFolder> Builder(Context);
649   Type *ElementTy = Builder.getInt8Ty();
650   Type *ArrTy = ArrayType::get(ArrayType::get(ElementTy, 64), 64);
651   Value *Indices[] = {
652     Builder.getInt32(0),
653     Builder.getInt32(13),
654     Builder.getInt32(42) };
655 
656   Value *V = Builder.CreateGEP(ArrTy, UndefValue::get(PointerType::getUnqual(ArrTy)),
657                                Indices);
658   ASSERT_TRUE(isa<GetElementPtrInst>(V));
659 
660   auto *GEPI = cast<GetElementPtrInst>(V);
661   ASSERT_NE(GEPI->idx_begin(), GEPI->idx_end());
662   ASSERT_EQ(GEPI->idx_end(), std::next(GEPI->idx_begin(), 3));
663   EXPECT_EQ(Indices[0], GEPI->idx_begin()[0]);
664   EXPECT_EQ(Indices[1], GEPI->idx_begin()[1]);
665   EXPECT_EQ(Indices[2], GEPI->idx_begin()[2]);
666   EXPECT_EQ(GEPI->idx_begin(), GEPI->indices().begin());
667   EXPECT_EQ(GEPI->idx_end(), GEPI->indices().end());
668 
669   const auto *CGEPI = GEPI;
670   ASSERT_NE(CGEPI->idx_begin(), CGEPI->idx_end());
671   ASSERT_EQ(CGEPI->idx_end(), std::next(CGEPI->idx_begin(), 3));
672   EXPECT_EQ(Indices[0], CGEPI->idx_begin()[0]);
673   EXPECT_EQ(Indices[1], CGEPI->idx_begin()[1]);
674   EXPECT_EQ(Indices[2], CGEPI->idx_begin()[2]);
675   EXPECT_EQ(CGEPI->idx_begin(), CGEPI->indices().begin());
676   EXPECT_EQ(CGEPI->idx_end(), CGEPI->indices().end());
677 
678   delete GEPI;
679 }
680 
681 TEST(InstructionsTest, SwitchInst) {
682   LLVMContext C;
683 
684   std::unique_ptr<BasicBlock> BB1, BB2, BB3;
685   BB1.reset(BasicBlock::Create(C));
686   BB2.reset(BasicBlock::Create(C));
687   BB3.reset(BasicBlock::Create(C));
688 
689   // We create block 0 after the others so that it gets destroyed first and
690   // clears the uses of the other basic blocks.
691   std::unique_ptr<BasicBlock> BB0(BasicBlock::Create(C));
692 
693   auto *Int32Ty = Type::getInt32Ty(C);
694 
695   SwitchInst *SI =
696       SwitchInst::Create(UndefValue::get(Int32Ty), BB0.get(), 3, BB0.get());
697   SI->addCase(ConstantInt::get(Int32Ty, 1), BB1.get());
698   SI->addCase(ConstantInt::get(Int32Ty, 2), BB2.get());
699   SI->addCase(ConstantInt::get(Int32Ty, 3), BB3.get());
700 
701   auto CI = SI->case_begin();
702   ASSERT_NE(CI, SI->case_end());
703   EXPECT_EQ(1, CI->getCaseValue()->getSExtValue());
704   EXPECT_EQ(BB1.get(), CI->getCaseSuccessor());
705   EXPECT_EQ(2, (CI + 1)->getCaseValue()->getSExtValue());
706   EXPECT_EQ(BB2.get(), (CI + 1)->getCaseSuccessor());
707   EXPECT_EQ(3, (CI + 2)->getCaseValue()->getSExtValue());
708   EXPECT_EQ(BB3.get(), (CI + 2)->getCaseSuccessor());
709   EXPECT_EQ(CI + 1, std::next(CI));
710   EXPECT_EQ(CI + 2, std::next(CI, 2));
711   EXPECT_EQ(CI + 3, std::next(CI, 3));
712   EXPECT_EQ(SI->case_end(), CI + 3);
713   EXPECT_EQ(0, CI - CI);
714   EXPECT_EQ(1, (CI + 1) - CI);
715   EXPECT_EQ(2, (CI + 2) - CI);
716   EXPECT_EQ(3, SI->case_end() - CI);
717   EXPECT_EQ(3, std::distance(CI, SI->case_end()));
718 
719   auto CCI = const_cast<const SwitchInst *>(SI)->case_begin();
720   SwitchInst::ConstCaseIt CCE = SI->case_end();
721   ASSERT_NE(CCI, SI->case_end());
722   EXPECT_EQ(1, CCI->getCaseValue()->getSExtValue());
723   EXPECT_EQ(BB1.get(), CCI->getCaseSuccessor());
724   EXPECT_EQ(2, (CCI + 1)->getCaseValue()->getSExtValue());
725   EXPECT_EQ(BB2.get(), (CCI + 1)->getCaseSuccessor());
726   EXPECT_EQ(3, (CCI + 2)->getCaseValue()->getSExtValue());
727   EXPECT_EQ(BB3.get(), (CCI + 2)->getCaseSuccessor());
728   EXPECT_EQ(CCI + 1, std::next(CCI));
729   EXPECT_EQ(CCI + 2, std::next(CCI, 2));
730   EXPECT_EQ(CCI + 3, std::next(CCI, 3));
731   EXPECT_EQ(CCE, CCI + 3);
732   EXPECT_EQ(0, CCI - CCI);
733   EXPECT_EQ(1, (CCI + 1) - CCI);
734   EXPECT_EQ(2, (CCI + 2) - CCI);
735   EXPECT_EQ(3, CCE - CCI);
736   EXPECT_EQ(3, std::distance(CCI, CCE));
737 
738   // Make sure that the const iterator is compatible with a const auto ref.
739   const auto &Handle = *CCI;
740   EXPECT_EQ(1, Handle.getCaseValue()->getSExtValue());
741   EXPECT_EQ(BB1.get(), Handle.getCaseSuccessor());
742 }
743 
744 TEST(InstructionsTest, CommuteShuffleMask) {
745   SmallVector<int, 16> Indices({-1, 0, 7});
746   ShuffleVectorInst::commuteShuffleMask(Indices, 4);
747   EXPECT_THAT(Indices, testing::ContainerEq(ArrayRef<int>({-1, 4, 3})));
748 }
749 
750 } // end anonymous namespace
751 } // end namespace llvm
752