1 //===- llvm/unittest/IR/InstructionsTest.cpp - Instructions unit tests ----===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/IR/Instructions.h"
10 #include "llvm/ADT/CombinationGenerator.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/Analysis/ValueTracking.h"
13 #include "llvm/Analysis/VectorUtils.h"
14 #include "llvm/AsmParser/Parser.h"
15 #include "llvm/IR/BasicBlock.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/DebugInfoMetadata.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/MDBuilder.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/NoFolder.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "gmock/gmock-matchers.h"
29 #include "gtest/gtest.h"
30 #include <memory>
31 
32 namespace llvm {
33 namespace {
34 
35 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
36   SMDiagnostic Err;
37   std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
38   if (!Mod)
39     Err.print("InstructionsTests", errs());
40   return Mod;
41 }
42 
43 TEST(InstructionsTest, ReturnInst) {
44   LLVMContext C;
45 
46   // test for PR6589
47   const ReturnInst* r0 = ReturnInst::Create(C);
48   EXPECT_EQ(r0->getNumOperands(), 0U);
49   EXPECT_EQ(r0->op_begin(), r0->op_end());
50 
51   IntegerType* Int1 = IntegerType::get(C, 1);
52   Constant* One = ConstantInt::get(Int1, 1, true);
53   const ReturnInst* r1 = ReturnInst::Create(C, One);
54   EXPECT_EQ(1U, r1->getNumOperands());
55   User::const_op_iterator b(r1->op_begin());
56   EXPECT_NE(r1->op_end(), b);
57   EXPECT_EQ(One, *b);
58   EXPECT_EQ(One, r1->getOperand(0));
59   ++b;
60   EXPECT_EQ(r1->op_end(), b);
61 
62   // clean up
63   delete r0;
64   delete r1;
65 }
66 
67 // Test fixture that provides a module and a single function within it. Useful
68 // for tests that need to refer to the function in some way.
69 class ModuleWithFunctionTest : public testing::Test {
70 protected:
71   ModuleWithFunctionTest() : M(new Module("MyModule", Ctx)) {
72     FArgTypes.push_back(Type::getInt8Ty(Ctx));
73     FArgTypes.push_back(Type::getInt32Ty(Ctx));
74     FArgTypes.push_back(Type::getInt64Ty(Ctx));
75     FunctionType *FTy =
76         FunctionType::get(Type::getVoidTy(Ctx), FArgTypes, false);
77     F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
78   }
79 
80   LLVMContext Ctx;
81   std::unique_ptr<Module> M;
82   SmallVector<Type *, 3> FArgTypes;
83   Function *F;
84 };
85 
86 TEST_F(ModuleWithFunctionTest, CallInst) {
87   Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20),
88                    ConstantInt::get(Type::getInt32Ty(Ctx), 9999),
89                    ConstantInt::get(Type::getInt64Ty(Ctx), 42)};
90   std::unique_ptr<CallInst> Call(CallInst::Create(F, Args));
91 
92   // Make sure iteration over a call's arguments works as expected.
93   unsigned Idx = 0;
94   for (Value *Arg : Call->args()) {
95     EXPECT_EQ(FArgTypes[Idx], Arg->getType());
96     EXPECT_EQ(Call->getArgOperand(Idx)->getType(), Arg->getType());
97     Idx++;
98   }
99 
100   Call->addRetAttr(Attribute::get(Call->getContext(), "test-str-attr"));
101   EXPECT_TRUE(Call->hasRetAttr("test-str-attr"));
102   EXPECT_FALSE(Call->hasRetAttr("not-on-call"));
103 }
104 
105 TEST_F(ModuleWithFunctionTest, InvokeInst) {
106   BasicBlock *BB1 = BasicBlock::Create(Ctx, "", F);
107   BasicBlock *BB2 = BasicBlock::Create(Ctx, "", F);
108 
109   Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20),
110                    ConstantInt::get(Type::getInt32Ty(Ctx), 9999),
111                    ConstantInt::get(Type::getInt64Ty(Ctx), 42)};
112   std::unique_ptr<InvokeInst> Invoke(InvokeInst::Create(F, BB1, BB2, Args));
113 
114   // Make sure iteration over invoke's arguments works as expected.
115   unsigned Idx = 0;
116   for (Value *Arg : Invoke->args()) {
117     EXPECT_EQ(FArgTypes[Idx], Arg->getType());
118     EXPECT_EQ(Invoke->getArgOperand(Idx)->getType(), Arg->getType());
119     Idx++;
120   }
121 }
122 
123 TEST(InstructionsTest, BranchInst) {
124   LLVMContext C;
125 
126   // Make a BasicBlocks
127   BasicBlock* bb0 = BasicBlock::Create(C);
128   BasicBlock* bb1 = BasicBlock::Create(C);
129 
130   // Mandatory BranchInst
131   const BranchInst* b0 = BranchInst::Create(bb0);
132 
133   EXPECT_TRUE(b0->isUnconditional());
134   EXPECT_FALSE(b0->isConditional());
135   EXPECT_EQ(1U, b0->getNumSuccessors());
136 
137   // check num operands
138   EXPECT_EQ(1U, b0->getNumOperands());
139 
140   EXPECT_NE(b0->op_begin(), b0->op_end());
141   EXPECT_EQ(b0->op_end(), std::next(b0->op_begin()));
142 
143   EXPECT_EQ(b0->op_end(), std::next(b0->op_begin()));
144 
145   IntegerType* Int1 = IntegerType::get(C, 1);
146   Constant* One = ConstantInt::get(Int1, 1, true);
147 
148   // Conditional BranchInst
149   BranchInst* b1 = BranchInst::Create(bb0, bb1, One);
150 
151   EXPECT_FALSE(b1->isUnconditional());
152   EXPECT_TRUE(b1->isConditional());
153   EXPECT_EQ(2U, b1->getNumSuccessors());
154 
155   // check num operands
156   EXPECT_EQ(3U, b1->getNumOperands());
157 
158   User::const_op_iterator b(b1->op_begin());
159 
160   // check COND
161   EXPECT_NE(b, b1->op_end());
162   EXPECT_EQ(One, *b);
163   EXPECT_EQ(One, b1->getOperand(0));
164   EXPECT_EQ(One, b1->getCondition());
165   ++b;
166 
167   // check ELSE
168   EXPECT_EQ(bb1, *b);
169   EXPECT_EQ(bb1, b1->getOperand(1));
170   EXPECT_EQ(bb1, b1->getSuccessor(1));
171   ++b;
172 
173   // check THEN
174   EXPECT_EQ(bb0, *b);
175   EXPECT_EQ(bb0, b1->getOperand(2));
176   EXPECT_EQ(bb0, b1->getSuccessor(0));
177   ++b;
178 
179   EXPECT_EQ(b1->op_end(), b);
180 
181   // clean up
182   delete b0;
183   delete b1;
184 
185   delete bb0;
186   delete bb1;
187 }
188 
189 TEST(InstructionsTest, CastInst) {
190   LLVMContext C;
191 
192   Type *Int8Ty = Type::getInt8Ty(C);
193   Type *Int16Ty = Type::getInt16Ty(C);
194   Type *Int32Ty = Type::getInt32Ty(C);
195   Type *Int64Ty = Type::getInt64Ty(C);
196   Type *V8x8Ty = FixedVectorType::get(Int8Ty, 8);
197   Type *V8x64Ty = FixedVectorType::get(Int64Ty, 8);
198   Type *X86MMXTy = Type::getX86_MMXTy(C);
199 
200   Type *HalfTy = Type::getHalfTy(C);
201   Type *FloatTy = Type::getFloatTy(C);
202   Type *DoubleTy = Type::getDoubleTy(C);
203 
204   Type *V2Int32Ty = FixedVectorType::get(Int32Ty, 2);
205   Type *V2Int64Ty = FixedVectorType::get(Int64Ty, 2);
206   Type *V4Int16Ty = FixedVectorType::get(Int16Ty, 4);
207   Type *V1Int16Ty = FixedVectorType::get(Int16Ty, 1);
208 
209   Type *VScaleV2Int32Ty = ScalableVectorType::get(Int32Ty, 2);
210   Type *VScaleV2Int64Ty = ScalableVectorType::get(Int64Ty, 2);
211   Type *VScaleV4Int16Ty = ScalableVectorType::get(Int16Ty, 4);
212   Type *VScaleV1Int16Ty = ScalableVectorType::get(Int16Ty, 1);
213 
214   Type *Int32PtrTy = PointerType::get(Int32Ty, 0);
215   Type *Int64PtrTy = PointerType::get(Int64Ty, 0);
216 
217   Type *Int32PtrAS1Ty = PointerType::get(Int32Ty, 1);
218   Type *Int64PtrAS1Ty = PointerType::get(Int64Ty, 1);
219 
220   Type *V2Int32PtrAS1Ty = FixedVectorType::get(Int32PtrAS1Ty, 2);
221   Type *V2Int64PtrAS1Ty = FixedVectorType::get(Int64PtrAS1Ty, 2);
222   Type *V4Int32PtrAS1Ty = FixedVectorType::get(Int32PtrAS1Ty, 4);
223   Type *VScaleV4Int32PtrAS1Ty = ScalableVectorType::get(Int32PtrAS1Ty, 4);
224   Type *V4Int64PtrAS1Ty = FixedVectorType::get(Int64PtrAS1Ty, 4);
225 
226   Type *V2Int64PtrTy = FixedVectorType::get(Int64PtrTy, 2);
227   Type *V2Int32PtrTy = FixedVectorType::get(Int32PtrTy, 2);
228   Type *VScaleV2Int32PtrTy = ScalableVectorType::get(Int32PtrTy, 2);
229   Type *V4Int32PtrTy = FixedVectorType::get(Int32PtrTy, 4);
230   Type *VScaleV4Int32PtrTy = ScalableVectorType::get(Int32PtrTy, 4);
231   Type *VScaleV4Int64PtrTy = ScalableVectorType::get(Int64PtrTy, 4);
232 
233   const Constant* c8 = Constant::getNullValue(V8x8Ty);
234   const Constant* c64 = Constant::getNullValue(V8x64Ty);
235 
236   const Constant *v2ptr32 = Constant::getNullValue(V2Int32PtrTy);
237 
238   EXPECT_EQ(CastInst::Trunc, CastInst::getCastOpcode(c64, true, V8x8Ty, true));
239   EXPECT_EQ(CastInst::SExt, CastInst::getCastOpcode(c8, true, V8x64Ty, true));
240 
241   EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, X86MMXTy));
242   EXPECT_FALSE(CastInst::isBitCastable(X86MMXTy, V8x8Ty));
243   EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, X86MMXTy));
244   EXPECT_FALSE(CastInst::isBitCastable(V8x64Ty, V8x8Ty));
245   EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, V8x64Ty));
246 
247   // Check address space casts are rejected since we don't know the sizes here
248   EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, Int32PtrAS1Ty));
249   EXPECT_FALSE(CastInst::isBitCastable(Int32PtrAS1Ty, Int32PtrTy));
250   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, V2Int32PtrAS1Ty));
251   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int32PtrTy));
252   EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int64PtrAS1Ty));
253   EXPECT_EQ(CastInst::AddrSpaceCast, CastInst::getCastOpcode(v2ptr32, true,
254                                                              V2Int32PtrAS1Ty,
255                                                              true));
256 
257   // Test mismatched number of elements for pointers
258   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int64PtrAS1Ty));
259   EXPECT_FALSE(CastInst::isBitCastable(V4Int64PtrAS1Ty, V2Int32PtrAS1Ty));
260   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int32PtrAS1Ty));
261   EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, V2Int32PtrTy));
262   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, Int32PtrTy));
263 
264   EXPECT_TRUE(CastInst::isBitCastable(Int32PtrTy, Int64PtrTy));
265   EXPECT_FALSE(CastInst::isBitCastable(DoubleTy, FloatTy));
266   EXPECT_FALSE(CastInst::isBitCastable(FloatTy, DoubleTy));
267   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy));
268   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy));
269   EXPECT_TRUE(CastInst::isBitCastable(FloatTy, Int32Ty));
270   EXPECT_TRUE(CastInst::isBitCastable(Int16Ty, HalfTy));
271   EXPECT_TRUE(CastInst::isBitCastable(Int32Ty, FloatTy));
272   EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, Int64Ty));
273 
274   EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, V4Int16Ty));
275   EXPECT_FALSE(CastInst::isBitCastable(Int32Ty, Int64Ty));
276   EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, Int32Ty));
277 
278   EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, Int64Ty));
279   EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, V2Int32PtrTy));
280   EXPECT_TRUE(CastInst::isBitCastable(V2Int64PtrTy, V2Int32PtrTy));
281   EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrTy, V2Int64PtrTy));
282   EXPECT_FALSE(CastInst::isBitCastable(V2Int32Ty, V2Int64Ty));
283   EXPECT_FALSE(CastInst::isBitCastable(V2Int64Ty, V2Int32Ty));
284 
285 
286   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
287                                      Constant::getNullValue(V4Int32PtrTy),
288                                      V2Int32PtrTy));
289   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
290                                      Constant::getNullValue(V2Int32PtrTy),
291                                      V4Int32PtrTy));
292 
293   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
294                                      Constant::getNullValue(V4Int32PtrAS1Ty),
295                                      V2Int32PtrTy));
296   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
297                                      Constant::getNullValue(V2Int32PtrTy),
298                                      V4Int32PtrAS1Ty));
299 
300   // Address space cast of fixed/scalable vectors of pointers to scalable/fixed
301   // vector of pointers.
302   EXPECT_FALSE(CastInst::castIsValid(
303       Instruction::AddrSpaceCast, Constant::getNullValue(VScaleV4Int32PtrAS1Ty),
304       V4Int32PtrTy));
305   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
306                                      Constant::getNullValue(V4Int32PtrTy),
307                                      VScaleV4Int32PtrAS1Ty));
308   // Address space cast of scalable vectors of pointers to scalable vector of
309   // pointers.
310   EXPECT_FALSE(CastInst::castIsValid(
311       Instruction::AddrSpaceCast, Constant::getNullValue(VScaleV4Int32PtrAS1Ty),
312       VScaleV2Int32PtrTy));
313   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
314                                      Constant::getNullValue(VScaleV2Int32PtrTy),
315                                      VScaleV4Int32PtrAS1Ty));
316   EXPECT_TRUE(CastInst::castIsValid(Instruction::AddrSpaceCast,
317                                     Constant::getNullValue(VScaleV4Int64PtrTy),
318                                     VScaleV4Int32PtrAS1Ty));
319   // Same number of lanes, different address space.
320   EXPECT_TRUE(CastInst::castIsValid(
321       Instruction::AddrSpaceCast, Constant::getNullValue(VScaleV4Int32PtrAS1Ty),
322       VScaleV4Int32PtrTy));
323   // Same number of lanes, same address space.
324   EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
325                                      Constant::getNullValue(VScaleV4Int64PtrTy),
326                                      VScaleV4Int32PtrTy));
327 
328   // Bit casting fixed/scalable vector to scalable/fixed vectors.
329   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
330                                      Constant::getNullValue(V2Int32Ty),
331                                      VScaleV2Int32Ty));
332   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
333                                      Constant::getNullValue(V2Int64Ty),
334                                      VScaleV2Int64Ty));
335   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
336                                      Constant::getNullValue(V4Int16Ty),
337                                      VScaleV4Int16Ty));
338   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
339                                      Constant::getNullValue(VScaleV2Int32Ty),
340                                      V2Int32Ty));
341   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
342                                      Constant::getNullValue(VScaleV2Int64Ty),
343                                      V2Int64Ty));
344   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
345                                      Constant::getNullValue(VScaleV4Int16Ty),
346                                      V4Int16Ty));
347 
348   // Bit casting scalable vectors to scalable vectors.
349   EXPECT_TRUE(CastInst::castIsValid(Instruction::BitCast,
350                                     Constant::getNullValue(VScaleV4Int16Ty),
351                                     VScaleV2Int32Ty));
352   EXPECT_TRUE(CastInst::castIsValid(Instruction::BitCast,
353                                     Constant::getNullValue(VScaleV2Int32Ty),
354                                     VScaleV4Int16Ty));
355   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
356                                      Constant::getNullValue(VScaleV2Int64Ty),
357                                      VScaleV2Int32Ty));
358   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
359                                      Constant::getNullValue(VScaleV2Int32Ty),
360                                      VScaleV2Int64Ty));
361 
362   // Bitcasting to/from <vscale x 1 x Ty>
363   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
364                                      Constant::getNullValue(VScaleV1Int16Ty),
365                                      V1Int16Ty));
366   EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
367                                      Constant::getNullValue(V1Int16Ty),
368                                      VScaleV1Int16Ty));
369 
370   // Check that assertion is not hit when creating a cast with a vector of
371   // pointers
372   // First form
373   BasicBlock *BB = BasicBlock::Create(C);
374   Constant *NullV2I32Ptr = Constant::getNullValue(V2Int32PtrTy);
375   auto Inst1 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty, "foo", BB);
376 
377   Constant *NullVScaleV2I32Ptr = Constant::getNullValue(VScaleV2Int32PtrTy);
378   auto Inst1VScale = CastInst::CreatePointerCast(
379       NullVScaleV2I32Ptr, VScaleV2Int32Ty, "foo.vscale", BB);
380 
381   // Second form
382   auto Inst2 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty);
383   auto Inst2VScale =
384       CastInst::CreatePointerCast(NullVScaleV2I32Ptr, VScaleV2Int32Ty);
385 
386   delete Inst2;
387   delete Inst2VScale;
388   Inst1->eraseFromParent();
389   Inst1VScale->eraseFromParent();
390   delete BB;
391 }
392 
393 TEST(InstructionsTest, VectorGep) {
394   LLVMContext C;
395 
396   // Type Definitions
397   Type *I8Ty = IntegerType::get(C, 8);
398   Type *I32Ty = IntegerType::get(C, 32);
399   PointerType *Ptri8Ty = PointerType::get(I8Ty, 0);
400   PointerType *Ptri32Ty = PointerType::get(I32Ty, 0);
401 
402   VectorType *V2xi8PTy = FixedVectorType::get(Ptri8Ty, 2);
403   VectorType *V2xi32PTy = FixedVectorType::get(Ptri32Ty, 2);
404 
405   // Test different aspects of the vector-of-pointers type
406   // and GEPs which use this type.
407   ConstantInt *Ci32a = ConstantInt::get(C, APInt(32, 1492));
408   ConstantInt *Ci32b = ConstantInt::get(C, APInt(32, 1948));
409   std::vector<Constant*> ConstVa(2, Ci32a);
410   std::vector<Constant*> ConstVb(2, Ci32b);
411   Constant *C2xi32a = ConstantVector::get(ConstVa);
412   Constant *C2xi32b = ConstantVector::get(ConstVb);
413 
414   CastInst *PtrVecA = new IntToPtrInst(C2xi32a, V2xi32PTy);
415   CastInst *PtrVecB = new IntToPtrInst(C2xi32b, V2xi32PTy);
416 
417   ICmpInst *ICmp0 = new ICmpInst(ICmpInst::ICMP_SGT, PtrVecA, PtrVecB);
418   ICmpInst *ICmp1 = new ICmpInst(ICmpInst::ICMP_ULT, PtrVecA, PtrVecB);
419   EXPECT_NE(ICmp0, ICmp1); // suppress warning.
420 
421   BasicBlock* BB0 = BasicBlock::Create(C);
422   // Test InsertAtEnd ICmpInst constructor.
423   ICmpInst *ICmp2 = new ICmpInst(*BB0, ICmpInst::ICMP_SGE, PtrVecA, PtrVecB);
424   EXPECT_NE(ICmp0, ICmp2); // suppress warning.
425 
426   GetElementPtrInst *Gep0 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32a);
427   GetElementPtrInst *Gep1 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32b);
428   GetElementPtrInst *Gep2 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32a);
429   GetElementPtrInst *Gep3 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32b);
430 
431   CastInst *BTC0 = new BitCastInst(Gep0, V2xi8PTy);
432   CastInst *BTC1 = new BitCastInst(Gep1, V2xi8PTy);
433   CastInst *BTC2 = new BitCastInst(Gep2, V2xi8PTy);
434   CastInst *BTC3 = new BitCastInst(Gep3, V2xi8PTy);
435 
436   Value *S0 = BTC0->stripPointerCasts();
437   Value *S1 = BTC1->stripPointerCasts();
438   Value *S2 = BTC2->stripPointerCasts();
439   Value *S3 = BTC3->stripPointerCasts();
440 
441   EXPECT_NE(S0, Gep0);
442   EXPECT_NE(S1, Gep1);
443   EXPECT_NE(S2, Gep2);
444   EXPECT_NE(S3, Gep3);
445 
446   int64_t Offset;
447   DataLayout TD("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f3"
448                 "2:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-s:64:64-f80"
449                 ":128:128-n8:16:32:64-S128");
450   // Make sure we don't crash
451   GetPointerBaseWithConstantOffset(Gep0, Offset, TD);
452   GetPointerBaseWithConstantOffset(Gep1, Offset, TD);
453   GetPointerBaseWithConstantOffset(Gep2, Offset, TD);
454   GetPointerBaseWithConstantOffset(Gep3, Offset, TD);
455 
456   // Gep of Geps
457   GetElementPtrInst *GepII0 = GetElementPtrInst::Create(I32Ty, Gep0, C2xi32b);
458   GetElementPtrInst *GepII1 = GetElementPtrInst::Create(I32Ty, Gep1, C2xi32a);
459   GetElementPtrInst *GepII2 = GetElementPtrInst::Create(I32Ty, Gep2, C2xi32b);
460   GetElementPtrInst *GepII3 = GetElementPtrInst::Create(I32Ty, Gep3, C2xi32a);
461 
462   EXPECT_EQ(GepII0->getNumIndices(), 1u);
463   EXPECT_EQ(GepII1->getNumIndices(), 1u);
464   EXPECT_EQ(GepII2->getNumIndices(), 1u);
465   EXPECT_EQ(GepII3->getNumIndices(), 1u);
466 
467   EXPECT_FALSE(GepII0->hasAllZeroIndices());
468   EXPECT_FALSE(GepII1->hasAllZeroIndices());
469   EXPECT_FALSE(GepII2->hasAllZeroIndices());
470   EXPECT_FALSE(GepII3->hasAllZeroIndices());
471 
472   delete GepII0;
473   delete GepII1;
474   delete GepII2;
475   delete GepII3;
476 
477   delete BTC0;
478   delete BTC1;
479   delete BTC2;
480   delete BTC3;
481 
482   delete Gep0;
483   delete Gep1;
484   delete Gep2;
485   delete Gep3;
486 
487   ICmp2->eraseFromParent();
488   delete BB0;
489 
490   delete ICmp0;
491   delete ICmp1;
492   delete PtrVecA;
493   delete PtrVecB;
494 }
495 
496 TEST(InstructionsTest, FPMathOperator) {
497   LLVMContext Context;
498   IRBuilder<> Builder(Context);
499   MDBuilder MDHelper(Context);
500   Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
501   MDNode *MD1 = MDHelper.createFPMath(1.0);
502   Value *V1 = Builder.CreateFAdd(I, I, "", MD1);
503   EXPECT_TRUE(isa<FPMathOperator>(V1));
504   FPMathOperator *O1 = cast<FPMathOperator>(V1);
505   EXPECT_EQ(O1->getFPAccuracy(), 1.0);
506   V1->deleteValue();
507   I->deleteValue();
508 }
509 
510 
511 TEST(InstructionsTest, isEliminableCastPair) {
512   LLVMContext C;
513 
514   Type* Int16Ty = Type::getInt16Ty(C);
515   Type* Int32Ty = Type::getInt32Ty(C);
516   Type* Int64Ty = Type::getInt64Ty(C);
517   Type* Int64PtrTy = Type::getInt64PtrTy(C);
518 
519   // Source and destination pointers have same size -> bitcast.
520   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
521                                            CastInst::IntToPtr,
522                                            Int64PtrTy, Int64Ty, Int64PtrTy,
523                                            Int32Ty, nullptr, Int32Ty),
524             CastInst::BitCast);
525 
526   // Source and destination have unknown sizes, but the same address space and
527   // the intermediate int is the maximum pointer size -> bitcast
528   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
529                                            CastInst::IntToPtr,
530                                            Int64PtrTy, Int64Ty, Int64PtrTy,
531                                            nullptr, nullptr, nullptr),
532             CastInst::BitCast);
533 
534   // Source and destination have unknown sizes, but the same address space and
535   // the intermediate int is not the maximum pointer size -> nothing
536   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
537                                            CastInst::IntToPtr,
538                                            Int64PtrTy, Int32Ty, Int64PtrTy,
539                                            nullptr, nullptr, nullptr),
540             0U);
541 
542   // Middle pointer big enough -> bitcast.
543   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
544                                            CastInst::PtrToInt,
545                                            Int64Ty, Int64PtrTy, Int64Ty,
546                                            nullptr, Int64Ty, nullptr),
547             CastInst::BitCast);
548 
549   // Middle pointer too small -> fail.
550   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
551                                            CastInst::PtrToInt,
552                                            Int64Ty, Int64PtrTy, Int64Ty,
553                                            nullptr, Int32Ty, nullptr),
554             0U);
555 
556   // Test that we don't eliminate bitcasts between different address spaces,
557   // or if we don't have available pointer size information.
558   DataLayout DL("e-p:32:32:32-p1:16:16:16-p2:64:64:64-i1:8:8-i8:8:8-i16:16:16"
559                 "-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64"
560                 "-v128:128:128-a:0:64-s:64:64-f80:128:128-n8:16:32:64-S128");
561 
562   Type* Int64PtrTyAS1 = Type::getInt64PtrTy(C, 1);
563   Type* Int64PtrTyAS2 = Type::getInt64PtrTy(C, 2);
564 
565   IntegerType *Int16SizePtr = DL.getIntPtrType(C, 1);
566   IntegerType *Int64SizePtr = DL.getIntPtrType(C, 2);
567 
568   // Cannot simplify inttoptr, addrspacecast
569   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
570                                            CastInst::AddrSpaceCast,
571                                            Int16Ty, Int64PtrTyAS1, Int64PtrTyAS2,
572                                            nullptr, Int16SizePtr, Int64SizePtr),
573             0U);
574 
575   // Cannot simplify addrspacecast, ptrtoint
576   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::AddrSpaceCast,
577                                            CastInst::PtrToInt,
578                                            Int64PtrTyAS1, Int64PtrTyAS2, Int16Ty,
579                                            Int64SizePtr, Int16SizePtr, nullptr),
580             0U);
581 
582   // Pass since the bitcast address spaces are the same
583   EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
584                                            CastInst::BitCast,
585                                            Int16Ty, Int64PtrTyAS1, Int64PtrTyAS1,
586                                            nullptr, nullptr, nullptr),
587             CastInst::IntToPtr);
588 
589 }
590 
591 TEST(InstructionsTest, CloneCall) {
592   LLVMContext C;
593   Type *Int32Ty = Type::getInt32Ty(C);
594   Type *ArgTys[] = {Int32Ty, Int32Ty, Int32Ty};
595   FunctionType *FnTy = FunctionType::get(Int32Ty, ArgTys, /*isVarArg=*/false);
596   Value *Callee = Constant::getNullValue(FnTy->getPointerTo());
597   Value *Args[] = {
598     ConstantInt::get(Int32Ty, 1),
599     ConstantInt::get(Int32Ty, 2),
600     ConstantInt::get(Int32Ty, 3)
601   };
602   std::unique_ptr<CallInst> Call(
603       CallInst::Create(FnTy, Callee, Args, "result"));
604 
605   // Test cloning the tail call kind.
606   CallInst::TailCallKind Kinds[] = {CallInst::TCK_None, CallInst::TCK_Tail,
607                                     CallInst::TCK_MustTail};
608   for (CallInst::TailCallKind TCK : Kinds) {
609     Call->setTailCallKind(TCK);
610     std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone()));
611     EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind());
612   }
613   Call->setTailCallKind(CallInst::TCK_None);
614 
615   // Test cloning an attribute.
616   {
617     AttrBuilder AB(C);
618     AB.addAttribute(Attribute::ReadOnly);
619     Call->setAttributes(
620         AttributeList::get(C, AttributeList::FunctionIndex, AB));
621     std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone()));
622     EXPECT_TRUE(Clone->onlyReadsMemory());
623   }
624 }
625 
626 TEST(InstructionsTest, AlterCallBundles) {
627   LLVMContext C;
628   Type *Int32Ty = Type::getInt32Ty(C);
629   FunctionType *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
630   Value *Callee = Constant::getNullValue(FnTy->getPointerTo());
631   Value *Args[] = {ConstantInt::get(Int32Ty, 42)};
632   OperandBundleDef OldBundle("before", UndefValue::get(Int32Ty));
633   std::unique_ptr<CallInst> Call(
634       CallInst::Create(FnTy, Callee, Args, OldBundle, "result"));
635   Call->setTailCallKind(CallInst::TailCallKind::TCK_NoTail);
636   AttrBuilder AB(C);
637   AB.addAttribute(Attribute::Cold);
638   Call->setAttributes(AttributeList::get(C, AttributeList::FunctionIndex, AB));
639   Call->setDebugLoc(DebugLoc(MDNode::get(C, None)));
640 
641   OperandBundleDef NewBundle("after", ConstantInt::get(Int32Ty, 7));
642   std::unique_ptr<CallInst> Clone(CallInst::Create(Call.get(), NewBundle));
643   EXPECT_EQ(Call->arg_size(), Clone->arg_size());
644   EXPECT_EQ(Call->getArgOperand(0), Clone->getArgOperand(0));
645   EXPECT_EQ(Call->getCallingConv(), Clone->getCallingConv());
646   EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind());
647   EXPECT_TRUE(Clone->hasFnAttr(Attribute::AttrKind::Cold));
648   EXPECT_EQ(Call->getDebugLoc(), Clone->getDebugLoc());
649   EXPECT_EQ(Clone->getNumOperandBundles(), 1U);
650   EXPECT_TRUE(Clone->getOperandBundle("after").hasValue());
651 }
652 
653 TEST(InstructionsTest, AlterInvokeBundles) {
654   LLVMContext C;
655   Type *Int32Ty = Type::getInt32Ty(C);
656   FunctionType *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
657   Value *Callee = Constant::getNullValue(FnTy->getPointerTo());
658   Value *Args[] = {ConstantInt::get(Int32Ty, 42)};
659   std::unique_ptr<BasicBlock> NormalDest(BasicBlock::Create(C));
660   std::unique_ptr<BasicBlock> UnwindDest(BasicBlock::Create(C));
661   OperandBundleDef OldBundle("before", UndefValue::get(Int32Ty));
662   std::unique_ptr<InvokeInst> Invoke(
663       InvokeInst::Create(FnTy, Callee, NormalDest.get(), UnwindDest.get(), Args,
664                          OldBundle, "result"));
665   AttrBuilder AB(C);
666   AB.addAttribute(Attribute::Cold);
667   Invoke->setAttributes(
668       AttributeList::get(C, AttributeList::FunctionIndex, AB));
669   Invoke->setDebugLoc(DebugLoc(MDNode::get(C, None)));
670 
671   OperandBundleDef NewBundle("after", ConstantInt::get(Int32Ty, 7));
672   std::unique_ptr<InvokeInst> Clone(
673       InvokeInst::Create(Invoke.get(), NewBundle));
674   EXPECT_EQ(Invoke->getNormalDest(), Clone->getNormalDest());
675   EXPECT_EQ(Invoke->getUnwindDest(), Clone->getUnwindDest());
676   EXPECT_EQ(Invoke->arg_size(), Clone->arg_size());
677   EXPECT_EQ(Invoke->getArgOperand(0), Clone->getArgOperand(0));
678   EXPECT_EQ(Invoke->getCallingConv(), Clone->getCallingConv());
679   EXPECT_TRUE(Clone->hasFnAttr(Attribute::AttrKind::Cold));
680   EXPECT_EQ(Invoke->getDebugLoc(), Clone->getDebugLoc());
681   EXPECT_EQ(Clone->getNumOperandBundles(), 1U);
682   EXPECT_TRUE(Clone->getOperandBundle("after").hasValue());
683 }
684 
685 TEST_F(ModuleWithFunctionTest, DropPoisonGeneratingFlags) {
686   auto *OnlyBB = BasicBlock::Create(Ctx, "bb", F);
687   auto *Arg0 = &*F->arg_begin();
688 
689   IRBuilder<NoFolder> B(Ctx);
690   B.SetInsertPoint(OnlyBB);
691 
692   {
693     auto *UI =
694         cast<Instruction>(B.CreateUDiv(Arg0, Arg0, "", /*isExact*/ true));
695     ASSERT_TRUE(UI->isExact());
696     UI->dropPoisonGeneratingFlags();
697     ASSERT_FALSE(UI->isExact());
698   }
699 
700   {
701     auto *ShrI =
702         cast<Instruction>(B.CreateLShr(Arg0, Arg0, "", /*isExact*/ true));
703     ASSERT_TRUE(ShrI->isExact());
704     ShrI->dropPoisonGeneratingFlags();
705     ASSERT_FALSE(ShrI->isExact());
706   }
707 
708   {
709     auto *AI = cast<Instruction>(
710         B.CreateAdd(Arg0, Arg0, "", /*HasNUW*/ true, /*HasNSW*/ false));
711     ASSERT_TRUE(AI->hasNoUnsignedWrap());
712     AI->dropPoisonGeneratingFlags();
713     ASSERT_FALSE(AI->hasNoUnsignedWrap());
714     ASSERT_FALSE(AI->hasNoSignedWrap());
715   }
716 
717   {
718     auto *SI = cast<Instruction>(
719         B.CreateAdd(Arg0, Arg0, "", /*HasNUW*/ false, /*HasNSW*/ true));
720     ASSERT_TRUE(SI->hasNoSignedWrap());
721     SI->dropPoisonGeneratingFlags();
722     ASSERT_FALSE(SI->hasNoUnsignedWrap());
723     ASSERT_FALSE(SI->hasNoSignedWrap());
724   }
725 
726   {
727     auto *ShlI = cast<Instruction>(
728         B.CreateShl(Arg0, Arg0, "", /*HasNUW*/ true, /*HasNSW*/ true));
729     ASSERT_TRUE(ShlI->hasNoSignedWrap());
730     ASSERT_TRUE(ShlI->hasNoUnsignedWrap());
731     ShlI->dropPoisonGeneratingFlags();
732     ASSERT_FALSE(ShlI->hasNoUnsignedWrap());
733     ASSERT_FALSE(ShlI->hasNoSignedWrap());
734   }
735 
736   {
737     Value *GEPBase = Constant::getNullValue(B.getInt8PtrTy());
738     auto *GI = cast<GetElementPtrInst>(
739         B.CreateInBoundsGEP(B.getInt8Ty(), GEPBase, Arg0));
740     ASSERT_TRUE(GI->isInBounds());
741     GI->dropPoisonGeneratingFlags();
742     ASSERT_FALSE(GI->isInBounds());
743   }
744 }
745 
746 TEST(InstructionsTest, GEPIndices) {
747   LLVMContext Context;
748   IRBuilder<NoFolder> Builder(Context);
749   Type *ElementTy = Builder.getInt8Ty();
750   Type *ArrTy = ArrayType::get(ArrayType::get(ElementTy, 64), 64);
751   Value *Indices[] = {
752     Builder.getInt32(0),
753     Builder.getInt32(13),
754     Builder.getInt32(42) };
755 
756   Value *V = Builder.CreateGEP(ArrTy, UndefValue::get(PointerType::getUnqual(ArrTy)),
757                                Indices);
758   ASSERT_TRUE(isa<GetElementPtrInst>(V));
759 
760   auto *GEPI = cast<GetElementPtrInst>(V);
761   ASSERT_NE(GEPI->idx_begin(), GEPI->idx_end());
762   ASSERT_EQ(GEPI->idx_end(), std::next(GEPI->idx_begin(), 3));
763   EXPECT_EQ(Indices[0], GEPI->idx_begin()[0]);
764   EXPECT_EQ(Indices[1], GEPI->idx_begin()[1]);
765   EXPECT_EQ(Indices[2], GEPI->idx_begin()[2]);
766   EXPECT_EQ(GEPI->idx_begin(), GEPI->indices().begin());
767   EXPECT_EQ(GEPI->idx_end(), GEPI->indices().end());
768 
769   const auto *CGEPI = GEPI;
770   ASSERT_NE(CGEPI->idx_begin(), CGEPI->idx_end());
771   ASSERT_EQ(CGEPI->idx_end(), std::next(CGEPI->idx_begin(), 3));
772   EXPECT_EQ(Indices[0], CGEPI->idx_begin()[0]);
773   EXPECT_EQ(Indices[1], CGEPI->idx_begin()[1]);
774   EXPECT_EQ(Indices[2], CGEPI->idx_begin()[2]);
775   EXPECT_EQ(CGEPI->idx_begin(), CGEPI->indices().begin());
776   EXPECT_EQ(CGEPI->idx_end(), CGEPI->indices().end());
777 
778   delete GEPI;
779 }
780 
781 TEST(InstructionsTest, SwitchInst) {
782   LLVMContext C;
783 
784   std::unique_ptr<BasicBlock> BB1, BB2, BB3;
785   BB1.reset(BasicBlock::Create(C));
786   BB2.reset(BasicBlock::Create(C));
787   BB3.reset(BasicBlock::Create(C));
788 
789   // We create block 0 after the others so that it gets destroyed first and
790   // clears the uses of the other basic blocks.
791   std::unique_ptr<BasicBlock> BB0(BasicBlock::Create(C));
792 
793   auto *Int32Ty = Type::getInt32Ty(C);
794 
795   SwitchInst *SI =
796       SwitchInst::Create(UndefValue::get(Int32Ty), BB0.get(), 3, BB0.get());
797   SI->addCase(ConstantInt::get(Int32Ty, 1), BB1.get());
798   SI->addCase(ConstantInt::get(Int32Ty, 2), BB2.get());
799   SI->addCase(ConstantInt::get(Int32Ty, 3), BB3.get());
800 
801   auto CI = SI->case_begin();
802   ASSERT_NE(CI, SI->case_end());
803   EXPECT_EQ(1, CI->getCaseValue()->getSExtValue());
804   EXPECT_EQ(BB1.get(), CI->getCaseSuccessor());
805   EXPECT_EQ(2, (CI + 1)->getCaseValue()->getSExtValue());
806   EXPECT_EQ(BB2.get(), (CI + 1)->getCaseSuccessor());
807   EXPECT_EQ(3, (CI + 2)->getCaseValue()->getSExtValue());
808   EXPECT_EQ(BB3.get(), (CI + 2)->getCaseSuccessor());
809   EXPECT_EQ(CI + 1, std::next(CI));
810   EXPECT_EQ(CI + 2, std::next(CI, 2));
811   EXPECT_EQ(CI + 3, std::next(CI, 3));
812   EXPECT_EQ(SI->case_end(), CI + 3);
813   EXPECT_EQ(0, CI - CI);
814   EXPECT_EQ(1, (CI + 1) - CI);
815   EXPECT_EQ(2, (CI + 2) - CI);
816   EXPECT_EQ(3, SI->case_end() - CI);
817   EXPECT_EQ(3, std::distance(CI, SI->case_end()));
818 
819   auto CCI = const_cast<const SwitchInst *>(SI)->case_begin();
820   SwitchInst::ConstCaseIt CCE = SI->case_end();
821   ASSERT_NE(CCI, SI->case_end());
822   EXPECT_EQ(1, CCI->getCaseValue()->getSExtValue());
823   EXPECT_EQ(BB1.get(), CCI->getCaseSuccessor());
824   EXPECT_EQ(2, (CCI + 1)->getCaseValue()->getSExtValue());
825   EXPECT_EQ(BB2.get(), (CCI + 1)->getCaseSuccessor());
826   EXPECT_EQ(3, (CCI + 2)->getCaseValue()->getSExtValue());
827   EXPECT_EQ(BB3.get(), (CCI + 2)->getCaseSuccessor());
828   EXPECT_EQ(CCI + 1, std::next(CCI));
829   EXPECT_EQ(CCI + 2, std::next(CCI, 2));
830   EXPECT_EQ(CCI + 3, std::next(CCI, 3));
831   EXPECT_EQ(CCE, CCI + 3);
832   EXPECT_EQ(0, CCI - CCI);
833   EXPECT_EQ(1, (CCI + 1) - CCI);
834   EXPECT_EQ(2, (CCI + 2) - CCI);
835   EXPECT_EQ(3, CCE - CCI);
836   EXPECT_EQ(3, std::distance(CCI, CCE));
837 
838   // Make sure that the const iterator is compatible with a const auto ref.
839   const auto &Handle = *CCI;
840   EXPECT_EQ(1, Handle.getCaseValue()->getSExtValue());
841   EXPECT_EQ(BB1.get(), Handle.getCaseSuccessor());
842 }
843 
844 TEST(InstructionsTest, SwitchInstProfUpdateWrapper) {
845   LLVMContext C;
846 
847   std::unique_ptr<BasicBlock> BB1, BB2, BB3;
848   BB1.reset(BasicBlock::Create(C));
849   BB2.reset(BasicBlock::Create(C));
850   BB3.reset(BasicBlock::Create(C));
851 
852   // We create block 0 after the others so that it gets destroyed first and
853   // clears the uses of the other basic blocks.
854   std::unique_ptr<BasicBlock> BB0(BasicBlock::Create(C));
855 
856   auto *Int32Ty = Type::getInt32Ty(C);
857 
858   SwitchInst *SI =
859       SwitchInst::Create(UndefValue::get(Int32Ty), BB0.get(), 4, BB0.get());
860   SI->addCase(ConstantInt::get(Int32Ty, 1), BB1.get());
861   SI->addCase(ConstantInt::get(Int32Ty, 2), BB2.get());
862   SI->setMetadata(LLVMContext::MD_prof,
863                   MDBuilder(C).createBranchWeights({ 9, 1, 22 }));
864 
865   {
866     SwitchInstProfUpdateWrapper SIW(*SI);
867     EXPECT_EQ(*SIW.getSuccessorWeight(0), 9u);
868     EXPECT_EQ(*SIW.getSuccessorWeight(1), 1u);
869     EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
870     SIW.setSuccessorWeight(0, 99u);
871     SIW.setSuccessorWeight(1, 11u);
872     EXPECT_EQ(*SIW.getSuccessorWeight(0), 99u);
873     EXPECT_EQ(*SIW.getSuccessorWeight(1), 11u);
874     EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
875   }
876 
877   { // Create another wrapper and check that the data persist.
878     SwitchInstProfUpdateWrapper SIW(*SI);
879     EXPECT_EQ(*SIW.getSuccessorWeight(0), 99u);
880     EXPECT_EQ(*SIW.getSuccessorWeight(1), 11u);
881     EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
882   }
883 }
884 
885 TEST(InstructionsTest, CommuteShuffleMask) {
886   SmallVector<int, 16> Indices({-1, 0, 7});
887   ShuffleVectorInst::commuteShuffleMask(Indices, 4);
888   EXPECT_THAT(Indices, testing::ContainerEq(ArrayRef<int>({-1, 4, 3})));
889 }
890 
891 TEST(InstructionsTest, ShuffleMaskQueries) {
892   // Create the elements for various constant vectors.
893   LLVMContext Ctx;
894   Type *Int32Ty = Type::getInt32Ty(Ctx);
895   Constant *CU = UndefValue::get(Int32Ty);
896   Constant *C0 = ConstantInt::get(Int32Ty, 0);
897   Constant *C1 = ConstantInt::get(Int32Ty, 1);
898   Constant *C2 = ConstantInt::get(Int32Ty, 2);
899   Constant *C3 = ConstantInt::get(Int32Ty, 3);
900   Constant *C4 = ConstantInt::get(Int32Ty, 4);
901   Constant *C5 = ConstantInt::get(Int32Ty, 5);
902   Constant *C6 = ConstantInt::get(Int32Ty, 6);
903   Constant *C7 = ConstantInt::get(Int32Ty, 7);
904 
905   Constant *Identity = ConstantVector::get({C0, CU, C2, C3, C4});
906   EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(Identity));
907   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(Identity)); // identity is distinguished from select
908   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(Identity));
909   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(Identity)); // identity is always single source
910   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(Identity));
911   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(Identity));
912 
913   Constant *Select = ConstantVector::get({CU, C1, C5});
914   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(Select));
915   EXPECT_TRUE(ShuffleVectorInst::isSelectMask(Select));
916   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(Select));
917   EXPECT_FALSE(ShuffleVectorInst::isSingleSourceMask(Select));
918   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(Select));
919   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(Select));
920 
921   Constant *Reverse = ConstantVector::get({C3, C2, C1, CU});
922   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(Reverse));
923   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(Reverse));
924   EXPECT_TRUE(ShuffleVectorInst::isReverseMask(Reverse));
925   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(Reverse)); // reverse is always single source
926   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(Reverse));
927   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(Reverse));
928 
929   Constant *SingleSource = ConstantVector::get({C2, C2, C0, CU});
930   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(SingleSource));
931   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(SingleSource));
932   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(SingleSource));
933   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(SingleSource));
934   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(SingleSource));
935   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(SingleSource));
936 
937   Constant *ZeroEltSplat = ConstantVector::get({C0, C0, CU, C0});
938   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(ZeroEltSplat));
939   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(ZeroEltSplat));
940   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(ZeroEltSplat));
941   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(ZeroEltSplat)); // 0-splat is always single source
942   EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(ZeroEltSplat));
943   EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(ZeroEltSplat));
944 
945   Constant *Transpose = ConstantVector::get({C0, C4, C2, C6});
946   EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(Transpose));
947   EXPECT_FALSE(ShuffleVectorInst::isSelectMask(Transpose));
948   EXPECT_FALSE(ShuffleVectorInst::isReverseMask(Transpose));
949   EXPECT_FALSE(ShuffleVectorInst::isSingleSourceMask(Transpose));
950   EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(Transpose));
951   EXPECT_TRUE(ShuffleVectorInst::isTransposeMask(Transpose));
952 
953   // More tests to make sure the logic is/stays correct...
954   EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(ConstantVector::get({CU, C1, CU, C3})));
955   EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(ConstantVector::get({C4, CU, C6, CU})));
956 
957   EXPECT_TRUE(ShuffleVectorInst::isSelectMask(ConstantVector::get({C4, C1, C6, CU})));
958   EXPECT_TRUE(ShuffleVectorInst::isSelectMask(ConstantVector::get({CU, C1, C6, C3})));
959 
960   EXPECT_TRUE(ShuffleVectorInst::isReverseMask(ConstantVector::get({C7, C6, CU, C4})));
961   EXPECT_TRUE(ShuffleVectorInst::isReverseMask(ConstantVector::get({C3, CU, C1, CU})));
962 
963   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(ConstantVector::get({C7, C5, CU, C7})));
964   EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(ConstantVector::get({C3, C0, CU, C3})));
965 
966   EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(ConstantVector::get({C4, CU, CU, C4})));
967   EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(ConstantVector::get({CU, C0, CU, C0})));
968 
969   EXPECT_TRUE(ShuffleVectorInst::isTransposeMask(ConstantVector::get({C1, C5, C3, C7})));
970   EXPECT_TRUE(ShuffleVectorInst::isTransposeMask(ConstantVector::get({C1, C3})));
971 
972   // Nothing special about the values here - just re-using inputs to reduce code.
973   Constant *V0 = ConstantVector::get({C0, C1, C2, C3});
974   Constant *V1 = ConstantVector::get({C3, C2, C1, C0});
975 
976   // Identity with undef elts.
977   ShuffleVectorInst *Id1 = new ShuffleVectorInst(V0, V1,
978                                                  ConstantVector::get({C0, C1, CU, CU}));
979   EXPECT_TRUE(Id1->isIdentity());
980   EXPECT_FALSE(Id1->isIdentityWithPadding());
981   EXPECT_FALSE(Id1->isIdentityWithExtract());
982   EXPECT_FALSE(Id1->isConcat());
983   delete Id1;
984 
985   // Result has less elements than operands.
986   ShuffleVectorInst *Id2 = new ShuffleVectorInst(V0, V1,
987                                                  ConstantVector::get({C0, C1, C2}));
988   EXPECT_FALSE(Id2->isIdentity());
989   EXPECT_FALSE(Id2->isIdentityWithPadding());
990   EXPECT_TRUE(Id2->isIdentityWithExtract());
991   EXPECT_FALSE(Id2->isConcat());
992   delete Id2;
993 
994   // Result has less elements than operands; choose from Op1.
995   ShuffleVectorInst *Id3 = new ShuffleVectorInst(V0, V1,
996                                                  ConstantVector::get({C4, CU, C6}));
997   EXPECT_FALSE(Id3->isIdentity());
998   EXPECT_FALSE(Id3->isIdentityWithPadding());
999   EXPECT_TRUE(Id3->isIdentityWithExtract());
1000   EXPECT_FALSE(Id3->isConcat());
1001   delete Id3;
1002 
1003   // Result has less elements than operands; choose from Op0 and Op1 is not identity.
1004   ShuffleVectorInst *Id4 = new ShuffleVectorInst(V0, V1,
1005                                                  ConstantVector::get({C4, C1, C6}));
1006   EXPECT_FALSE(Id4->isIdentity());
1007   EXPECT_FALSE(Id4->isIdentityWithPadding());
1008   EXPECT_FALSE(Id4->isIdentityWithExtract());
1009   EXPECT_FALSE(Id4->isConcat());
1010   delete Id4;
1011 
1012   // Result has more elements than operands, and extra elements are undef.
1013   ShuffleVectorInst *Id5 = new ShuffleVectorInst(V0, V1,
1014                                                  ConstantVector::get({CU, C1, C2, C3, CU, CU}));
1015   EXPECT_FALSE(Id5->isIdentity());
1016   EXPECT_TRUE(Id5->isIdentityWithPadding());
1017   EXPECT_FALSE(Id5->isIdentityWithExtract());
1018   EXPECT_FALSE(Id5->isConcat());
1019   delete Id5;
1020 
1021   // Result has more elements than operands, and extra elements are undef; choose from Op1.
1022   ShuffleVectorInst *Id6 = new ShuffleVectorInst(V0, V1,
1023                                                  ConstantVector::get({C4, C5, C6, CU, CU, CU}));
1024   EXPECT_FALSE(Id6->isIdentity());
1025   EXPECT_TRUE(Id6->isIdentityWithPadding());
1026   EXPECT_FALSE(Id6->isIdentityWithExtract());
1027   EXPECT_FALSE(Id6->isConcat());
1028   delete Id6;
1029 
1030   // Result has more elements than operands, but extra elements are not undef.
1031   ShuffleVectorInst *Id7 = new ShuffleVectorInst(V0, V1,
1032                                                  ConstantVector::get({C0, C1, C2, C3, CU, C1}));
1033   EXPECT_FALSE(Id7->isIdentity());
1034   EXPECT_FALSE(Id7->isIdentityWithPadding());
1035   EXPECT_FALSE(Id7->isIdentityWithExtract());
1036   EXPECT_FALSE(Id7->isConcat());
1037   delete Id7;
1038 
1039   // Result has more elements than operands; choose from Op0 and Op1 is not identity.
1040   ShuffleVectorInst *Id8 = new ShuffleVectorInst(V0, V1,
1041                                                  ConstantVector::get({C4, CU, C2, C3, CU, CU}));
1042   EXPECT_FALSE(Id8->isIdentity());
1043   EXPECT_FALSE(Id8->isIdentityWithPadding());
1044   EXPECT_FALSE(Id8->isIdentityWithExtract());
1045   EXPECT_FALSE(Id8->isConcat());
1046   delete Id8;
1047 
1048   // Result has twice as many elements as operands; choose consecutively from Op0 and Op1 is concat.
1049   ShuffleVectorInst *Id9 = new ShuffleVectorInst(V0, V1,
1050                                                  ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7}));
1051   EXPECT_FALSE(Id9->isIdentity());
1052   EXPECT_FALSE(Id9->isIdentityWithPadding());
1053   EXPECT_FALSE(Id9->isIdentityWithExtract());
1054   EXPECT_TRUE(Id9->isConcat());
1055   delete Id9;
1056 
1057   // Result has less than twice as many elements as operands, so not a concat.
1058   ShuffleVectorInst *Id10 = new ShuffleVectorInst(V0, V1,
1059                                                   ConstantVector::get({C0, CU, C2, C3, CU, CU, C6}));
1060   EXPECT_FALSE(Id10->isIdentity());
1061   EXPECT_FALSE(Id10->isIdentityWithPadding());
1062   EXPECT_FALSE(Id10->isIdentityWithExtract());
1063   EXPECT_FALSE(Id10->isConcat());
1064   delete Id10;
1065 
1066   // Result has more than twice as many elements as operands, so not a concat.
1067   ShuffleVectorInst *Id11 = new ShuffleVectorInst(V0, V1,
1068                                                   ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7, CU}));
1069   EXPECT_FALSE(Id11->isIdentity());
1070   EXPECT_FALSE(Id11->isIdentityWithPadding());
1071   EXPECT_FALSE(Id11->isIdentityWithExtract());
1072   EXPECT_FALSE(Id11->isConcat());
1073   delete Id11;
1074 
1075   // If an input is undef, it's not a concat.
1076   // TODO: IdentityWithPadding should be true here even though the high mask values are not undef.
1077   ShuffleVectorInst *Id12 = new ShuffleVectorInst(V0, ConstantVector::get({CU, CU, CU, CU}),
1078                                                   ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7}));
1079   EXPECT_FALSE(Id12->isIdentity());
1080   EXPECT_FALSE(Id12->isIdentityWithPadding());
1081   EXPECT_FALSE(Id12->isIdentityWithExtract());
1082   EXPECT_FALSE(Id12->isConcat());
1083   delete Id12;
1084 
1085   // Not possible to express shuffle mask for scalable vector for extract
1086   // subvector.
1087   Type *VScaleV4Int32Ty = ScalableVectorType::get(Int32Ty, 4);
1088   ShuffleVectorInst *Id13 =
1089       new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV4Int32Ty),
1090                             UndefValue::get(VScaleV4Int32Ty),
1091                             Constant::getNullValue(VScaleV4Int32Ty));
1092   int Index = 0;
1093   EXPECT_FALSE(Id13->isExtractSubvectorMask(Index));
1094   EXPECT_FALSE(Id13->changesLength());
1095   EXPECT_FALSE(Id13->increasesLength());
1096   delete Id13;
1097 
1098   // Result has twice as many operands.
1099   Type *VScaleV2Int32Ty = ScalableVectorType::get(Int32Ty, 2);
1100   ShuffleVectorInst *Id14 =
1101       new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV2Int32Ty),
1102                             UndefValue::get(VScaleV2Int32Ty),
1103                             Constant::getNullValue(VScaleV4Int32Ty));
1104   EXPECT_TRUE(Id14->changesLength());
1105   EXPECT_TRUE(Id14->increasesLength());
1106   delete Id14;
1107 
1108   // Not possible to express these masks for scalable vectors, make sure we
1109   // don't crash.
1110   ShuffleVectorInst *Id15 =
1111       new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV2Int32Ty),
1112                             Constant::getNullValue(VScaleV2Int32Ty),
1113                             Constant::getNullValue(VScaleV2Int32Ty));
1114   EXPECT_FALSE(Id15->isIdentityWithPadding());
1115   EXPECT_FALSE(Id15->isIdentityWithExtract());
1116   EXPECT_FALSE(Id15->isConcat());
1117   delete Id15;
1118 }
1119 
1120 TEST(InstructionsTest, ShuffleMaskIsReplicationMask) {
1121   for (int ReplicationFactor : seq_inclusive(1, 8)) {
1122     for (int VF : seq_inclusive(1, 8)) {
1123       const auto ReplicatedMask = createReplicatedMask(ReplicationFactor, VF);
1124       int GuessedReplicationFactor = -1, GuessedVF = -1;
1125       EXPECT_TRUE(ShuffleVectorInst::isReplicationMask(
1126           ReplicatedMask, GuessedReplicationFactor, GuessedVF));
1127       EXPECT_EQ(GuessedReplicationFactor, ReplicationFactor);
1128       EXPECT_EQ(GuessedVF, VF);
1129 
1130       for (int OpVF : seq_inclusive(VF, 2 * VF + 1)) {
1131         LLVMContext Ctx;
1132         Type *OpVFTy = FixedVectorType::get(IntegerType::getInt1Ty(Ctx), OpVF);
1133         Value *Op = ConstantVector::getNullValue(OpVFTy);
1134         ShuffleVectorInst *SVI = new ShuffleVectorInst(Op, Op, ReplicatedMask);
1135         EXPECT_EQ(SVI->isReplicationMask(GuessedReplicationFactor, GuessedVF),
1136                   OpVF == VF);
1137         delete SVI;
1138       }
1139     }
1140   }
1141 }
1142 
1143 TEST(InstructionsTest, ShuffleMaskIsReplicationMask_undef) {
1144   for (int ReplicationFactor : seq_inclusive(1, 4)) {
1145     for (int VF : seq_inclusive(1, 4)) {
1146       const auto ReplicatedMask = createReplicatedMask(ReplicationFactor, VF);
1147       int GuessedReplicationFactor = -1, GuessedVF = -1;
1148 
1149       // If we change some mask elements to undef, we should still match.
1150 
1151       SmallVector<SmallVector<bool>> ElementChoices(ReplicatedMask.size(),
1152                                                     {false, true});
1153 
1154       CombinationGenerator<bool, decltype(ElementChoices)::value_type,
1155                            /*variable_smallsize=*/4>
1156           G(ElementChoices);
1157 
1158       G.generate([&](ArrayRef<bool> UndefOverrides) -> bool {
1159         SmallVector<int> AdjustedMask;
1160         AdjustedMask.reserve(ReplicatedMask.size());
1161         for (auto I : zip(ReplicatedMask, UndefOverrides))
1162           AdjustedMask.emplace_back(std::get<1>(I) ? -1 : std::get<0>(I));
1163         assert(AdjustedMask.size() == ReplicatedMask.size() &&
1164                "Size misprediction");
1165 
1166         EXPECT_TRUE(ShuffleVectorInst::isReplicationMask(
1167             AdjustedMask, GuessedReplicationFactor, GuessedVF));
1168         // Do not check GuessedReplicationFactor and GuessedVF,
1169         // with enough undef's we may deduce a different tuple.
1170 
1171         return /*Abort=*/false;
1172       });
1173     }
1174   }
1175 }
1176 
1177 TEST(InstructionsTest, ShuffleMaskIsReplicationMask_Exhaustive_Correctness) {
1178   for (int ShufMaskNumElts : seq_inclusive(1, 6)) {
1179     SmallVector<int> PossibleShufMaskElts;
1180     PossibleShufMaskElts.reserve(ShufMaskNumElts + 2);
1181     for (int PossibleShufMaskElt : seq_inclusive(-1, ShufMaskNumElts))
1182       PossibleShufMaskElts.emplace_back(PossibleShufMaskElt);
1183     assert(PossibleShufMaskElts.size() == ShufMaskNumElts + 2U &&
1184            "Size misprediction");
1185 
1186     SmallVector<SmallVector<int>> ElementChoices(ShufMaskNumElts,
1187                                                  PossibleShufMaskElts);
1188 
1189     CombinationGenerator<int, decltype(ElementChoices)::value_type,
1190                          /*variable_smallsize=*/4>
1191         G(ElementChoices);
1192 
1193     G.generate([&](ArrayRef<int> Mask) -> bool {
1194       int GuessedReplicationFactor = -1, GuessedVF = -1;
1195       bool Match = ShuffleVectorInst::isReplicationMask(
1196           Mask, GuessedReplicationFactor, GuessedVF);
1197       if (!Match)
1198         return /*Abort=*/false;
1199 
1200       const auto ActualMask =
1201           createReplicatedMask(GuessedReplicationFactor, GuessedVF);
1202       EXPECT_EQ(Mask.size(), ActualMask.size());
1203       for (auto I : zip(Mask, ActualMask)) {
1204         int Elt = std::get<0>(I);
1205         int ActualElt = std::get<0>(I);
1206 
1207         if (Elt != -1) {
1208           EXPECT_EQ(Elt, ActualElt);
1209         }
1210       }
1211 
1212       return /*Abort=*/false;
1213     });
1214   }
1215 }
1216 
1217 TEST(InstructionsTest, GetSplat) {
1218   // Create the elements for various constant vectors.
1219   LLVMContext Ctx;
1220   Type *Int32Ty = Type::getInt32Ty(Ctx);
1221   Constant *CU = UndefValue::get(Int32Ty);
1222   Constant *C0 = ConstantInt::get(Int32Ty, 0);
1223   Constant *C1 = ConstantInt::get(Int32Ty, 1);
1224 
1225   Constant *Splat0 = ConstantVector::get({C0, C0, C0, C0});
1226   Constant *Splat1 = ConstantVector::get({C1, C1, C1, C1 ,C1});
1227   Constant *Splat0Undef = ConstantVector::get({C0, CU, C0, CU});
1228   Constant *Splat1Undef = ConstantVector::get({CU, CU, C1, CU});
1229   Constant *NotSplat = ConstantVector::get({C1, C1, C0, C1 ,C1});
1230   Constant *NotSplatUndef = ConstantVector::get({CU, C1, CU, CU ,C0});
1231 
1232   // Default - undefs are not allowed.
1233   EXPECT_EQ(Splat0->getSplatValue(), C0);
1234   EXPECT_EQ(Splat1->getSplatValue(), C1);
1235   EXPECT_EQ(Splat0Undef->getSplatValue(), nullptr);
1236   EXPECT_EQ(Splat1Undef->getSplatValue(), nullptr);
1237   EXPECT_EQ(NotSplat->getSplatValue(), nullptr);
1238   EXPECT_EQ(NotSplatUndef->getSplatValue(), nullptr);
1239 
1240   // Disallow undefs explicitly.
1241   EXPECT_EQ(Splat0->getSplatValue(false), C0);
1242   EXPECT_EQ(Splat1->getSplatValue(false), C1);
1243   EXPECT_EQ(Splat0Undef->getSplatValue(false), nullptr);
1244   EXPECT_EQ(Splat1Undef->getSplatValue(false), nullptr);
1245   EXPECT_EQ(NotSplat->getSplatValue(false), nullptr);
1246   EXPECT_EQ(NotSplatUndef->getSplatValue(false), nullptr);
1247 
1248   // Allow undefs.
1249   EXPECT_EQ(Splat0->getSplatValue(true), C0);
1250   EXPECT_EQ(Splat1->getSplatValue(true), C1);
1251   EXPECT_EQ(Splat0Undef->getSplatValue(true), C0);
1252   EXPECT_EQ(Splat1Undef->getSplatValue(true), C1);
1253   EXPECT_EQ(NotSplat->getSplatValue(true), nullptr);
1254   EXPECT_EQ(NotSplatUndef->getSplatValue(true), nullptr);
1255 }
1256 
1257 TEST(InstructionsTest, SkipDebug) {
1258   LLVMContext C;
1259   std::unique_ptr<Module> M = parseIR(C,
1260                                       R"(
1261       declare void @llvm.dbg.value(metadata, metadata, metadata)
1262 
1263       define void @f() {
1264       entry:
1265         call void @llvm.dbg.value(metadata i32 0, metadata !11, metadata !DIExpression()), !dbg !13
1266         ret void
1267       }
1268 
1269       !llvm.dbg.cu = !{!0}
1270       !llvm.module.flags = !{!3, !4}
1271       !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
1272       !1 = !DIFile(filename: "t2.c", directory: "foo")
1273       !2 = !{}
1274       !3 = !{i32 2, !"Dwarf Version", i32 4}
1275       !4 = !{i32 2, !"Debug Info Version", i32 3}
1276       !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2)
1277       !9 = !DISubroutineType(types: !10)
1278       !10 = !{null}
1279       !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12)
1280       !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
1281       !13 = !DILocation(line: 2, column: 7, scope: !8)
1282   )");
1283   ASSERT_TRUE(M);
1284   Function *F = cast<Function>(M->getNamedValue("f"));
1285   BasicBlock &BB = F->front();
1286 
1287   // The first non-debug instruction is the terminator.
1288   auto *Term = BB.getTerminator();
1289   EXPECT_EQ(Term, BB.begin()->getNextNonDebugInstruction());
1290   EXPECT_EQ(Term->getIterator(), skipDebugIntrinsics(BB.begin()));
1291 
1292   // After the terminator, there are no non-debug instructions.
1293   EXPECT_EQ(nullptr, Term->getNextNonDebugInstruction());
1294 }
1295 
1296 TEST(InstructionsTest, PhiMightNotBeFPMathOperator) {
1297   LLVMContext Context;
1298   IRBuilder<> Builder(Context);
1299   MDBuilder MDHelper(Context);
1300   Instruction *I = Builder.CreatePHI(Builder.getInt32Ty(), 0);
1301   EXPECT_FALSE(isa<FPMathOperator>(I));
1302   I->deleteValue();
1303   Instruction *FP = Builder.CreatePHI(Builder.getDoubleTy(), 0);
1304   EXPECT_TRUE(isa<FPMathOperator>(FP));
1305   FP->deleteValue();
1306 }
1307 
1308 TEST(InstructionsTest, FPCallIsFPMathOperator) {
1309   LLVMContext C;
1310 
1311   Type *ITy = Type::getInt32Ty(C);
1312   FunctionType *IFnTy = FunctionType::get(ITy, {});
1313   Value *ICallee = Constant::getNullValue(IFnTy->getPointerTo());
1314   std::unique_ptr<CallInst> ICall(CallInst::Create(IFnTy, ICallee, {}, ""));
1315   EXPECT_FALSE(isa<FPMathOperator>(ICall));
1316 
1317   Type *VITy = FixedVectorType::get(ITy, 2);
1318   FunctionType *VIFnTy = FunctionType::get(VITy, {});
1319   Value *VICallee = Constant::getNullValue(VIFnTy->getPointerTo());
1320   std::unique_ptr<CallInst> VICall(CallInst::Create(VIFnTy, VICallee, {}, ""));
1321   EXPECT_FALSE(isa<FPMathOperator>(VICall));
1322 
1323   Type *AITy = ArrayType::get(ITy, 2);
1324   FunctionType *AIFnTy = FunctionType::get(AITy, {});
1325   Value *AICallee = Constant::getNullValue(AIFnTy->getPointerTo());
1326   std::unique_ptr<CallInst> AICall(CallInst::Create(AIFnTy, AICallee, {}, ""));
1327   EXPECT_FALSE(isa<FPMathOperator>(AICall));
1328 
1329   Type *FTy = Type::getFloatTy(C);
1330   FunctionType *FFnTy = FunctionType::get(FTy, {});
1331   Value *FCallee = Constant::getNullValue(FFnTy->getPointerTo());
1332   std::unique_ptr<CallInst> FCall(CallInst::Create(FFnTy, FCallee, {}, ""));
1333   EXPECT_TRUE(isa<FPMathOperator>(FCall));
1334 
1335   Type *VFTy = FixedVectorType::get(FTy, 2);
1336   FunctionType *VFFnTy = FunctionType::get(VFTy, {});
1337   Value *VFCallee = Constant::getNullValue(VFFnTy->getPointerTo());
1338   std::unique_ptr<CallInst> VFCall(CallInst::Create(VFFnTy, VFCallee, {}, ""));
1339   EXPECT_TRUE(isa<FPMathOperator>(VFCall));
1340 
1341   Type *AFTy = ArrayType::get(FTy, 2);
1342   FunctionType *AFFnTy = FunctionType::get(AFTy, {});
1343   Value *AFCallee = Constant::getNullValue(AFFnTy->getPointerTo());
1344   std::unique_ptr<CallInst> AFCall(CallInst::Create(AFFnTy, AFCallee, {}, ""));
1345   EXPECT_TRUE(isa<FPMathOperator>(AFCall));
1346 
1347   Type *AVFTy = ArrayType::get(VFTy, 2);
1348   FunctionType *AVFFnTy = FunctionType::get(AVFTy, {});
1349   Value *AVFCallee = Constant::getNullValue(AVFFnTy->getPointerTo());
1350   std::unique_ptr<CallInst> AVFCall(
1351       CallInst::Create(AVFFnTy, AVFCallee, {}, ""));
1352   EXPECT_TRUE(isa<FPMathOperator>(AVFCall));
1353 
1354   Type *AAVFTy = ArrayType::get(AVFTy, 2);
1355   FunctionType *AAVFFnTy = FunctionType::get(AAVFTy, {});
1356   Value *AAVFCallee = Constant::getNullValue(AAVFFnTy->getPointerTo());
1357   std::unique_ptr<CallInst> AAVFCall(
1358       CallInst::Create(AAVFFnTy, AAVFCallee, {}, ""));
1359   EXPECT_TRUE(isa<FPMathOperator>(AAVFCall));
1360 }
1361 
1362 TEST(InstructionsTest, FNegInstruction) {
1363   LLVMContext Context;
1364   Type *FltTy = Type::getFloatTy(Context);
1365   Constant *One = ConstantFP::get(FltTy, 1.0);
1366   BinaryOperator *FAdd = BinaryOperator::CreateFAdd(One, One);
1367   FAdd->setHasNoNaNs(true);
1368   UnaryOperator *FNeg = UnaryOperator::CreateFNegFMF(One, FAdd);
1369   EXPECT_TRUE(FNeg->hasNoNaNs());
1370   EXPECT_FALSE(FNeg->hasNoInfs());
1371   EXPECT_FALSE(FNeg->hasNoSignedZeros());
1372   EXPECT_FALSE(FNeg->hasAllowReciprocal());
1373   EXPECT_FALSE(FNeg->hasAllowContract());
1374   EXPECT_FALSE(FNeg->hasAllowReassoc());
1375   EXPECT_FALSE(FNeg->hasApproxFunc());
1376   FAdd->deleteValue();
1377   FNeg->deleteValue();
1378 }
1379 
1380 TEST(InstructionsTest, CallBrInstruction) {
1381   LLVMContext Context;
1382   std::unique_ptr<Module> M = parseIR(Context, R"(
1383 define void @foo() {
1384 entry:
1385   callbr void asm sideeffect "// XXX: ${0:l}", "X"(i8* blockaddress(@foo, %branch_test.exit))
1386           to label %land.rhs.i [label %branch_test.exit]
1387 
1388 land.rhs.i:
1389   br label %branch_test.exit
1390 
1391 branch_test.exit:
1392   %0 = phi i1 [ true, %entry ], [ false, %land.rhs.i ]
1393   br i1 %0, label %if.end, label %if.then
1394 
1395 if.then:
1396   ret void
1397 
1398 if.end:
1399   ret void
1400 }
1401 )");
1402   Function *Foo = M->getFunction("foo");
1403   auto BBs = Foo->getBasicBlockList().begin();
1404   CallBrInst &CBI = cast<CallBrInst>(BBs->front());
1405   ++BBs;
1406   ++BBs;
1407   BasicBlock &BranchTestExit = *BBs;
1408   ++BBs;
1409   BasicBlock &IfThen = *BBs;
1410 
1411   // Test that setting the first indirect destination of callbr updates the dest
1412   EXPECT_EQ(&BranchTestExit, CBI.getIndirectDest(0));
1413   CBI.setIndirectDest(0, &IfThen);
1414   EXPECT_EQ(&IfThen, CBI.getIndirectDest(0));
1415 
1416   // Further, test that changing the indirect destination updates the arg
1417   // operand to use the block address of the new indirect destination basic
1418   // block. This is a critical invariant of CallBrInst.
1419   BlockAddress *IndirectBA = BlockAddress::get(CBI.getIndirectDest(0));
1420   BlockAddress *ArgBA = cast<BlockAddress>(CBI.getArgOperand(0));
1421   EXPECT_EQ(IndirectBA, ArgBA)
1422       << "After setting the indirect destination, callbr had an indirect "
1423          "destination of '"
1424       << CBI.getIndirectDest(0)->getName() << "', but a argument of '"
1425       << ArgBA->getBasicBlock()->getName() << "'. These should always match:\n"
1426       << CBI;
1427   EXPECT_EQ(IndirectBA->getBasicBlock(), &IfThen);
1428   EXPECT_EQ(ArgBA->getBasicBlock(), &IfThen);
1429 }
1430 
1431 TEST(InstructionsTest, UnaryOperator) {
1432   LLVMContext Context;
1433   IRBuilder<> Builder(Context);
1434   Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
1435   Value *F = Builder.CreateFNeg(I);
1436 
1437   EXPECT_TRUE(isa<Value>(F));
1438   EXPECT_TRUE(isa<Instruction>(F));
1439   EXPECT_TRUE(isa<UnaryInstruction>(F));
1440   EXPECT_TRUE(isa<UnaryOperator>(F));
1441   EXPECT_FALSE(isa<BinaryOperator>(F));
1442 
1443   F->deleteValue();
1444   I->deleteValue();
1445 }
1446 
1447 TEST(InstructionsTest, DropLocation) {
1448   LLVMContext C;
1449   std::unique_ptr<Module> M = parseIR(C,
1450                                       R"(
1451       declare void @callee()
1452 
1453       define void @no_parent_scope() {
1454         call void @callee()           ; I1: Call with no location.
1455         call void @callee(), !dbg !11 ; I2: Call with location.
1456         ret void, !dbg !11            ; I3: Non-call with location.
1457       }
1458 
1459       define void @with_parent_scope() !dbg !8 {
1460         call void @callee()           ; I1: Call with no location.
1461         call void @callee(), !dbg !11 ; I2: Call with location.
1462         ret void, !dbg !11            ; I3: Non-call with location.
1463       }
1464 
1465       !llvm.dbg.cu = !{!0}
1466       !llvm.module.flags = !{!3, !4}
1467       !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
1468       !1 = !DIFile(filename: "t2.c", directory: "foo")
1469       !2 = !{}
1470       !3 = !{i32 2, !"Dwarf Version", i32 4}
1471       !4 = !{i32 2, !"Debug Info Version", i32 3}
1472       !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2)
1473       !9 = !DISubroutineType(types: !10)
1474       !10 = !{null}
1475       !11 = !DILocation(line: 2, column: 7, scope: !8, inlinedAt: !12)
1476       !12 = !DILocation(line: 3, column: 8, scope: !8)
1477   )");
1478   ASSERT_TRUE(M);
1479 
1480   {
1481     Function *NoParentScopeF =
1482         cast<Function>(M->getNamedValue("no_parent_scope"));
1483     BasicBlock &BB = NoParentScopeF->front();
1484 
1485     auto *I1 = BB.getFirstNonPHI();
1486     auto *I2 = I1->getNextNode();
1487     auto *I3 = BB.getTerminator();
1488 
1489     EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1490     I1->dropLocation();
1491     EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1492 
1493     EXPECT_EQ(I2->getDebugLoc().getLine(), 2U);
1494     I2->dropLocation();
1495     EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1496 
1497     EXPECT_EQ(I3->getDebugLoc().getLine(), 2U);
1498     I3->dropLocation();
1499     EXPECT_EQ(I3->getDebugLoc(), DebugLoc());
1500   }
1501 
1502   {
1503     Function *WithParentScopeF =
1504         cast<Function>(M->getNamedValue("with_parent_scope"));
1505     BasicBlock &BB = WithParentScopeF->front();
1506 
1507     auto *I2 = BB.getFirstNonPHI()->getNextNode();
1508 
1509     MDNode *Scope = cast<MDNode>(WithParentScopeF->getSubprogram());
1510     EXPECT_EQ(I2->getDebugLoc().getLine(), 2U);
1511     I2->dropLocation();
1512     EXPECT_EQ(I2->getDebugLoc().getLine(), 0U);
1513     EXPECT_EQ(I2->getDebugLoc().getScope(), Scope);
1514     EXPECT_EQ(I2->getDebugLoc().getInlinedAt(), nullptr);
1515   }
1516 }
1517 
1518 TEST(InstructionsTest, BranchWeightOverflow) {
1519   LLVMContext C;
1520   std::unique_ptr<Module> M = parseIR(C,
1521                                       R"(
1522       declare void @callee()
1523 
1524       define void @caller() {
1525         call void @callee(), !prof !1
1526         ret void
1527       }
1528 
1529       !1 = !{!"branch_weights", i32 20000}
1530   )");
1531   ASSERT_TRUE(M);
1532   CallInst *CI =
1533       cast<CallInst>(&M->getFunction("caller")->getEntryBlock().front());
1534   uint64_t ProfWeight;
1535   CI->extractProfTotalWeight(ProfWeight);
1536   ASSERT_EQ(ProfWeight, 20000U);
1537   CI->updateProfWeight(10000000, 1);
1538   CI->extractProfTotalWeight(ProfWeight);
1539   ASSERT_EQ(ProfWeight, UINT32_MAX);
1540 }
1541 
1542 TEST(InstructionsTest, AllocaInst) {
1543   LLVMContext Ctx;
1544   std::unique_ptr<Module> M = parseIR(Ctx, R"(
1545       %T = type { i64, [3 x i32]}
1546       define void @f(i32 %n) {
1547       entry:
1548         %A = alloca i32, i32 1
1549         %B = alloca i32, i32 4
1550         %C = alloca i32, i32 %n
1551         %D = alloca <8 x double>
1552         %E = alloca <vscale x 8 x double>
1553         %F = alloca [2 x half]
1554         %G = alloca [2 x [3 x i128]]
1555         %H = alloca %T
1556         ret void
1557       }
1558     )");
1559   const DataLayout &DL = M->getDataLayout();
1560   ASSERT_TRUE(M);
1561   Function *Fun = cast<Function>(M->getNamedValue("f"));
1562   BasicBlock &BB = Fun->front();
1563   auto It = BB.begin();
1564   AllocaInst &A = cast<AllocaInst>(*It++);
1565   AllocaInst &B = cast<AllocaInst>(*It++);
1566   AllocaInst &C = cast<AllocaInst>(*It++);
1567   AllocaInst &D = cast<AllocaInst>(*It++);
1568   AllocaInst &E = cast<AllocaInst>(*It++);
1569   AllocaInst &F = cast<AllocaInst>(*It++);
1570   AllocaInst &G = cast<AllocaInst>(*It++);
1571   AllocaInst &H = cast<AllocaInst>(*It++);
1572   EXPECT_EQ(A.getAllocationSizeInBits(DL), TypeSize::getFixed(32));
1573   EXPECT_EQ(B.getAllocationSizeInBits(DL), TypeSize::getFixed(128));
1574   EXPECT_FALSE(C.getAllocationSizeInBits(DL));
1575   EXPECT_EQ(D.getAllocationSizeInBits(DL), TypeSize::getFixed(512));
1576   EXPECT_EQ(E.getAllocationSizeInBits(DL), TypeSize::getScalable(512));
1577   EXPECT_EQ(F.getAllocationSizeInBits(DL), TypeSize::getFixed(32));
1578   EXPECT_EQ(G.getAllocationSizeInBits(DL), TypeSize::getFixed(768));
1579   EXPECT_EQ(H.getAllocationSizeInBits(DL), TypeSize::getFixed(160));
1580 }
1581 
1582 } // end anonymous namespace
1583 } // end namespace llvm
1584