llvm-project

Форк
0
/
InstructionsTest.cpp 
1821 строка · 70.4 Кб
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/FPEnv.h"
21
#include "llvm/IR/Function.h"
22
#include "llvm/IR/IRBuilder.h"
23
#include "llvm/IR/LLVMContext.h"
24
#include "llvm/IR/MDBuilder.h"
25
#include "llvm/IR/Module.h"
26
#include "llvm/IR/NoFolder.h"
27
#include "llvm/IR/Operator.h"
28
#include "llvm/Support/CommandLine.h"
29
#include "llvm/Support/SourceMgr.h"
30
#include "llvm-c/Core.h"
31
#include "gmock/gmock-matchers.h"
32
#include "gtest/gtest.h"
33
#include <memory>
34

35
extern llvm::cl::opt<bool> UseNewDbgInfoFormat;
36

37
namespace llvm {
38
namespace {
39

40
static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
41
  SMDiagnostic Err;
42
  std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
43
  if (!Mod)
44
    Err.print("InstructionsTests", errs());
45
  return Mod;
46
}
47

48
TEST(InstructionsTest, ReturnInst) {
49
  LLVMContext C;
50

51
  // test for PR6589
52
  const ReturnInst* r0 = ReturnInst::Create(C);
53
  EXPECT_EQ(r0->getNumOperands(), 0U);
54
  EXPECT_EQ(r0->op_begin(), r0->op_end());
55

56
  IntegerType* Int1 = IntegerType::get(C, 1);
57
  Constant* One = ConstantInt::get(Int1, 1, true);
58
  const ReturnInst* r1 = ReturnInst::Create(C, One);
59
  EXPECT_EQ(1U, r1->getNumOperands());
60
  User::const_op_iterator b(r1->op_begin());
61
  EXPECT_NE(r1->op_end(), b);
62
  EXPECT_EQ(One, *b);
63
  EXPECT_EQ(One, r1->getOperand(0));
64
  ++b;
65
  EXPECT_EQ(r1->op_end(), b);
66

67
  // clean up
68
  delete r0;
69
  delete r1;
70
}
71

72
// Test fixture that provides a module and a single function within it. Useful
73
// for tests that need to refer to the function in some way.
74
class ModuleWithFunctionTest : public testing::Test {
75
protected:
76
  ModuleWithFunctionTest() : M(new Module("MyModule", Ctx)) {
77
    FArgTypes.push_back(Type::getInt8Ty(Ctx));
78
    FArgTypes.push_back(Type::getInt32Ty(Ctx));
79
    FArgTypes.push_back(Type::getInt64Ty(Ctx));
80
    FunctionType *FTy =
81
        FunctionType::get(Type::getVoidTy(Ctx), FArgTypes, false);
82
    F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
83
  }
84

85
  LLVMContext Ctx;
86
  std::unique_ptr<Module> M;
87
  SmallVector<Type *, 3> FArgTypes;
88
  Function *F;
89
};
90

91
TEST_F(ModuleWithFunctionTest, CallInst) {
92
  Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20),
93
                   ConstantInt::get(Type::getInt32Ty(Ctx), 9999),
94
                   ConstantInt::get(Type::getInt64Ty(Ctx), 42)};
95
  std::unique_ptr<CallInst> Call(CallInst::Create(F, Args));
96

97
  // Make sure iteration over a call's arguments works as expected.
98
  unsigned Idx = 0;
99
  for (Value *Arg : Call->args()) {
100
    EXPECT_EQ(FArgTypes[Idx], Arg->getType());
101
    EXPECT_EQ(Call->getArgOperand(Idx)->getType(), Arg->getType());
102
    Idx++;
103
  }
104

105
  Call->addRetAttr(Attribute::get(Call->getContext(), "test-str-attr"));
106
  EXPECT_TRUE(Call->hasRetAttr("test-str-attr"));
107
  EXPECT_FALSE(Call->hasRetAttr("not-on-call"));
108

109
  Call->addFnAttr(Attribute::get(Call->getContext(), "test-str-fn-attr"));
110
  ASSERT_TRUE(Call->hasFnAttr("test-str-fn-attr"));
111
  Call->removeFnAttr("test-str-fn-attr");
112
  EXPECT_FALSE(Call->hasFnAttr("test-str-fn-attr"));
113
}
114

115
TEST_F(ModuleWithFunctionTest, InvokeInst) {
116
  BasicBlock *BB1 = BasicBlock::Create(Ctx, "", F);
117
  BasicBlock *BB2 = BasicBlock::Create(Ctx, "", F);
118

119
  Value *Args[] = {ConstantInt::get(Type::getInt8Ty(Ctx), 20),
120
                   ConstantInt::get(Type::getInt32Ty(Ctx), 9999),
121
                   ConstantInt::get(Type::getInt64Ty(Ctx), 42)};
122
  std::unique_ptr<InvokeInst> Invoke(InvokeInst::Create(F, BB1, BB2, Args));
123

124
  // Make sure iteration over invoke's arguments works as expected.
125
  unsigned Idx = 0;
126
  for (Value *Arg : Invoke->args()) {
127
    EXPECT_EQ(FArgTypes[Idx], Arg->getType());
128
    EXPECT_EQ(Invoke->getArgOperand(Idx)->getType(), Arg->getType());
129
    Idx++;
130
  }
131
}
132

133
TEST(InstructionsTest, BranchInst) {
134
  LLVMContext C;
135

136
  // Make a BasicBlocks
137
  BasicBlock* bb0 = BasicBlock::Create(C);
138
  BasicBlock* bb1 = BasicBlock::Create(C);
139

140
  // Mandatory BranchInst
141
  const BranchInst* b0 = BranchInst::Create(bb0);
142

143
  EXPECT_TRUE(b0->isUnconditional());
144
  EXPECT_FALSE(b0->isConditional());
145
  EXPECT_EQ(1U, b0->getNumSuccessors());
146

147
  // check num operands
148
  EXPECT_EQ(1U, b0->getNumOperands());
149

150
  EXPECT_NE(b0->op_begin(), b0->op_end());
151
  EXPECT_EQ(b0->op_end(), std::next(b0->op_begin()));
152

153
  EXPECT_EQ(b0->op_end(), std::next(b0->op_begin()));
154

155
  IntegerType* Int1 = IntegerType::get(C, 1);
156
  Constant* One = ConstantInt::get(Int1, 1, true);
157

158
  // Conditional BranchInst
159
  BranchInst* b1 = BranchInst::Create(bb0, bb1, One);
160

161
  EXPECT_FALSE(b1->isUnconditional());
162
  EXPECT_TRUE(b1->isConditional());
163
  EXPECT_EQ(2U, b1->getNumSuccessors());
164

165
  // check num operands
166
  EXPECT_EQ(3U, b1->getNumOperands());
167

168
  User::const_op_iterator b(b1->op_begin());
169

170
  // check COND
171
  EXPECT_NE(b, b1->op_end());
172
  EXPECT_EQ(One, *b);
173
  EXPECT_EQ(One, b1->getOperand(0));
174
  EXPECT_EQ(One, b1->getCondition());
175
  ++b;
176

177
  // check ELSE
178
  EXPECT_EQ(bb1, *b);
179
  EXPECT_EQ(bb1, b1->getOperand(1));
180
  EXPECT_EQ(bb1, b1->getSuccessor(1));
181
  ++b;
182

183
  // check THEN
184
  EXPECT_EQ(bb0, *b);
185
  EXPECT_EQ(bb0, b1->getOperand(2));
186
  EXPECT_EQ(bb0, b1->getSuccessor(0));
187
  ++b;
188

189
  EXPECT_EQ(b1->op_end(), b);
190

191
  // clean up
192
  delete b0;
193
  delete b1;
194

195
  delete bb0;
196
  delete bb1;
197
}
198

199
TEST(InstructionsTest, CastInst) {
200
  LLVMContext C;
201

202
  Type *Int8Ty = Type::getInt8Ty(C);
203
  Type *Int16Ty = Type::getInt16Ty(C);
204
  Type *Int32Ty = Type::getInt32Ty(C);
205
  Type *Int64Ty = Type::getInt64Ty(C);
206
  Type *V8x8Ty = FixedVectorType::get(Int8Ty, 8);
207
  Type *V8x64Ty = FixedVectorType::get(Int64Ty, 8);
208
  Type *X86MMXTy = Type::getX86_MMXTy(C);
209

210
  Type *HalfTy = Type::getHalfTy(C);
211
  Type *FloatTy = Type::getFloatTy(C);
212
  Type *DoubleTy = Type::getDoubleTy(C);
213

214
  Type *V2Int32Ty = FixedVectorType::get(Int32Ty, 2);
215
  Type *V2Int64Ty = FixedVectorType::get(Int64Ty, 2);
216
  Type *V4Int16Ty = FixedVectorType::get(Int16Ty, 4);
217
  Type *V1Int16Ty = FixedVectorType::get(Int16Ty, 1);
218

219
  Type *VScaleV2Int32Ty = ScalableVectorType::get(Int32Ty, 2);
220
  Type *VScaleV2Int64Ty = ScalableVectorType::get(Int64Ty, 2);
221
  Type *VScaleV4Int16Ty = ScalableVectorType::get(Int16Ty, 4);
222
  Type *VScaleV1Int16Ty = ScalableVectorType::get(Int16Ty, 1);
223

224
  Type *Int32PtrTy = PointerType::get(Int32Ty, 0);
225
  Type *Int64PtrTy = PointerType::get(Int64Ty, 0);
226

227
  Type *Int32PtrAS1Ty = PointerType::get(Int32Ty, 1);
228
  Type *Int64PtrAS1Ty = PointerType::get(Int64Ty, 1);
229

230
  Type *V2Int32PtrAS1Ty = FixedVectorType::get(Int32PtrAS1Ty, 2);
231
  Type *V2Int64PtrAS1Ty = FixedVectorType::get(Int64PtrAS1Ty, 2);
232
  Type *V4Int32PtrAS1Ty = FixedVectorType::get(Int32PtrAS1Ty, 4);
233
  Type *VScaleV4Int32PtrAS1Ty = ScalableVectorType::get(Int32PtrAS1Ty, 4);
234
  Type *V4Int64PtrAS1Ty = FixedVectorType::get(Int64PtrAS1Ty, 4);
235

236
  Type *V2Int64PtrTy = FixedVectorType::get(Int64PtrTy, 2);
237
  Type *V2Int32PtrTy = FixedVectorType::get(Int32PtrTy, 2);
238
  Type *VScaleV2Int32PtrTy = ScalableVectorType::get(Int32PtrTy, 2);
239
  Type *V4Int32PtrTy = FixedVectorType::get(Int32PtrTy, 4);
240
  Type *VScaleV4Int32PtrTy = ScalableVectorType::get(Int32PtrTy, 4);
241
  Type *VScaleV4Int64PtrTy = ScalableVectorType::get(Int64PtrTy, 4);
242

243
  const Constant* c8 = Constant::getNullValue(V8x8Ty);
244
  const Constant* c64 = Constant::getNullValue(V8x64Ty);
245

246
  const Constant *v2ptr32 = Constant::getNullValue(V2Int32PtrTy);
247

248
  EXPECT_EQ(CastInst::Trunc, CastInst::getCastOpcode(c64, true, V8x8Ty, true));
249
  EXPECT_EQ(CastInst::SExt, CastInst::getCastOpcode(c8, true, V8x64Ty, true));
250

251
  EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, X86MMXTy));
252
  EXPECT_FALSE(CastInst::isBitCastable(X86MMXTy, V8x8Ty));
253
  EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, X86MMXTy));
254
  EXPECT_FALSE(CastInst::isBitCastable(V8x64Ty, V8x8Ty));
255
  EXPECT_FALSE(CastInst::isBitCastable(V8x8Ty, V8x64Ty));
256

257
  // Check address space casts are rejected since we don't know the sizes here
258
  EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, Int32PtrAS1Ty));
259
  EXPECT_FALSE(CastInst::isBitCastable(Int32PtrAS1Ty, Int32PtrTy));
260
  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, V2Int32PtrAS1Ty));
261
  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int32PtrTy));
262
  EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V2Int64PtrAS1Ty));
263
  EXPECT_EQ(CastInst::AddrSpaceCast, CastInst::getCastOpcode(v2ptr32, true,
264
                                                             V2Int32PtrAS1Ty,
265
                                                             true));
266

267
  // Test mismatched number of elements for pointers
268
  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int64PtrAS1Ty));
269
  EXPECT_FALSE(CastInst::isBitCastable(V4Int64PtrAS1Ty, V2Int32PtrAS1Ty));
270
  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrAS1Ty, V4Int32PtrAS1Ty));
271
  EXPECT_FALSE(CastInst::isBitCastable(Int32PtrTy, V2Int32PtrTy));
272
  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, Int32PtrTy));
273

274
  EXPECT_TRUE(CastInst::isBitCastable(Int32PtrTy, Int64PtrTy));
275
  EXPECT_FALSE(CastInst::isBitCastable(DoubleTy, FloatTy));
276
  EXPECT_FALSE(CastInst::isBitCastable(FloatTy, DoubleTy));
277
  EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy));
278
  EXPECT_TRUE(CastInst::isBitCastable(FloatTy, FloatTy));
279
  EXPECT_TRUE(CastInst::isBitCastable(FloatTy, Int32Ty));
280
  EXPECT_TRUE(CastInst::isBitCastable(Int16Ty, HalfTy));
281
  EXPECT_TRUE(CastInst::isBitCastable(Int32Ty, FloatTy));
282
  EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, Int64Ty));
283

284
  EXPECT_TRUE(CastInst::isBitCastable(V2Int32Ty, V4Int16Ty));
285
  EXPECT_FALSE(CastInst::isBitCastable(Int32Ty, Int64Ty));
286
  EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, Int32Ty));
287

288
  EXPECT_FALSE(CastInst::isBitCastable(V2Int32PtrTy, Int64Ty));
289
  EXPECT_FALSE(CastInst::isBitCastable(Int64Ty, V2Int32PtrTy));
290
  EXPECT_TRUE(CastInst::isBitCastable(V2Int64PtrTy, V2Int32PtrTy));
291
  EXPECT_TRUE(CastInst::isBitCastable(V2Int32PtrTy, V2Int64PtrTy));
292
  EXPECT_FALSE(CastInst::isBitCastable(V2Int32Ty, V2Int64Ty));
293
  EXPECT_FALSE(CastInst::isBitCastable(V2Int64Ty, V2Int32Ty));
294

295

296
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
297
                                     Constant::getNullValue(V4Int32PtrTy),
298
                                     V2Int32PtrTy));
299
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
300
                                     Constant::getNullValue(V2Int32PtrTy),
301
                                     V4Int32PtrTy));
302

303
  EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
304
                                     Constant::getNullValue(V4Int32PtrAS1Ty),
305
                                     V2Int32PtrTy));
306
  EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
307
                                     Constant::getNullValue(V2Int32PtrTy),
308
                                     V4Int32PtrAS1Ty));
309

310
  // Address space cast of fixed/scalable vectors of pointers to scalable/fixed
311
  // vector of pointers.
312
  EXPECT_FALSE(CastInst::castIsValid(
313
      Instruction::AddrSpaceCast, Constant::getNullValue(VScaleV4Int32PtrAS1Ty),
314
      V4Int32PtrTy));
315
  EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
316
                                     Constant::getNullValue(V4Int32PtrTy),
317
                                     VScaleV4Int32PtrAS1Ty));
318
  // Address space cast of scalable vectors of pointers to scalable vector of
319
  // pointers.
320
  EXPECT_FALSE(CastInst::castIsValid(
321
      Instruction::AddrSpaceCast, Constant::getNullValue(VScaleV4Int32PtrAS1Ty),
322
      VScaleV2Int32PtrTy));
323
  EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
324
                                     Constant::getNullValue(VScaleV2Int32PtrTy),
325
                                     VScaleV4Int32PtrAS1Ty));
326
  EXPECT_TRUE(CastInst::castIsValid(Instruction::AddrSpaceCast,
327
                                    Constant::getNullValue(VScaleV4Int64PtrTy),
328
                                    VScaleV4Int32PtrAS1Ty));
329
  // Same number of lanes, different address space.
330
  EXPECT_TRUE(CastInst::castIsValid(
331
      Instruction::AddrSpaceCast, Constant::getNullValue(VScaleV4Int32PtrAS1Ty),
332
      VScaleV4Int32PtrTy));
333
  // Same number of lanes, same address space.
334
  EXPECT_FALSE(CastInst::castIsValid(Instruction::AddrSpaceCast,
335
                                     Constant::getNullValue(VScaleV4Int64PtrTy),
336
                                     VScaleV4Int32PtrTy));
337

338
  // Bit casting fixed/scalable vector to scalable/fixed vectors.
339
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
340
                                     Constant::getNullValue(V2Int32Ty),
341
                                     VScaleV2Int32Ty));
342
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
343
                                     Constant::getNullValue(V2Int64Ty),
344
                                     VScaleV2Int64Ty));
345
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
346
                                     Constant::getNullValue(V4Int16Ty),
347
                                     VScaleV4Int16Ty));
348
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
349
                                     Constant::getNullValue(VScaleV2Int32Ty),
350
                                     V2Int32Ty));
351
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
352
                                     Constant::getNullValue(VScaleV2Int64Ty),
353
                                     V2Int64Ty));
354
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
355
                                     Constant::getNullValue(VScaleV4Int16Ty),
356
                                     V4Int16Ty));
357

358
  // Bit casting scalable vectors to scalable vectors.
359
  EXPECT_TRUE(CastInst::castIsValid(Instruction::BitCast,
360
                                    Constant::getNullValue(VScaleV4Int16Ty),
361
                                    VScaleV2Int32Ty));
362
  EXPECT_TRUE(CastInst::castIsValid(Instruction::BitCast,
363
                                    Constant::getNullValue(VScaleV2Int32Ty),
364
                                    VScaleV4Int16Ty));
365
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
366
                                     Constant::getNullValue(VScaleV2Int64Ty),
367
                                     VScaleV2Int32Ty));
368
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
369
                                     Constant::getNullValue(VScaleV2Int32Ty),
370
                                     VScaleV2Int64Ty));
371

372
  // Bitcasting to/from <vscale x 1 x Ty>
373
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
374
                                     Constant::getNullValue(VScaleV1Int16Ty),
375
                                     V1Int16Ty));
376
  EXPECT_FALSE(CastInst::castIsValid(Instruction::BitCast,
377
                                     Constant::getNullValue(V1Int16Ty),
378
                                     VScaleV1Int16Ty));
379

380
  // Check that assertion is not hit when creating a cast with a vector of
381
  // pointers
382
  // First form
383
  BasicBlock *BB = BasicBlock::Create(C);
384
  Constant *NullV2I32Ptr = Constant::getNullValue(V2Int32PtrTy);
385
  auto Inst1 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty, "foo", BB);
386

387
  Constant *NullVScaleV2I32Ptr = Constant::getNullValue(VScaleV2Int32PtrTy);
388
  auto Inst1VScale = CastInst::CreatePointerCast(
389
      NullVScaleV2I32Ptr, VScaleV2Int32Ty, "foo.vscale", BB);
390

391
  // Second form
392
  auto Inst2 = CastInst::CreatePointerCast(NullV2I32Ptr, V2Int32Ty);
393
  auto Inst2VScale =
394
      CastInst::CreatePointerCast(NullVScaleV2I32Ptr, VScaleV2Int32Ty);
395

396
  delete Inst2;
397
  delete Inst2VScale;
398
  Inst1->eraseFromParent();
399
  Inst1VScale->eraseFromParent();
400
  delete BB;
401
}
402

403
TEST(InstructionsTest, CastCAPI) {
404
  LLVMContext C;
405

406
  Type *Int8Ty = Type::getInt8Ty(C);
407
  Type *Int32Ty = Type::getInt32Ty(C);
408
  Type *Int64Ty = Type::getInt64Ty(C);
409

410
  Type *FloatTy = Type::getFloatTy(C);
411
  Type *DoubleTy = Type::getDoubleTy(C);
412

413
  Type *Int8PtrTy = PointerType::get(Int8Ty, 0);
414
  Type *Int32PtrTy = PointerType::get(Int32Ty, 0);
415

416
  const Constant *C8 = Constant::getNullValue(Int8Ty);
417
  const Constant *C64 = Constant::getNullValue(Int64Ty);
418

419
  EXPECT_EQ(LLVMBitCast,
420
            LLVMGetCastOpcode(wrap(C64), true, wrap(Int64Ty), true));
421
  EXPECT_EQ(LLVMTrunc, LLVMGetCastOpcode(wrap(C64), true, wrap(Int8Ty), true));
422
  EXPECT_EQ(LLVMSExt, LLVMGetCastOpcode(wrap(C8), true, wrap(Int64Ty), true));
423
  EXPECT_EQ(LLVMZExt, LLVMGetCastOpcode(wrap(C8), false, wrap(Int64Ty), true));
424

425
  const Constant *CF32 = Constant::getNullValue(FloatTy);
426
  const Constant *CF64 = Constant::getNullValue(DoubleTy);
427

428
  EXPECT_EQ(LLVMFPToUI,
429
            LLVMGetCastOpcode(wrap(CF32), true, wrap(Int8Ty), false));
430
  EXPECT_EQ(LLVMFPToSI,
431
            LLVMGetCastOpcode(wrap(CF32), true, wrap(Int8Ty), true));
432
  EXPECT_EQ(LLVMUIToFP,
433
            LLVMGetCastOpcode(wrap(C8), false, wrap(FloatTy), true));
434
  EXPECT_EQ(LLVMSIToFP, LLVMGetCastOpcode(wrap(C8), true, wrap(FloatTy), true));
435
  EXPECT_EQ(LLVMFPTrunc,
436
            LLVMGetCastOpcode(wrap(CF64), true, wrap(FloatTy), true));
437
  EXPECT_EQ(LLVMFPExt,
438
            LLVMGetCastOpcode(wrap(CF32), true, wrap(DoubleTy), true));
439

440
  const Constant *CPtr8 = Constant::getNullValue(Int8PtrTy);
441

442
  EXPECT_EQ(LLVMPtrToInt,
443
            LLVMGetCastOpcode(wrap(CPtr8), true, wrap(Int8Ty), true));
444
  EXPECT_EQ(LLVMIntToPtr,
445
            LLVMGetCastOpcode(wrap(C8), true, wrap(Int8PtrTy), true));
446

447
  Type *V8x8Ty = FixedVectorType::get(Int8Ty, 8);
448
  Type *V8x64Ty = FixedVectorType::get(Int64Ty, 8);
449
  const Constant *CV8 = Constant::getNullValue(V8x8Ty);
450
  const Constant *CV64 = Constant::getNullValue(V8x64Ty);
451

452
  EXPECT_EQ(LLVMTrunc, LLVMGetCastOpcode(wrap(CV64), true, wrap(V8x8Ty), true));
453
  EXPECT_EQ(LLVMSExt, LLVMGetCastOpcode(wrap(CV8), true, wrap(V8x64Ty), true));
454

455
  Type *Int32PtrAS1Ty = PointerType::get(Int32Ty, 1);
456
  Type *V2Int32PtrAS1Ty = FixedVectorType::get(Int32PtrAS1Ty, 2);
457
  Type *V2Int32PtrTy = FixedVectorType::get(Int32PtrTy, 2);
458
  const Constant *CV2ptr32 = Constant::getNullValue(V2Int32PtrTy);
459

460
  EXPECT_EQ(LLVMAddrSpaceCast, LLVMGetCastOpcode(wrap(CV2ptr32), true,
461
                                                 wrap(V2Int32PtrAS1Ty), true));
462
}
463

464
TEST(InstructionsTest, VectorGep) {
465
  LLVMContext C;
466

467
  // Type Definitions
468
  Type *I8Ty = IntegerType::get(C, 8);
469
  Type *I32Ty = IntegerType::get(C, 32);
470
  PointerType *Ptri8Ty = PointerType::get(I8Ty, 0);
471
  PointerType *Ptri32Ty = PointerType::get(I32Ty, 0);
472

473
  VectorType *V2xi8PTy = FixedVectorType::get(Ptri8Ty, 2);
474
  VectorType *V2xi32PTy = FixedVectorType::get(Ptri32Ty, 2);
475

476
  // Test different aspects of the vector-of-pointers type
477
  // and GEPs which use this type.
478
  ConstantInt *Ci32a = ConstantInt::get(C, APInt(32, 1492));
479
  ConstantInt *Ci32b = ConstantInt::get(C, APInt(32, 1948));
480
  std::vector<Constant*> ConstVa(2, Ci32a);
481
  std::vector<Constant*> ConstVb(2, Ci32b);
482
  Constant *C2xi32a = ConstantVector::get(ConstVa);
483
  Constant *C2xi32b = ConstantVector::get(ConstVb);
484

485
  CastInst *PtrVecA = new IntToPtrInst(C2xi32a, V2xi32PTy);
486
  CastInst *PtrVecB = new IntToPtrInst(C2xi32b, V2xi32PTy);
487

488
  ICmpInst *ICmp0 = new ICmpInst(ICmpInst::ICMP_SGT, PtrVecA, PtrVecB);
489
  ICmpInst *ICmp1 = new ICmpInst(ICmpInst::ICMP_ULT, PtrVecA, PtrVecB);
490
  EXPECT_NE(ICmp0, ICmp1); // suppress warning.
491

492
  BasicBlock* BB0 = BasicBlock::Create(C);
493
  // Test InsertAtEnd ICmpInst constructor.
494
  ICmpInst *ICmp2 = new ICmpInst(BB0, ICmpInst::ICMP_SGE, PtrVecA, PtrVecB);
495
  EXPECT_NE(ICmp0, ICmp2); // suppress warning.
496

497
  GetElementPtrInst *Gep0 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32a);
498
  GetElementPtrInst *Gep1 = GetElementPtrInst::Create(I32Ty, PtrVecA, C2xi32b);
499
  GetElementPtrInst *Gep2 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32a);
500
  GetElementPtrInst *Gep3 = GetElementPtrInst::Create(I32Ty, PtrVecB, C2xi32b);
501

502
  CastInst *BTC0 = new BitCastInst(Gep0, V2xi8PTy);
503
  CastInst *BTC1 = new BitCastInst(Gep1, V2xi8PTy);
504
  CastInst *BTC2 = new BitCastInst(Gep2, V2xi8PTy);
505
  CastInst *BTC3 = new BitCastInst(Gep3, V2xi8PTy);
506

507
  Value *S0 = BTC0->stripPointerCasts();
508
  Value *S1 = BTC1->stripPointerCasts();
509
  Value *S2 = BTC2->stripPointerCasts();
510
  Value *S3 = BTC3->stripPointerCasts();
511

512
  EXPECT_NE(S0, Gep0);
513
  EXPECT_NE(S1, Gep1);
514
  EXPECT_NE(S2, Gep2);
515
  EXPECT_NE(S3, Gep3);
516

517
  int64_t Offset;
518
  DataLayout TD("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f3"
519
                "2:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-s:64:64-f80"
520
                ":128:128-n8:16:32:64-S128");
521
  // Make sure we don't crash
522
  GetPointerBaseWithConstantOffset(Gep0, Offset, TD);
523
  GetPointerBaseWithConstantOffset(Gep1, Offset, TD);
524
  GetPointerBaseWithConstantOffset(Gep2, Offset, TD);
525
  GetPointerBaseWithConstantOffset(Gep3, Offset, TD);
526

527
  // Gep of Geps
528
  GetElementPtrInst *GepII0 = GetElementPtrInst::Create(I32Ty, Gep0, C2xi32b);
529
  GetElementPtrInst *GepII1 = GetElementPtrInst::Create(I32Ty, Gep1, C2xi32a);
530
  GetElementPtrInst *GepII2 = GetElementPtrInst::Create(I32Ty, Gep2, C2xi32b);
531
  GetElementPtrInst *GepII3 = GetElementPtrInst::Create(I32Ty, Gep3, C2xi32a);
532

533
  EXPECT_EQ(GepII0->getNumIndices(), 1u);
534
  EXPECT_EQ(GepII1->getNumIndices(), 1u);
535
  EXPECT_EQ(GepII2->getNumIndices(), 1u);
536
  EXPECT_EQ(GepII3->getNumIndices(), 1u);
537

538
  EXPECT_FALSE(GepII0->hasAllZeroIndices());
539
  EXPECT_FALSE(GepII1->hasAllZeroIndices());
540
  EXPECT_FALSE(GepII2->hasAllZeroIndices());
541
  EXPECT_FALSE(GepII3->hasAllZeroIndices());
542

543
  delete GepII0;
544
  delete GepII1;
545
  delete GepII2;
546
  delete GepII3;
547

548
  delete BTC0;
549
  delete BTC1;
550
  delete BTC2;
551
  delete BTC3;
552

553
  delete Gep0;
554
  delete Gep1;
555
  delete Gep2;
556
  delete Gep3;
557

558
  ICmp2->eraseFromParent();
559
  delete BB0;
560

561
  delete ICmp0;
562
  delete ICmp1;
563
  delete PtrVecA;
564
  delete PtrVecB;
565
}
566

567
TEST(InstructionsTest, FPMathOperator) {
568
  LLVMContext Context;
569
  IRBuilder<> Builder(Context);
570
  MDBuilder MDHelper(Context);
571
  Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
572
  MDNode *MD1 = MDHelper.createFPMath(1.0);
573
  Value *V1 = Builder.CreateFAdd(I, I, "", MD1);
574
  EXPECT_TRUE(isa<FPMathOperator>(V1));
575
  FPMathOperator *O1 = cast<FPMathOperator>(V1);
576
  EXPECT_EQ(O1->getFPAccuracy(), 1.0);
577
  V1->deleteValue();
578
  I->deleteValue();
579
}
580

581
TEST(InstructionTest, ConstrainedTrans) {
582
  LLVMContext Context;
583
  std::unique_ptr<Module> M(new Module("MyModule", Context));
584
  FunctionType *FTy =
585
      FunctionType::get(Type::getVoidTy(Context),
586
                        {Type::getFloatTy(Context), Type::getFloatTy(Context),
587
                         Type::getInt32Ty(Context)},
588
                        false);
589
  auto *F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
590
  auto *BB = BasicBlock::Create(Context, "bb", F);
591
  IRBuilder<> Builder(Context);
592
  Builder.SetInsertPoint(BB);
593
  auto *Arg0 = F->arg_begin();
594
  auto *Arg1 = F->arg_begin() + 1;
595

596
  {
597
    auto *I = cast<Instruction>(Builder.CreateFAdd(Arg0, Arg1));
598
    EXPECT_EQ(Intrinsic::experimental_constrained_fadd,
599
              getConstrainedIntrinsicID(*I));
600
  }
601

602
  {
603
    auto *I = cast<Instruction>(
604
        Builder.CreateFPToSI(Arg0, Type::getInt32Ty(Context)));
605
    EXPECT_EQ(Intrinsic::experimental_constrained_fptosi,
606
              getConstrainedIntrinsicID(*I));
607
  }
608

609
  {
610
    auto *I = cast<Instruction>(Builder.CreateIntrinsic(
611
        Intrinsic::ceil, {Type::getFloatTy(Context)}, {Arg0}));
612
    EXPECT_EQ(Intrinsic::experimental_constrained_ceil,
613
              getConstrainedIntrinsicID(*I));
614
  }
615

616
  {
617
    auto *I = cast<Instruction>(Builder.CreateFCmpOEQ(Arg0, Arg1));
618
    EXPECT_EQ(Intrinsic::experimental_constrained_fcmp,
619
              getConstrainedIntrinsicID(*I));
620
  }
621

622
  {
623
    auto *Arg2 = F->arg_begin() + 2;
624
    auto *I = cast<Instruction>(Builder.CreateAdd(Arg2, Arg2));
625
    EXPECT_EQ(Intrinsic::not_intrinsic, getConstrainedIntrinsicID(*I));
626
  }
627

628
  {
629
    auto *I = cast<Instruction>(Builder.CreateConstrainedFPBinOp(
630
        Intrinsic::experimental_constrained_fadd, Arg0, Arg0));
631
    EXPECT_EQ(Intrinsic::not_intrinsic, getConstrainedIntrinsicID(*I));
632
  }
633
}
634

635
TEST(InstructionsTest, isEliminableCastPair) {
636
  LLVMContext C;
637

638
  Type* Int16Ty = Type::getInt16Ty(C);
639
  Type* Int32Ty = Type::getInt32Ty(C);
640
  Type* Int64Ty = Type::getInt64Ty(C);
641
  Type *Int64PtrTy = PointerType::get(C, 0);
642

643
  // Source and destination pointers have same size -> bitcast.
644
  EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
645
                                           CastInst::IntToPtr,
646
                                           Int64PtrTy, Int64Ty, Int64PtrTy,
647
                                           Int32Ty, nullptr, Int32Ty),
648
            CastInst::BitCast);
649

650
  // Source and destination have unknown sizes, but the same address space and
651
  // the intermediate int is the maximum pointer size -> bitcast
652
  EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
653
                                           CastInst::IntToPtr,
654
                                           Int64PtrTy, Int64Ty, Int64PtrTy,
655
                                           nullptr, nullptr, nullptr),
656
            CastInst::BitCast);
657

658
  // Source and destination have unknown sizes, but the same address space and
659
  // the intermediate int is not the maximum pointer size -> nothing
660
  EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::PtrToInt,
661
                                           CastInst::IntToPtr,
662
                                           Int64PtrTy, Int32Ty, Int64PtrTy,
663
                                           nullptr, nullptr, nullptr),
664
            0U);
665

666
  // Middle pointer big enough -> bitcast.
667
  EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
668
                                           CastInst::PtrToInt,
669
                                           Int64Ty, Int64PtrTy, Int64Ty,
670
                                           nullptr, Int64Ty, nullptr),
671
            CastInst::BitCast);
672

673
  // Middle pointer too small -> fail.
674
  EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
675
                                           CastInst::PtrToInt,
676
                                           Int64Ty, Int64PtrTy, Int64Ty,
677
                                           nullptr, Int32Ty, nullptr),
678
            0U);
679

680
  // Test that we don't eliminate bitcasts between different address spaces,
681
  // or if we don't have available pointer size information.
682
  DataLayout DL("e-p:32:32:32-p1:16:16:16-p2:64:64:64-i1:8:8-i8:8:8-i16:16:16"
683
                "-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64"
684
                "-v128:128:128-a:0:64-s:64:64-f80:128:128-n8:16:32:64-S128");
685

686
  Type *Int64PtrTyAS1 = PointerType::get(C, 1);
687
  Type *Int64PtrTyAS2 = PointerType::get(C, 2);
688

689
  IntegerType *Int16SizePtr = DL.getIntPtrType(C, 1);
690
  IntegerType *Int64SizePtr = DL.getIntPtrType(C, 2);
691

692
  // Cannot simplify inttoptr, addrspacecast
693
  EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
694
                                           CastInst::AddrSpaceCast,
695
                                           Int16Ty, Int64PtrTyAS1, Int64PtrTyAS2,
696
                                           nullptr, Int16SizePtr, Int64SizePtr),
697
            0U);
698

699
  // Cannot simplify addrspacecast, ptrtoint
700
  EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::AddrSpaceCast,
701
                                           CastInst::PtrToInt,
702
                                           Int64PtrTyAS1, Int64PtrTyAS2, Int16Ty,
703
                                           Int64SizePtr, Int16SizePtr, nullptr),
704
            0U);
705

706
  // Pass since the bitcast address spaces are the same
707
  EXPECT_EQ(CastInst::isEliminableCastPair(CastInst::IntToPtr,
708
                                           CastInst::BitCast,
709
                                           Int16Ty, Int64PtrTyAS1, Int64PtrTyAS1,
710
                                           nullptr, nullptr, nullptr),
711
            CastInst::IntToPtr);
712

713
}
714

715
TEST(InstructionsTest, CloneCall) {
716
  LLVMContext C;
717
  Type *Int32Ty = Type::getInt32Ty(C);
718
  Type *ArgTys[] = {Int32Ty, Int32Ty, Int32Ty};
719
  FunctionType *FnTy = FunctionType::get(Int32Ty, ArgTys, /*isVarArg=*/false);
720
  Value *Callee = Constant::getNullValue(PointerType::getUnqual(C));
721
  Value *Args[] = {
722
    ConstantInt::get(Int32Ty, 1),
723
    ConstantInt::get(Int32Ty, 2),
724
    ConstantInt::get(Int32Ty, 3)
725
  };
726
  std::unique_ptr<CallInst> Call(
727
      CallInst::Create(FnTy, Callee, Args, "result"));
728

729
  // Test cloning the tail call kind.
730
  CallInst::TailCallKind Kinds[] = {CallInst::TCK_None, CallInst::TCK_Tail,
731
                                    CallInst::TCK_MustTail};
732
  for (CallInst::TailCallKind TCK : Kinds) {
733
    Call->setTailCallKind(TCK);
734
    std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone()));
735
    EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind());
736
  }
737
  Call->setTailCallKind(CallInst::TCK_None);
738

739
  // Test cloning an attribute.
740
  {
741
    AttrBuilder AB(C);
742
    AB.addAttribute(Attribute::NoUnwind);
743
    Call->setAttributes(
744
        AttributeList::get(C, AttributeList::FunctionIndex, AB));
745
    std::unique_ptr<CallInst> Clone(cast<CallInst>(Call->clone()));
746
    EXPECT_TRUE(Clone->doesNotThrow());
747
  }
748
}
749

750
TEST(InstructionsTest, AlterCallBundles) {
751
  LLVMContext C;
752
  Type *Int32Ty = Type::getInt32Ty(C);
753
  FunctionType *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
754
  Value *Callee = Constant::getNullValue(PointerType::getUnqual(C));
755
  Value *Args[] = {ConstantInt::get(Int32Ty, 42)};
756
  OperandBundleDef OldBundle("before", UndefValue::get(Int32Ty));
757
  std::unique_ptr<CallInst> Call(
758
      CallInst::Create(FnTy, Callee, Args, OldBundle, "result"));
759
  Call->setTailCallKind(CallInst::TailCallKind::TCK_NoTail);
760
  AttrBuilder AB(C);
761
  AB.addAttribute(Attribute::Cold);
762
  Call->setAttributes(AttributeList::get(C, AttributeList::FunctionIndex, AB));
763
  Call->setDebugLoc(DebugLoc(MDNode::get(C, std::nullopt)));
764

765
  OperandBundleDef NewBundle("after", ConstantInt::get(Int32Ty, 7));
766
  std::unique_ptr<CallInst> Clone(CallInst::Create(Call.get(), NewBundle));
767
  EXPECT_EQ(Call->arg_size(), Clone->arg_size());
768
  EXPECT_EQ(Call->getArgOperand(0), Clone->getArgOperand(0));
769
  EXPECT_EQ(Call->getCallingConv(), Clone->getCallingConv());
770
  EXPECT_EQ(Call->getTailCallKind(), Clone->getTailCallKind());
771
  EXPECT_TRUE(Clone->hasFnAttr(Attribute::AttrKind::Cold));
772
  EXPECT_EQ(Call->getDebugLoc(), Clone->getDebugLoc());
773
  EXPECT_EQ(Clone->getNumOperandBundles(), 1U);
774
  EXPECT_TRUE(Clone->getOperandBundle("after"));
775
}
776

777
TEST(InstructionsTest, AlterInvokeBundles) {
778
  LLVMContext C;
779
  Type *Int32Ty = Type::getInt32Ty(C);
780
  FunctionType *FnTy = FunctionType::get(Int32Ty, Int32Ty, /*isVarArg=*/false);
781
  Value *Callee = Constant::getNullValue(PointerType::getUnqual(C));
782
  Value *Args[] = {ConstantInt::get(Int32Ty, 42)};
783
  std::unique_ptr<BasicBlock> NormalDest(BasicBlock::Create(C));
784
  std::unique_ptr<BasicBlock> UnwindDest(BasicBlock::Create(C));
785
  OperandBundleDef OldBundle("before", UndefValue::get(Int32Ty));
786
  std::unique_ptr<InvokeInst> Invoke(
787
      InvokeInst::Create(FnTy, Callee, NormalDest.get(), UnwindDest.get(), Args,
788
                         OldBundle, "result"));
789
  AttrBuilder AB(C);
790
  AB.addAttribute(Attribute::Cold);
791
  Invoke->setAttributes(
792
      AttributeList::get(C, AttributeList::FunctionIndex, AB));
793
  Invoke->setDebugLoc(DebugLoc(MDNode::get(C, std::nullopt)));
794

795
  OperandBundleDef NewBundle("after", ConstantInt::get(Int32Ty, 7));
796
  std::unique_ptr<InvokeInst> Clone(
797
      InvokeInst::Create(Invoke.get(), NewBundle));
798
  EXPECT_EQ(Invoke->getNormalDest(), Clone->getNormalDest());
799
  EXPECT_EQ(Invoke->getUnwindDest(), Clone->getUnwindDest());
800
  EXPECT_EQ(Invoke->arg_size(), Clone->arg_size());
801
  EXPECT_EQ(Invoke->getArgOperand(0), Clone->getArgOperand(0));
802
  EXPECT_EQ(Invoke->getCallingConv(), Clone->getCallingConv());
803
  EXPECT_TRUE(Clone->hasFnAttr(Attribute::AttrKind::Cold));
804
  EXPECT_EQ(Invoke->getDebugLoc(), Clone->getDebugLoc());
805
  EXPECT_EQ(Clone->getNumOperandBundles(), 1U);
806
  EXPECT_TRUE(Clone->getOperandBundle("after"));
807
}
808

809
TEST_F(ModuleWithFunctionTest, DropPoisonGeneratingFlags) {
810
  auto *OnlyBB = BasicBlock::Create(Ctx, "bb", F);
811
  auto *Arg0 = &*F->arg_begin();
812

813
  IRBuilder<NoFolder> B(Ctx);
814
  B.SetInsertPoint(OnlyBB);
815

816
  {
817
    auto *UI =
818
        cast<Instruction>(B.CreateUDiv(Arg0, Arg0, "", /*isExact*/ true));
819
    ASSERT_TRUE(UI->isExact());
820
    UI->dropPoisonGeneratingFlags();
821
    ASSERT_FALSE(UI->isExact());
822
  }
823

824
  {
825
    auto *ShrI =
826
        cast<Instruction>(B.CreateLShr(Arg0, Arg0, "", /*isExact*/ true));
827
    ASSERT_TRUE(ShrI->isExact());
828
    ShrI->dropPoisonGeneratingFlags();
829
    ASSERT_FALSE(ShrI->isExact());
830
  }
831

832
  {
833
    auto *AI = cast<Instruction>(
834
        B.CreateAdd(Arg0, Arg0, "", /*HasNUW*/ true, /*HasNSW*/ false));
835
    ASSERT_TRUE(AI->hasNoUnsignedWrap());
836
    AI->dropPoisonGeneratingFlags();
837
    ASSERT_FALSE(AI->hasNoUnsignedWrap());
838
    ASSERT_FALSE(AI->hasNoSignedWrap());
839
  }
840

841
  {
842
    auto *SI = cast<Instruction>(
843
        B.CreateAdd(Arg0, Arg0, "", /*HasNUW*/ false, /*HasNSW*/ true));
844
    ASSERT_TRUE(SI->hasNoSignedWrap());
845
    SI->dropPoisonGeneratingFlags();
846
    ASSERT_FALSE(SI->hasNoUnsignedWrap());
847
    ASSERT_FALSE(SI->hasNoSignedWrap());
848
  }
849

850
  {
851
    auto *ShlI = cast<Instruction>(
852
        B.CreateShl(Arg0, Arg0, "", /*HasNUW*/ true, /*HasNSW*/ true));
853
    ASSERT_TRUE(ShlI->hasNoSignedWrap());
854
    ASSERT_TRUE(ShlI->hasNoUnsignedWrap());
855
    ShlI->dropPoisonGeneratingFlags();
856
    ASSERT_FALSE(ShlI->hasNoUnsignedWrap());
857
    ASSERT_FALSE(ShlI->hasNoSignedWrap());
858
  }
859

860
  {
861
    Value *GEPBase = Constant::getNullValue(B.getPtrTy());
862
    auto *GI = cast<GetElementPtrInst>(
863
        B.CreateInBoundsGEP(B.getInt8Ty(), GEPBase, Arg0));
864
    ASSERT_TRUE(GI->isInBounds());
865
    GI->dropPoisonGeneratingFlags();
866
    ASSERT_FALSE(GI->isInBounds());
867
  }
868
}
869

870
TEST(InstructionsTest, GEPIndices) {
871
  LLVMContext Context;
872
  IRBuilder<NoFolder> Builder(Context);
873
  Type *ElementTy = Builder.getInt8Ty();
874
  Type *ArrTy = ArrayType::get(ArrayType::get(ElementTy, 64), 64);
875
  Value *Indices[] = {
876
    Builder.getInt32(0),
877
    Builder.getInt32(13),
878
    Builder.getInt32(42) };
879

880
  Value *V = Builder.CreateGEP(ArrTy, UndefValue::get(PointerType::getUnqual(ArrTy)),
881
                               Indices);
882
  ASSERT_TRUE(isa<GetElementPtrInst>(V));
883

884
  auto *GEPI = cast<GetElementPtrInst>(V);
885
  ASSERT_NE(GEPI->idx_begin(), GEPI->idx_end());
886
  ASSERT_EQ(GEPI->idx_end(), std::next(GEPI->idx_begin(), 3));
887
  EXPECT_EQ(Indices[0], GEPI->idx_begin()[0]);
888
  EXPECT_EQ(Indices[1], GEPI->idx_begin()[1]);
889
  EXPECT_EQ(Indices[2], GEPI->idx_begin()[2]);
890
  EXPECT_EQ(GEPI->idx_begin(), GEPI->indices().begin());
891
  EXPECT_EQ(GEPI->idx_end(), GEPI->indices().end());
892

893
  const auto *CGEPI = GEPI;
894
  ASSERT_NE(CGEPI->idx_begin(), CGEPI->idx_end());
895
  ASSERT_EQ(CGEPI->idx_end(), std::next(CGEPI->idx_begin(), 3));
896
  EXPECT_EQ(Indices[0], CGEPI->idx_begin()[0]);
897
  EXPECT_EQ(Indices[1], CGEPI->idx_begin()[1]);
898
  EXPECT_EQ(Indices[2], CGEPI->idx_begin()[2]);
899
  EXPECT_EQ(CGEPI->idx_begin(), CGEPI->indices().begin());
900
  EXPECT_EQ(CGEPI->idx_end(), CGEPI->indices().end());
901

902
  delete GEPI;
903
}
904

905
TEST(InstructionsTest, SwitchInst) {
906
  LLVMContext C;
907

908
  std::unique_ptr<BasicBlock> BB1, BB2, BB3;
909
  BB1.reset(BasicBlock::Create(C));
910
  BB2.reset(BasicBlock::Create(C));
911
  BB3.reset(BasicBlock::Create(C));
912

913
  // We create block 0 after the others so that it gets destroyed first and
914
  // clears the uses of the other basic blocks.
915
  std::unique_ptr<BasicBlock> BB0(BasicBlock::Create(C));
916

917
  auto *Int32Ty = Type::getInt32Ty(C);
918

919
  SwitchInst *SI =
920
      SwitchInst::Create(UndefValue::get(Int32Ty), BB0.get(), 3, BB0.get());
921
  SI->addCase(ConstantInt::get(Int32Ty, 1), BB1.get());
922
  SI->addCase(ConstantInt::get(Int32Ty, 2), BB2.get());
923
  SI->addCase(ConstantInt::get(Int32Ty, 3), BB3.get());
924

925
  auto CI = SI->case_begin();
926
  ASSERT_NE(CI, SI->case_end());
927
  EXPECT_EQ(1, CI->getCaseValue()->getSExtValue());
928
  EXPECT_EQ(BB1.get(), CI->getCaseSuccessor());
929
  EXPECT_EQ(2, (CI + 1)->getCaseValue()->getSExtValue());
930
  EXPECT_EQ(BB2.get(), (CI + 1)->getCaseSuccessor());
931
  EXPECT_EQ(3, (CI + 2)->getCaseValue()->getSExtValue());
932
  EXPECT_EQ(BB3.get(), (CI + 2)->getCaseSuccessor());
933
  EXPECT_EQ(CI + 1, std::next(CI));
934
  EXPECT_EQ(CI + 2, std::next(CI, 2));
935
  EXPECT_EQ(CI + 3, std::next(CI, 3));
936
  EXPECT_EQ(SI->case_end(), CI + 3);
937
  EXPECT_EQ(0, CI - CI);
938
  EXPECT_EQ(1, (CI + 1) - CI);
939
  EXPECT_EQ(2, (CI + 2) - CI);
940
  EXPECT_EQ(3, SI->case_end() - CI);
941
  EXPECT_EQ(3, std::distance(CI, SI->case_end()));
942

943
  auto CCI = const_cast<const SwitchInst *>(SI)->case_begin();
944
  SwitchInst::ConstCaseIt CCE = SI->case_end();
945
  ASSERT_NE(CCI, SI->case_end());
946
  EXPECT_EQ(1, CCI->getCaseValue()->getSExtValue());
947
  EXPECT_EQ(BB1.get(), CCI->getCaseSuccessor());
948
  EXPECT_EQ(2, (CCI + 1)->getCaseValue()->getSExtValue());
949
  EXPECT_EQ(BB2.get(), (CCI + 1)->getCaseSuccessor());
950
  EXPECT_EQ(3, (CCI + 2)->getCaseValue()->getSExtValue());
951
  EXPECT_EQ(BB3.get(), (CCI + 2)->getCaseSuccessor());
952
  EXPECT_EQ(CCI + 1, std::next(CCI));
953
  EXPECT_EQ(CCI + 2, std::next(CCI, 2));
954
  EXPECT_EQ(CCI + 3, std::next(CCI, 3));
955
  EXPECT_EQ(CCE, CCI + 3);
956
  EXPECT_EQ(0, CCI - CCI);
957
  EXPECT_EQ(1, (CCI + 1) - CCI);
958
  EXPECT_EQ(2, (CCI + 2) - CCI);
959
  EXPECT_EQ(3, CCE - CCI);
960
  EXPECT_EQ(3, std::distance(CCI, CCE));
961

962
  // Make sure that the const iterator is compatible with a const auto ref.
963
  const auto &Handle = *CCI;
964
  EXPECT_EQ(1, Handle.getCaseValue()->getSExtValue());
965
  EXPECT_EQ(BB1.get(), Handle.getCaseSuccessor());
966
}
967

968
TEST(InstructionsTest, SwitchInstProfUpdateWrapper) {
969
  LLVMContext C;
970

971
  std::unique_ptr<BasicBlock> BB1, BB2, BB3;
972
  BB1.reset(BasicBlock::Create(C));
973
  BB2.reset(BasicBlock::Create(C));
974
  BB3.reset(BasicBlock::Create(C));
975

976
  // We create block 0 after the others so that it gets destroyed first and
977
  // clears the uses of the other basic blocks.
978
  std::unique_ptr<BasicBlock> BB0(BasicBlock::Create(C));
979

980
  auto *Int32Ty = Type::getInt32Ty(C);
981

982
  SwitchInst *SI =
983
      SwitchInst::Create(UndefValue::get(Int32Ty), BB0.get(), 4, BB0.get());
984
  SI->addCase(ConstantInt::get(Int32Ty, 1), BB1.get());
985
  SI->addCase(ConstantInt::get(Int32Ty, 2), BB2.get());
986
  SI->setMetadata(LLVMContext::MD_prof,
987
                  MDBuilder(C).createBranchWeights({ 9, 1, 22 }));
988

989
  {
990
    SwitchInstProfUpdateWrapper SIW(*SI);
991
    EXPECT_EQ(*SIW.getSuccessorWeight(0), 9u);
992
    EXPECT_EQ(*SIW.getSuccessorWeight(1), 1u);
993
    EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
994
    SIW.setSuccessorWeight(0, 99u);
995
    SIW.setSuccessorWeight(1, 11u);
996
    EXPECT_EQ(*SIW.getSuccessorWeight(0), 99u);
997
    EXPECT_EQ(*SIW.getSuccessorWeight(1), 11u);
998
    EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
999
  }
1000

1001
  { // Create another wrapper and check that the data persist.
1002
    SwitchInstProfUpdateWrapper SIW(*SI);
1003
    EXPECT_EQ(*SIW.getSuccessorWeight(0), 99u);
1004
    EXPECT_EQ(*SIW.getSuccessorWeight(1), 11u);
1005
    EXPECT_EQ(*SIW.getSuccessorWeight(2), 22u);
1006
  }
1007
}
1008

1009
TEST(InstructionsTest, CommuteShuffleMask) {
1010
  SmallVector<int, 16> Indices({-1, 0, 7});
1011
  ShuffleVectorInst::commuteShuffleMask(Indices, 4);
1012
  EXPECT_THAT(Indices, testing::ContainerEq(ArrayRef<int>({-1, 4, 3})));
1013
}
1014

1015
TEST(InstructionsTest, ShuffleMaskQueries) {
1016
  // Create the elements for various constant vectors.
1017
  LLVMContext Ctx;
1018
  Type *Int32Ty = Type::getInt32Ty(Ctx);
1019
  Constant *CU = UndefValue::get(Int32Ty);
1020
  Constant *C0 = ConstantInt::get(Int32Ty, 0);
1021
  Constant *C1 = ConstantInt::get(Int32Ty, 1);
1022
  Constant *C2 = ConstantInt::get(Int32Ty, 2);
1023
  Constant *C3 = ConstantInt::get(Int32Ty, 3);
1024
  Constant *C4 = ConstantInt::get(Int32Ty, 4);
1025
  Constant *C5 = ConstantInt::get(Int32Ty, 5);
1026
  Constant *C6 = ConstantInt::get(Int32Ty, 6);
1027
  Constant *C7 = ConstantInt::get(Int32Ty, 7);
1028

1029
  Constant *Identity = ConstantVector::get({C0, CU, C2, C3, C4});
1030
  EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(
1031
      Identity, cast<FixedVectorType>(Identity->getType())->getNumElements()));
1032
  EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1033
      Identity,
1034
      cast<FixedVectorType>(Identity->getType())
1035
          ->getNumElements())); // identity is distinguished from select
1036
  EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1037
      Identity, cast<FixedVectorType>(Identity->getType())->getNumElements()));
1038
  EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1039
      Identity, cast<FixedVectorType>(Identity->getType())
1040
                    ->getNumElements())); // identity is always single source
1041
  EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1042
      Identity, cast<FixedVectorType>(Identity->getType())->getNumElements()));
1043
  EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1044
      Identity, cast<FixedVectorType>(Identity->getType())->getNumElements()));
1045

1046
  Constant *Select = ConstantVector::get({CU, C1, C5});
1047
  EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1048
      Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1049
  EXPECT_TRUE(ShuffleVectorInst::isSelectMask(
1050
      Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1051
  EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1052
      Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1053
  EXPECT_FALSE(ShuffleVectorInst::isSingleSourceMask(
1054
      Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1055
  EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1056
      Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1057
  EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1058
      Select, cast<FixedVectorType>(Select->getType())->getNumElements()));
1059

1060
  Constant *Reverse = ConstantVector::get({C3, C2, C1, CU});
1061
  EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1062
      Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1063
  EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1064
      Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1065
  EXPECT_TRUE(ShuffleVectorInst::isReverseMask(
1066
      Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1067
  EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1068
      Reverse, cast<FixedVectorType>(Reverse->getType())
1069
                   ->getNumElements())); // reverse is always single source
1070
  EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1071
      Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1072
  EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1073
      Reverse, cast<FixedVectorType>(Reverse->getType())->getNumElements()));
1074

1075
  Constant *SingleSource = ConstantVector::get({C2, C2, C0, CU});
1076
  EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1077
      SingleSource,
1078
      cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1079
  EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1080
      SingleSource,
1081
      cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1082
  EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1083
      SingleSource,
1084
      cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1085
  EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1086
      SingleSource,
1087
      cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1088
  EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1089
      SingleSource,
1090
      cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1091
  EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1092
      SingleSource,
1093
      cast<FixedVectorType>(SingleSource->getType())->getNumElements()));
1094

1095
  Constant *ZeroEltSplat = ConstantVector::get({C0, C0, CU, C0});
1096
  EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1097
      ZeroEltSplat,
1098
      cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1099
  EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1100
      ZeroEltSplat,
1101
      cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1102
  EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1103
      ZeroEltSplat,
1104
      cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1105
  EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1106
      ZeroEltSplat, cast<FixedVectorType>(ZeroEltSplat->getType())
1107
                        ->getNumElements())); // 0-splat is always single source
1108
  EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(
1109
      ZeroEltSplat,
1110
      cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1111
  EXPECT_FALSE(ShuffleVectorInst::isTransposeMask(
1112
      ZeroEltSplat,
1113
      cast<FixedVectorType>(ZeroEltSplat->getType())->getNumElements()));
1114

1115
  Constant *Transpose = ConstantVector::get({C0, C4, C2, C6});
1116
  EXPECT_FALSE(ShuffleVectorInst::isIdentityMask(
1117
      Transpose,
1118
      cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1119
  EXPECT_FALSE(ShuffleVectorInst::isSelectMask(
1120
      Transpose,
1121
      cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1122
  EXPECT_FALSE(ShuffleVectorInst::isReverseMask(
1123
      Transpose,
1124
      cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1125
  EXPECT_FALSE(ShuffleVectorInst::isSingleSourceMask(
1126
      Transpose,
1127
      cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1128
  EXPECT_FALSE(ShuffleVectorInst::isZeroEltSplatMask(
1129
      Transpose,
1130
      cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1131
  EXPECT_TRUE(ShuffleVectorInst::isTransposeMask(
1132
      Transpose,
1133
      cast<FixedVectorType>(Transpose->getType())->getNumElements()));
1134

1135
  // More tests to make sure the logic is/stays correct...
1136
  EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(
1137
      ConstantVector::get({CU, C1, CU, C3}), 4));
1138
  EXPECT_TRUE(ShuffleVectorInst::isIdentityMask(
1139
      ConstantVector::get({C4, CU, C6, CU}), 4));
1140

1141
  EXPECT_TRUE(ShuffleVectorInst::isSelectMask(
1142
      ConstantVector::get({C4, C1, C6, CU}), 4));
1143
  EXPECT_TRUE(ShuffleVectorInst::isSelectMask(
1144
      ConstantVector::get({CU, C1, C6, C3}), 4));
1145

1146
  EXPECT_TRUE(ShuffleVectorInst::isReverseMask(
1147
      ConstantVector::get({C7, C6, CU, C4}), 4));
1148
  EXPECT_TRUE(ShuffleVectorInst::isReverseMask(
1149
      ConstantVector::get({C3, CU, C1, CU}), 4));
1150

1151
  EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1152
      ConstantVector::get({C7, C5, CU, C7}), 4));
1153
  EXPECT_TRUE(ShuffleVectorInst::isSingleSourceMask(
1154
      ConstantVector::get({C3, C0, CU, C3}), 4));
1155

1156
  EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(
1157
      ConstantVector::get({C4, CU, CU, C4}), 4));
1158
  EXPECT_TRUE(ShuffleVectorInst::isZeroEltSplatMask(
1159
      ConstantVector::get({CU, C0, CU, C0}), 4));
1160

1161
  EXPECT_TRUE(ShuffleVectorInst::isTransposeMask(
1162
      ConstantVector::get({C1, C5, C3, C7}), 4));
1163
  EXPECT_TRUE(
1164
      ShuffleVectorInst::isTransposeMask(ConstantVector::get({C1, C3}), 2));
1165

1166
  // Nothing special about the values here - just re-using inputs to reduce code. 
1167
  Constant *V0 = ConstantVector::get({C0, C1, C2, C3});
1168
  Constant *V1 = ConstantVector::get({C3, C2, C1, C0});
1169

1170
  // Identity with undef elts.
1171
  ShuffleVectorInst *Id1 = new ShuffleVectorInst(V0, V1,
1172
                                                 ConstantVector::get({C0, C1, CU, CU}));
1173
  EXPECT_TRUE(Id1->isIdentity());
1174
  EXPECT_FALSE(Id1->isIdentityWithPadding());
1175
  EXPECT_FALSE(Id1->isIdentityWithExtract());
1176
  EXPECT_FALSE(Id1->isConcat());
1177
  delete Id1;
1178

1179
  // Result has less elements than operands.
1180
  ShuffleVectorInst *Id2 = new ShuffleVectorInst(V0, V1,
1181
                                                 ConstantVector::get({C0, C1, C2}));
1182
  EXPECT_FALSE(Id2->isIdentity());
1183
  EXPECT_FALSE(Id2->isIdentityWithPadding());
1184
  EXPECT_TRUE(Id2->isIdentityWithExtract());
1185
  EXPECT_FALSE(Id2->isConcat());
1186
  delete Id2;
1187

1188
  // Result has less elements than operands; choose from Op1.
1189
  ShuffleVectorInst *Id3 = new ShuffleVectorInst(V0, V1,
1190
                                                 ConstantVector::get({C4, CU, C6}));
1191
  EXPECT_FALSE(Id3->isIdentity());
1192
  EXPECT_FALSE(Id3->isIdentityWithPadding());
1193
  EXPECT_TRUE(Id3->isIdentityWithExtract());
1194
  EXPECT_FALSE(Id3->isConcat());
1195
  delete Id3;
1196

1197
  // Result has less elements than operands; choose from Op0 and Op1 is not identity.
1198
  ShuffleVectorInst *Id4 = new ShuffleVectorInst(V0, V1,
1199
                                                 ConstantVector::get({C4, C1, C6}));
1200
  EXPECT_FALSE(Id4->isIdentity());
1201
  EXPECT_FALSE(Id4->isIdentityWithPadding());
1202
  EXPECT_FALSE(Id4->isIdentityWithExtract());
1203
  EXPECT_FALSE(Id4->isConcat());
1204
  delete Id4;
1205

1206
  // Result has more elements than operands, and extra elements are undef.
1207
  ShuffleVectorInst *Id5 = new ShuffleVectorInst(V0, V1,
1208
                                                 ConstantVector::get({CU, C1, C2, C3, CU, CU}));
1209
  EXPECT_FALSE(Id5->isIdentity());
1210
  EXPECT_TRUE(Id5->isIdentityWithPadding());
1211
  EXPECT_FALSE(Id5->isIdentityWithExtract());
1212
  EXPECT_FALSE(Id5->isConcat());
1213
  delete Id5;
1214

1215
  // Result has more elements than operands, and extra elements are undef; choose from Op1.
1216
  ShuffleVectorInst *Id6 = new ShuffleVectorInst(V0, V1,
1217
                                                 ConstantVector::get({C4, C5, C6, CU, CU, CU}));
1218
  EXPECT_FALSE(Id6->isIdentity());
1219
  EXPECT_TRUE(Id6->isIdentityWithPadding());
1220
  EXPECT_FALSE(Id6->isIdentityWithExtract());
1221
  EXPECT_FALSE(Id6->isConcat());
1222
  delete Id6;
1223
  
1224
  // Result has more elements than operands, but extra elements are not undef.
1225
  ShuffleVectorInst *Id7 = new ShuffleVectorInst(V0, V1,
1226
                                                 ConstantVector::get({C0, C1, C2, C3, CU, C1}));
1227
  EXPECT_FALSE(Id7->isIdentity());
1228
  EXPECT_FALSE(Id7->isIdentityWithPadding());
1229
  EXPECT_FALSE(Id7->isIdentityWithExtract());
1230
  EXPECT_FALSE(Id7->isConcat());
1231
  delete Id7;
1232
  
1233
  // Result has more elements than operands; choose from Op0 and Op1 is not identity.
1234
  ShuffleVectorInst *Id8 = new ShuffleVectorInst(V0, V1,
1235
                                                 ConstantVector::get({C4, CU, C2, C3, CU, CU}));
1236
  EXPECT_FALSE(Id8->isIdentity());
1237
  EXPECT_FALSE(Id8->isIdentityWithPadding());
1238
  EXPECT_FALSE(Id8->isIdentityWithExtract());
1239
  EXPECT_FALSE(Id8->isConcat());
1240
  delete Id8;
1241

1242
  // Result has twice as many elements as operands; choose consecutively from Op0 and Op1 is concat.
1243
  ShuffleVectorInst *Id9 = new ShuffleVectorInst(V0, V1,
1244
                                                 ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7}));
1245
  EXPECT_FALSE(Id9->isIdentity());
1246
  EXPECT_FALSE(Id9->isIdentityWithPadding());
1247
  EXPECT_FALSE(Id9->isIdentityWithExtract());
1248
  EXPECT_TRUE(Id9->isConcat());
1249
  delete Id9;
1250

1251
  // Result has less than twice as many elements as operands, so not a concat.
1252
  ShuffleVectorInst *Id10 = new ShuffleVectorInst(V0, V1,
1253
                                                  ConstantVector::get({C0, CU, C2, C3, CU, CU, C6}));
1254
  EXPECT_FALSE(Id10->isIdentity());
1255
  EXPECT_FALSE(Id10->isIdentityWithPadding());
1256
  EXPECT_FALSE(Id10->isIdentityWithExtract());
1257
  EXPECT_FALSE(Id10->isConcat());
1258
  delete Id10;
1259

1260
  // Result has more than twice as many elements as operands, so not a concat.
1261
  ShuffleVectorInst *Id11 = new ShuffleVectorInst(V0, V1,
1262
                                                  ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7, CU}));
1263
  EXPECT_FALSE(Id11->isIdentity());
1264
  EXPECT_FALSE(Id11->isIdentityWithPadding());
1265
  EXPECT_FALSE(Id11->isIdentityWithExtract());
1266
  EXPECT_FALSE(Id11->isConcat());
1267
  delete Id11;
1268

1269
  // If an input is undef, it's not a concat.
1270
  // TODO: IdentityWithPadding should be true here even though the high mask values are not undef.
1271
  ShuffleVectorInst *Id12 = new ShuffleVectorInst(V0, ConstantVector::get({CU, CU, CU, CU}),
1272
                                                  ConstantVector::get({C0, CU, C2, C3, CU, CU, C6, C7}));
1273
  EXPECT_FALSE(Id12->isIdentity());
1274
  EXPECT_FALSE(Id12->isIdentityWithPadding());
1275
  EXPECT_FALSE(Id12->isIdentityWithExtract());
1276
  EXPECT_FALSE(Id12->isConcat());
1277
  delete Id12;
1278

1279
  // Not possible to express shuffle mask for scalable vector for extract
1280
  // subvector.
1281
  Type *VScaleV4Int32Ty = ScalableVectorType::get(Int32Ty, 4);
1282
  ShuffleVectorInst *Id13 =
1283
      new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV4Int32Ty),
1284
                            UndefValue::get(VScaleV4Int32Ty),
1285
                            Constant::getNullValue(VScaleV4Int32Ty));
1286
  int Index = 0;
1287
  EXPECT_FALSE(Id13->isExtractSubvectorMask(Index));
1288
  EXPECT_FALSE(Id13->changesLength());
1289
  EXPECT_FALSE(Id13->increasesLength());
1290
  delete Id13;
1291

1292
  // Result has twice as many operands.
1293
  Type *VScaleV2Int32Ty = ScalableVectorType::get(Int32Ty, 2);
1294
  ShuffleVectorInst *Id14 =
1295
      new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV2Int32Ty),
1296
                            UndefValue::get(VScaleV2Int32Ty),
1297
                            Constant::getNullValue(VScaleV4Int32Ty));
1298
  EXPECT_TRUE(Id14->changesLength());
1299
  EXPECT_TRUE(Id14->increasesLength());
1300
  delete Id14;
1301

1302
  // Not possible to express these masks for scalable vectors, make sure we
1303
  // don't crash.
1304
  ShuffleVectorInst *Id15 =
1305
      new ShuffleVectorInst(Constant::getAllOnesValue(VScaleV2Int32Ty),
1306
                            Constant::getNullValue(VScaleV2Int32Ty),
1307
                            Constant::getNullValue(VScaleV2Int32Ty));
1308
  EXPECT_FALSE(Id15->isIdentityWithPadding());
1309
  EXPECT_FALSE(Id15->isIdentityWithExtract());
1310
  EXPECT_FALSE(Id15->isConcat());
1311
  delete Id15;
1312
}
1313

1314
TEST(InstructionsTest, ShuffleMaskIsReplicationMask) {
1315
  for (int ReplicationFactor : seq_inclusive(1, 8)) {
1316
    for (int VF : seq_inclusive(1, 8)) {
1317
      const auto ReplicatedMask = createReplicatedMask(ReplicationFactor, VF);
1318
      int GuessedReplicationFactor = -1, GuessedVF = -1;
1319
      EXPECT_TRUE(ShuffleVectorInst::isReplicationMask(
1320
          ReplicatedMask, GuessedReplicationFactor, GuessedVF));
1321
      EXPECT_EQ(GuessedReplicationFactor, ReplicationFactor);
1322
      EXPECT_EQ(GuessedVF, VF);
1323

1324
      for (int OpVF : seq_inclusive(VF, 2 * VF + 1)) {
1325
        LLVMContext Ctx;
1326
        Type *OpVFTy = FixedVectorType::get(IntegerType::getInt1Ty(Ctx), OpVF);
1327
        Value *Op = ConstantVector::getNullValue(OpVFTy);
1328
        ShuffleVectorInst *SVI = new ShuffleVectorInst(Op, Op, ReplicatedMask);
1329
        EXPECT_EQ(SVI->isReplicationMask(GuessedReplicationFactor, GuessedVF),
1330
                  OpVF == VF);
1331
        delete SVI;
1332
      }
1333
    }
1334
  }
1335
}
1336

1337
TEST(InstructionsTest, ShuffleMaskIsReplicationMask_undef) {
1338
  for (int ReplicationFactor : seq_inclusive(1, 4)) {
1339
    for (int VF : seq_inclusive(1, 4)) {
1340
      const auto ReplicatedMask = createReplicatedMask(ReplicationFactor, VF);
1341
      int GuessedReplicationFactor = -1, GuessedVF = -1;
1342

1343
      // If we change some mask elements to undef, we should still match.
1344

1345
      SmallVector<SmallVector<bool>> ElementChoices(ReplicatedMask.size(),
1346
                                                    {false, true});
1347

1348
      CombinationGenerator<bool, decltype(ElementChoices)::value_type,
1349
                           /*variable_smallsize=*/4>
1350
          G(ElementChoices);
1351

1352
      G.generate([&](ArrayRef<bool> UndefOverrides) -> bool {
1353
        SmallVector<int> AdjustedMask;
1354
        AdjustedMask.reserve(ReplicatedMask.size());
1355
        for (auto I : zip(ReplicatedMask, UndefOverrides))
1356
          AdjustedMask.emplace_back(std::get<1>(I) ? -1 : std::get<0>(I));
1357
        assert(AdjustedMask.size() == ReplicatedMask.size() &&
1358
               "Size misprediction");
1359

1360
        EXPECT_TRUE(ShuffleVectorInst::isReplicationMask(
1361
            AdjustedMask, GuessedReplicationFactor, GuessedVF));
1362
        // Do not check GuessedReplicationFactor and GuessedVF,
1363
        // with enough undef's we may deduce a different tuple.
1364

1365
        return /*Abort=*/false;
1366
      });
1367
    }
1368
  }
1369
}
1370

1371
TEST(InstructionsTest, ShuffleMaskIsReplicationMask_Exhaustive_Correctness) {
1372
  for (int ShufMaskNumElts : seq_inclusive(1, 6)) {
1373
    SmallVector<int> PossibleShufMaskElts;
1374
    PossibleShufMaskElts.reserve(ShufMaskNumElts + 2);
1375
    for (int PossibleShufMaskElt : seq_inclusive(-1, ShufMaskNumElts))
1376
      PossibleShufMaskElts.emplace_back(PossibleShufMaskElt);
1377
    assert(PossibleShufMaskElts.size() == ShufMaskNumElts + 2U &&
1378
           "Size misprediction");
1379

1380
    SmallVector<SmallVector<int>> ElementChoices(ShufMaskNumElts,
1381
                                                 PossibleShufMaskElts);
1382

1383
    CombinationGenerator<int, decltype(ElementChoices)::value_type,
1384
                         /*variable_smallsize=*/4>
1385
        G(ElementChoices);
1386

1387
    G.generate([&](ArrayRef<int> Mask) -> bool {
1388
      int GuessedReplicationFactor = -1, GuessedVF = -1;
1389
      bool Match = ShuffleVectorInst::isReplicationMask(
1390
          Mask, GuessedReplicationFactor, GuessedVF);
1391
      if (!Match)
1392
        return /*Abort=*/false;
1393

1394
      const auto ActualMask =
1395
          createReplicatedMask(GuessedReplicationFactor, GuessedVF);
1396
      EXPECT_EQ(Mask.size(), ActualMask.size());
1397
      for (auto I : zip(Mask, ActualMask)) {
1398
        int Elt = std::get<0>(I);
1399
        int ActualElt = std::get<0>(I);
1400

1401
        if (Elt != -1) {
1402
          EXPECT_EQ(Elt, ActualElt);
1403
        }
1404
      }
1405

1406
      return /*Abort=*/false;
1407
    });
1408
  }
1409
}
1410

1411
TEST(InstructionsTest, GetSplat) {
1412
  // Create the elements for various constant vectors.
1413
  LLVMContext Ctx;
1414
  Type *Int32Ty = Type::getInt32Ty(Ctx);
1415
  Constant *CU = UndefValue::get(Int32Ty);
1416
  Constant *CP = PoisonValue::get(Int32Ty);
1417
  Constant *C0 = ConstantInt::get(Int32Ty, 0);
1418
  Constant *C1 = ConstantInt::get(Int32Ty, 1);
1419

1420
  Constant *Splat0 = ConstantVector::get({C0, C0, C0, C0});
1421
  Constant *Splat1 = ConstantVector::get({C1, C1, C1, C1 ,C1});
1422
  Constant *Splat0Undef = ConstantVector::get({C0, CU, C0, CU});
1423
  Constant *Splat1Undef = ConstantVector::get({CU, CU, C1, CU});
1424
  Constant *NotSplat = ConstantVector::get({C1, C1, C0, C1 ,C1});
1425
  Constant *NotSplatUndef = ConstantVector::get({CU, C1, CU, CU ,C0});
1426
  Constant *Splat0Poison = ConstantVector::get({C0, CP, C0, CP});
1427
  Constant *Splat1Poison = ConstantVector::get({CP, CP, C1, CP});
1428
  Constant *NotSplatPoison = ConstantVector::get({CP, C1, CP, CP, C0});
1429

1430
  // Default - undef/poison is not allowed.
1431
  EXPECT_EQ(Splat0->getSplatValue(), C0);
1432
  EXPECT_EQ(Splat1->getSplatValue(), C1);
1433
  EXPECT_EQ(Splat0Undef->getSplatValue(), nullptr);
1434
  EXPECT_EQ(Splat1Undef->getSplatValue(), nullptr);
1435
  EXPECT_EQ(Splat0Poison->getSplatValue(), nullptr);
1436
  EXPECT_EQ(Splat1Poison->getSplatValue(), nullptr);
1437
  EXPECT_EQ(NotSplat->getSplatValue(), nullptr);
1438
  EXPECT_EQ(NotSplatUndef->getSplatValue(), nullptr);
1439
  EXPECT_EQ(NotSplatPoison->getSplatValue(), nullptr);
1440

1441
  // Disallow poison explicitly.
1442
  EXPECT_EQ(Splat0->getSplatValue(false), C0);
1443
  EXPECT_EQ(Splat1->getSplatValue(false), C1);
1444
  EXPECT_EQ(Splat0Undef->getSplatValue(false), nullptr);
1445
  EXPECT_EQ(Splat1Undef->getSplatValue(false), nullptr);
1446
  EXPECT_EQ(Splat0Poison->getSplatValue(false), nullptr);
1447
  EXPECT_EQ(Splat1Poison->getSplatValue(false), nullptr);
1448
  EXPECT_EQ(NotSplat->getSplatValue(false), nullptr);
1449
  EXPECT_EQ(NotSplatUndef->getSplatValue(false), nullptr);
1450
  EXPECT_EQ(NotSplatPoison->getSplatValue(false), nullptr);
1451

1452
  // Allow poison but not undef.
1453
  EXPECT_EQ(Splat0->getSplatValue(true), C0);
1454
  EXPECT_EQ(Splat1->getSplatValue(true), C1);
1455
  EXPECT_EQ(Splat0Undef->getSplatValue(true), nullptr);
1456
  EXPECT_EQ(Splat1Undef->getSplatValue(true), nullptr);
1457
  EXPECT_EQ(Splat0Poison->getSplatValue(true), C0);
1458
  EXPECT_EQ(Splat1Poison->getSplatValue(true), C1);
1459
  EXPECT_EQ(NotSplat->getSplatValue(true), nullptr);
1460
  EXPECT_EQ(NotSplatUndef->getSplatValue(true), nullptr);
1461
  EXPECT_EQ(NotSplatPoison->getSplatValue(true), nullptr);
1462
}
1463

1464
TEST(InstructionsTest, SkipDebug) {
1465
  LLVMContext C;
1466
  bool OldDbgValueMode = UseNewDbgInfoFormat;
1467
  UseNewDbgInfoFormat = false;
1468
  std::unique_ptr<Module> M = parseIR(C,
1469
                                      R"(
1470
      declare void @llvm.dbg.value(metadata, metadata, metadata)
1471

1472
      define void @f() {
1473
      entry:
1474
        call void @llvm.dbg.value(metadata i32 0, metadata !11, metadata !DIExpression()), !dbg !13
1475
        ret void
1476
      }
1477

1478
      !llvm.dbg.cu = !{!0}
1479
      !llvm.module.flags = !{!3, !4}
1480
      !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
1481
      !1 = !DIFile(filename: "t2.c", directory: "foo")
1482
      !2 = !{}
1483
      !3 = !{i32 2, !"Dwarf Version", i32 4}
1484
      !4 = !{i32 2, !"Debug Info Version", i32 3}
1485
      !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)
1486
      !9 = !DISubroutineType(types: !10)
1487
      !10 = !{null}
1488
      !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12)
1489
      !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
1490
      !13 = !DILocation(line: 2, column: 7, scope: !8)
1491
  )");
1492
  ASSERT_TRUE(M);
1493
  Function *F = cast<Function>(M->getNamedValue("f"));
1494
  BasicBlock &BB = F->front();
1495

1496
  // The first non-debug instruction is the terminator.
1497
  auto *Term = BB.getTerminator();
1498
  EXPECT_EQ(Term, BB.begin()->getNextNonDebugInstruction());
1499
  EXPECT_EQ(Term->getIterator(), skipDebugIntrinsics(BB.begin()));
1500

1501
  // After the terminator, there are no non-debug instructions.
1502
  EXPECT_EQ(nullptr, Term->getNextNonDebugInstruction());
1503
  UseNewDbgInfoFormat = OldDbgValueMode;
1504
}
1505

1506
TEST(InstructionsTest, PhiMightNotBeFPMathOperator) {
1507
  LLVMContext Context;
1508
  IRBuilder<> Builder(Context);
1509
  MDBuilder MDHelper(Context);
1510
  Instruction *I = Builder.CreatePHI(Builder.getInt32Ty(), 0);
1511
  EXPECT_FALSE(isa<FPMathOperator>(I));
1512
  I->deleteValue();
1513
  Instruction *FP = Builder.CreatePHI(Builder.getDoubleTy(), 0);
1514
  EXPECT_TRUE(isa<FPMathOperator>(FP));
1515
  FP->deleteValue();
1516
}
1517

1518
TEST(InstructionsTest, FPCallIsFPMathOperator) {
1519
  LLVMContext C;
1520

1521
  Type *ITy = Type::getInt32Ty(C);
1522
  FunctionType *IFnTy = FunctionType::get(ITy, {});
1523
  PointerType *PtrTy = PointerType::getUnqual(C);
1524
  Value *ICallee = Constant::getNullValue(PtrTy);
1525
  std::unique_ptr<CallInst> ICall(CallInst::Create(IFnTy, ICallee, {}, ""));
1526
  EXPECT_FALSE(isa<FPMathOperator>(ICall));
1527

1528
  Type *VITy = FixedVectorType::get(ITy, 2);
1529
  FunctionType *VIFnTy = FunctionType::get(VITy, {});
1530
  Value *VICallee = Constant::getNullValue(PtrTy);
1531
  std::unique_ptr<CallInst> VICall(CallInst::Create(VIFnTy, VICallee, {}, ""));
1532
  EXPECT_FALSE(isa<FPMathOperator>(VICall));
1533

1534
  Type *AITy = ArrayType::get(ITy, 2);
1535
  FunctionType *AIFnTy = FunctionType::get(AITy, {});
1536
  Value *AICallee = Constant::getNullValue(PtrTy);
1537
  std::unique_ptr<CallInst> AICall(CallInst::Create(AIFnTy, AICallee, {}, ""));
1538
  EXPECT_FALSE(isa<FPMathOperator>(AICall));
1539

1540
  Type *FTy = Type::getFloatTy(C);
1541
  FunctionType *FFnTy = FunctionType::get(FTy, {});
1542
  Value *FCallee = Constant::getNullValue(PtrTy);
1543
  std::unique_ptr<CallInst> FCall(CallInst::Create(FFnTy, FCallee, {}, ""));
1544
  EXPECT_TRUE(isa<FPMathOperator>(FCall));
1545

1546
  Type *VFTy = FixedVectorType::get(FTy, 2);
1547
  FunctionType *VFFnTy = FunctionType::get(VFTy, {});
1548
  Value *VFCallee = Constant::getNullValue(PtrTy);
1549
  std::unique_ptr<CallInst> VFCall(CallInst::Create(VFFnTy, VFCallee, {}, ""));
1550
  EXPECT_TRUE(isa<FPMathOperator>(VFCall));
1551

1552
  Type *AFTy = ArrayType::get(FTy, 2);
1553
  FunctionType *AFFnTy = FunctionType::get(AFTy, {});
1554
  Value *AFCallee = Constant::getNullValue(PtrTy);
1555
  std::unique_ptr<CallInst> AFCall(CallInst::Create(AFFnTy, AFCallee, {}, ""));
1556
  EXPECT_TRUE(isa<FPMathOperator>(AFCall));
1557

1558
  Type *AVFTy = ArrayType::get(VFTy, 2);
1559
  FunctionType *AVFFnTy = FunctionType::get(AVFTy, {});
1560
  Value *AVFCallee = Constant::getNullValue(PtrTy);
1561
  std::unique_ptr<CallInst> AVFCall(
1562
      CallInst::Create(AVFFnTy, AVFCallee, {}, ""));
1563
  EXPECT_TRUE(isa<FPMathOperator>(AVFCall));
1564

1565
  Type *AAVFTy = ArrayType::get(AVFTy, 2);
1566
  FunctionType *AAVFFnTy = FunctionType::get(AAVFTy, {});
1567
  Value *AAVFCallee = Constant::getNullValue(PtrTy);
1568
  std::unique_ptr<CallInst> AAVFCall(
1569
      CallInst::Create(AAVFFnTy, AAVFCallee, {}, ""));
1570
  EXPECT_TRUE(isa<FPMathOperator>(AAVFCall));
1571
}
1572

1573
TEST(InstructionsTest, FNegInstruction) {
1574
  LLVMContext Context;
1575
  Type *FltTy = Type::getFloatTy(Context);
1576
  Constant *One = ConstantFP::get(FltTy, 1.0);
1577
  BinaryOperator *FAdd = BinaryOperator::CreateFAdd(One, One);
1578
  FAdd->setHasNoNaNs(true);
1579
  UnaryOperator *FNeg = UnaryOperator::CreateFNegFMF(One, FAdd);
1580
  EXPECT_TRUE(FNeg->hasNoNaNs());
1581
  EXPECT_FALSE(FNeg->hasNoInfs());
1582
  EXPECT_FALSE(FNeg->hasNoSignedZeros());
1583
  EXPECT_FALSE(FNeg->hasAllowReciprocal());
1584
  EXPECT_FALSE(FNeg->hasAllowContract());
1585
  EXPECT_FALSE(FNeg->hasAllowReassoc());
1586
  EXPECT_FALSE(FNeg->hasApproxFunc());
1587
  FAdd->deleteValue();
1588
  FNeg->deleteValue();
1589
}
1590

1591
TEST(InstructionsTest, CallBrInstruction) {
1592
  LLVMContext Context;
1593
  std::unique_ptr<Module> M = parseIR(Context, R"(
1594
define void @foo() {
1595
entry:
1596
  callbr void asm sideeffect "// XXX: ${0:l}", "!i"()
1597
          to label %land.rhs.i [label %branch_test.exit]
1598

1599
land.rhs.i:
1600
  br label %branch_test.exit
1601

1602
branch_test.exit:
1603
  %0 = phi i1 [ true, %entry ], [ false, %land.rhs.i ]
1604
  br i1 %0, label %if.end, label %if.then
1605

1606
if.then:
1607
  ret void
1608

1609
if.end:
1610
  ret void
1611
}
1612
)");
1613
  Function *Foo = M->getFunction("foo");
1614
  auto BBs = Foo->begin();
1615
  CallBrInst &CBI = cast<CallBrInst>(BBs->front());
1616
  ++BBs;
1617
  ++BBs;
1618
  BasicBlock &BranchTestExit = *BBs;
1619
  ++BBs;
1620
  BasicBlock &IfThen = *BBs;
1621

1622
  // Test that setting the first indirect destination of callbr updates the dest
1623
  EXPECT_EQ(&BranchTestExit, CBI.getIndirectDest(0));
1624
  CBI.setIndirectDest(0, &IfThen);
1625
  EXPECT_EQ(&IfThen, CBI.getIndirectDest(0));
1626
}
1627

1628
TEST(InstructionsTest, UnaryOperator) {
1629
  LLVMContext Context;
1630
  IRBuilder<> Builder(Context);
1631
  Instruction *I = Builder.CreatePHI(Builder.getDoubleTy(), 0);
1632
  Value *F = Builder.CreateFNeg(I);
1633

1634
  EXPECT_TRUE(isa<Value>(F));
1635
  EXPECT_TRUE(isa<Instruction>(F));
1636
  EXPECT_TRUE(isa<UnaryInstruction>(F));
1637
  EXPECT_TRUE(isa<UnaryOperator>(F));
1638
  EXPECT_FALSE(isa<BinaryOperator>(F));
1639

1640
  F->deleteValue();
1641
  I->deleteValue();
1642
}
1643

1644
TEST(InstructionsTest, DropLocation) {
1645
  LLVMContext C;
1646
  std::unique_ptr<Module> M = parseIR(C,
1647
                                      R"(
1648
      declare void @callee()
1649

1650
      define void @no_parent_scope() {
1651
        call void @callee()           ; I1: Call with no location.
1652
        call void @callee(), !dbg !11 ; I2: Call with location.
1653
        ret void, !dbg !11            ; I3: Non-call with location.
1654
      }
1655

1656
      define void @with_parent_scope() !dbg !8 {
1657
        call void @callee()           ; I1: Call with no location.
1658
        call void @callee(), !dbg !11 ; I2: Call with location.
1659
        ret void, !dbg !11            ; I3: Non-call with location.
1660
      }
1661

1662
      !llvm.dbg.cu = !{!0}
1663
      !llvm.module.flags = !{!3, !4}
1664
      !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
1665
      !1 = !DIFile(filename: "t2.c", directory: "foo")
1666
      !2 = !{}
1667
      !3 = !{i32 2, !"Dwarf Version", i32 4}
1668
      !4 = !{i32 2, !"Debug Info Version", i32 3}
1669
      !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)
1670
      !9 = !DISubroutineType(types: !10)
1671
      !10 = !{null}
1672
      !11 = !DILocation(line: 2, column: 7, scope: !8, inlinedAt: !12)
1673
      !12 = !DILocation(line: 3, column: 8, scope: !8)
1674
  )");
1675
  ASSERT_TRUE(M);
1676

1677
  {
1678
    Function *NoParentScopeF =
1679
        cast<Function>(M->getNamedValue("no_parent_scope"));
1680
    BasicBlock &BB = NoParentScopeF->front();
1681

1682
    auto *I1 = BB.getFirstNonPHI();
1683
    auto *I2 = I1->getNextNode();
1684
    auto *I3 = BB.getTerminator();
1685

1686
    EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1687
    I1->dropLocation();
1688
    EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1689

1690
    EXPECT_EQ(I2->getDebugLoc().getLine(), 2U);
1691
    I2->dropLocation();
1692
    EXPECT_EQ(I1->getDebugLoc(), DebugLoc());
1693

1694
    EXPECT_EQ(I3->getDebugLoc().getLine(), 2U);
1695
    I3->dropLocation();
1696
    EXPECT_EQ(I3->getDebugLoc(), DebugLoc());
1697
  }
1698

1699
  {
1700
    Function *WithParentScopeF =
1701
        cast<Function>(M->getNamedValue("with_parent_scope"));
1702
    BasicBlock &BB = WithParentScopeF->front();
1703

1704
    auto *I2 = BB.getFirstNonPHI()->getNextNode();
1705

1706
    MDNode *Scope = cast<MDNode>(WithParentScopeF->getSubprogram());
1707
    EXPECT_EQ(I2->getDebugLoc().getLine(), 2U);
1708
    I2->dropLocation();
1709
    EXPECT_EQ(I2->getDebugLoc().getLine(), 0U);
1710
    EXPECT_EQ(I2->getDebugLoc().getScope(), Scope);
1711
    EXPECT_EQ(I2->getDebugLoc().getInlinedAt(), nullptr);
1712
  }
1713
}
1714

1715
TEST(InstructionsTest, BranchWeightOverflow) {
1716
  LLVMContext C;
1717
  std::unique_ptr<Module> M = parseIR(C,
1718
                                      R"(
1719
      declare void @callee()
1720

1721
      define void @caller() {
1722
        call void @callee(), !prof !1
1723
        ret void
1724
      }
1725

1726
      !1 = !{!"branch_weights", i32 20000}
1727
  )");
1728
  ASSERT_TRUE(M);
1729
  CallInst *CI =
1730
      cast<CallInst>(&M->getFunction("caller")->getEntryBlock().front());
1731
  uint64_t ProfWeight;
1732
  CI->extractProfTotalWeight(ProfWeight);
1733
  ASSERT_EQ(ProfWeight, 20000U);
1734
  CI->updateProfWeight(10000000, 1);
1735
  CI->extractProfTotalWeight(ProfWeight);
1736
  ASSERT_EQ(ProfWeight, UINT32_MAX);
1737
}
1738

1739
TEST(InstructionsTest, AllocaInst) {
1740
  LLVMContext Ctx;
1741
  std::unique_ptr<Module> M = parseIR(Ctx, R"(
1742
      %T = type { i64, [3 x i32]}
1743
      define void @f(i32 %n) {
1744
      entry:
1745
        %A = alloca i32, i32 1
1746
        %B = alloca i32, i32 4
1747
        %C = alloca i32, i32 %n
1748
        %D = alloca <8 x double>
1749
        %E = alloca <vscale x 8 x double>
1750
        %F = alloca [2 x half]
1751
        %G = alloca [2 x [3 x i128]]
1752
        %H = alloca %T
1753
        %I = alloca i32, i64 9223372036854775807
1754
        ret void
1755
      }
1756
    )");
1757
  const DataLayout &DL = M->getDataLayout();
1758
  ASSERT_TRUE(M);
1759
  Function *Fun = cast<Function>(M->getNamedValue("f"));
1760
  BasicBlock &BB = Fun->front();
1761
  auto It = BB.begin();
1762
  AllocaInst &A = cast<AllocaInst>(*It++);
1763
  AllocaInst &B = cast<AllocaInst>(*It++);
1764
  AllocaInst &C = cast<AllocaInst>(*It++);
1765
  AllocaInst &D = cast<AllocaInst>(*It++);
1766
  AllocaInst &E = cast<AllocaInst>(*It++);
1767
  AllocaInst &F = cast<AllocaInst>(*It++);
1768
  AllocaInst &G = cast<AllocaInst>(*It++);
1769
  AllocaInst &H = cast<AllocaInst>(*It++);
1770
  AllocaInst &I = cast<AllocaInst>(*It++);
1771
  EXPECT_EQ(A.getAllocationSizeInBits(DL), TypeSize::getFixed(32));
1772
  EXPECT_EQ(B.getAllocationSizeInBits(DL), TypeSize::getFixed(128));
1773
  EXPECT_FALSE(C.getAllocationSizeInBits(DL));
1774
  EXPECT_EQ(D.getAllocationSizeInBits(DL), TypeSize::getFixed(512));
1775
  EXPECT_EQ(E.getAllocationSizeInBits(DL), TypeSize::getScalable(512));
1776
  EXPECT_EQ(F.getAllocationSizeInBits(DL), TypeSize::getFixed(32));
1777
  EXPECT_EQ(G.getAllocationSizeInBits(DL), TypeSize::getFixed(768));
1778
  EXPECT_EQ(H.getAllocationSizeInBits(DL), TypeSize::getFixed(160));
1779
  EXPECT_FALSE(I.getAllocationSizeInBits(DL));
1780
}
1781

1782
TEST(InstructionsTest, InsertAtBegin) {
1783
  LLVMContext Ctx;
1784
  std::unique_ptr<Module> M = parseIR(Ctx, R"(
1785
    define void @f(i32 %a, i32 %b) {
1786
     entry:
1787
       ret void
1788
    }
1789
)");
1790
  Function *F = &*M->begin();
1791
  Argument *ArgA = F->getArg(0);
1792
  Argument *ArgB = F->getArg(1);
1793
  BasicBlock *BB = &*F->begin();
1794
  Instruction *Ret = &*BB->begin();
1795
  Instruction *I = BinaryOperator::CreateAdd(ArgA, ArgB);
1796
  auto It = I->insertInto(BB, BB->begin());
1797
  EXPECT_EQ(&*It, I);
1798
  EXPECT_EQ(I->getNextNode(), Ret);
1799
}
1800

1801
TEST(InstructionsTest, InsertAtEnd) {
1802
  LLVMContext Ctx;
1803
  std::unique_ptr<Module> M = parseIR(Ctx, R"(
1804
    define void @f(i32 %a, i32 %b) {
1805
     entry:
1806
       ret void
1807
    }
1808
)");
1809
  Function *F = &*M->begin();
1810
  Argument *ArgA = F->getArg(0);
1811
  Argument *ArgB = F->getArg(1);
1812
  BasicBlock *BB = &*F->begin();
1813
  Instruction *Ret = &*BB->begin();
1814
  Instruction *I = BinaryOperator::CreateAdd(ArgA, ArgB);
1815
  auto It = I->insertInto(BB, BB->end());
1816
  EXPECT_EQ(&*It, I);
1817
  EXPECT_EQ(Ret->getNextNode(), I);
1818
}
1819

1820
} // end anonymous namespace
1821
} // end namespace llvm
1822

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.