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