LLVM  16.0.0git
Instructions.cpp
Go to the documentation of this file.
1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
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 // This file implements all of the non-inline methods for the LLVM instruction
10 // classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/Instructions.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/IR/Attributes.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/MDBuilder.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/TypeSize.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstdint>
45 #include <vector>
46 
47 using namespace llvm;
48 
50  "disable-i2p-p2i-opt", cl::init(false),
51  cl::desc("Disables inttoptr/ptrtoint roundtrip optimization"));
52 
53 //===----------------------------------------------------------------------===//
54 // AllocaInst Class
55 //===----------------------------------------------------------------------===//
56 
59  TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType());
60  if (isArrayAllocation()) {
61  auto *C = dyn_cast<ConstantInt>(getArraySize());
62  if (!C)
63  return None;
64  assert(!Size.isScalable() && "Array elements cannot have a scalable size");
65  Size *= C->getZExtValue();
66  }
67  return Size;
68 }
69 
70 //===----------------------------------------------------------------------===//
71 // SelectInst Class
72 //===----------------------------------------------------------------------===//
73 
74 /// areInvalidOperands - Return a string if the specified operands are invalid
75 /// for a select operation, otherwise return null.
76 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
77  if (Op1->getType() != Op2->getType())
78  return "both values to select must have same type";
79 
80  if (Op1->getType()->isTokenTy())
81  return "select values cannot have token type";
82 
83  if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
84  // Vector select.
85  if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
86  return "vector select condition element type must be i1";
87  VectorType *ET = dyn_cast<VectorType>(Op1->getType());
88  if (!ET)
89  return "selected values for vector select must be vectors";
90  if (ET->getElementCount() != VT->getElementCount())
91  return "vector select requires selected vectors to have "
92  "the same vector length as select condition";
93  } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
94  return "select condition must be i1 or <n x i1>";
95  }
96  return nullptr;
97 }
98 
99 //===----------------------------------------------------------------------===//
100 // PHINode Class
101 //===----------------------------------------------------------------------===//
102 
103 PHINode::PHINode(const PHINode &PN)
104  : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
105  ReservedSpace(PN.getNumOperands()) {
107  std::copy(PN.op_begin(), PN.op_end(), op_begin());
108  std::copy(PN.block_begin(), PN.block_end(), block_begin());
110 }
111 
112 // removeIncomingValue - Remove an incoming value. This is useful if a
113 // predecessor basic block is deleted.
114 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
115  Value *Removed = getIncomingValue(Idx);
116 
117  // Move everything after this operand down.
118  //
119  // FIXME: we could just swap with the end of the list, then erase. However,
120  // clients might not expect this to happen. The code as it is thrashes the
121  // use/def lists, which is kinda lame.
122  std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
123  std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
124 
125  // Nuke the last value.
126  Op<-1>().set(nullptr);
128 
129  // If the PHI node is dead, because it has zero entries, nuke it now.
130  if (getNumOperands() == 0 && DeletePHIIfEmpty) {
131  // If anyone is using this PHI, make them use a dummy value instead...
133  eraseFromParent();
134  }
135  return Removed;
136 }
137 
138 /// growOperands - grow operands - This grows the operand list in response
139 /// to a push_back style of operation. This grows the number of ops by 1.5
140 /// times.
141 ///
142 void PHINode::growOperands() {
143  unsigned e = getNumOperands();
144  unsigned NumOps = e + e / 2;
145  if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
146 
147  ReservedSpace = NumOps;
148  growHungoffUses(ReservedSpace, /* IsPhi */ true);
149 }
150 
151 /// hasConstantValue - If the specified PHI node always merges together the same
152 /// value, return the value, otherwise return null.
154  // Exploit the fact that phi nodes always have at least one entry.
155  Value *ConstantValue = getIncomingValue(0);
156  for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
157  if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
158  if (ConstantValue != this)
159  return nullptr; // Incoming values not all the same.
160  // The case where the first value is this PHI.
161  ConstantValue = getIncomingValue(i);
162  }
163  if (ConstantValue == this)
164  return UndefValue::get(getType());
165  return ConstantValue;
166 }
167 
168 /// hasConstantOrUndefValue - Whether the specified PHI node always merges
169 /// together the same value, assuming that undefs result in the same value as
170 /// non-undefs.
171 /// Unlike \ref hasConstantValue, this does not return a value because the
172 /// unique non-undef incoming value need not dominate the PHI node.
174  Value *ConstantValue = nullptr;
175  for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
176  Value *Incoming = getIncomingValue(i);
177  if (Incoming != this && !isa<UndefValue>(Incoming)) {
178  if (ConstantValue && ConstantValue != Incoming)
179  return false;
180  ConstantValue = Incoming;
181  }
182  }
183  return true;
184 }
185 
186 //===----------------------------------------------------------------------===//
187 // LandingPadInst Implementation
188 //===----------------------------------------------------------------------===//
189 
190 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
191  const Twine &NameStr, Instruction *InsertBefore)
192  : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
193  init(NumReservedValues, NameStr);
194 }
195 
196 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
197  const Twine &NameStr, BasicBlock *InsertAtEnd)
198  : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
199  init(NumReservedValues, NameStr);
200 }
201 
202 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
203  : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
204  LP.getNumOperands()),
205  ReservedSpace(LP.getNumOperands()) {
207  Use *OL = getOperandList();
208  const Use *InOL = LP.getOperandList();
209  for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
210  OL[I] = InOL[I];
211 
212  setCleanup(LP.isCleanup());
213 }
214 
215 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
216  const Twine &NameStr,
217  Instruction *InsertBefore) {
218  return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
219 }
220 
221 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
222  const Twine &NameStr,
223  BasicBlock *InsertAtEnd) {
224  return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
225 }
226 
227 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
228  ReservedSpace = NumReservedValues;
230  allocHungoffUses(ReservedSpace);
231  setName(NameStr);
232  setCleanup(false);
233 }
234 
235 /// growOperands - grow operands - This grows the operand list in response to a
236 /// push_back style of operation. This grows the number of ops by 2 times.
237 void LandingPadInst::growOperands(unsigned Size) {
238  unsigned e = getNumOperands();
239  if (ReservedSpace >= e + Size) return;
240  ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
241  growHungoffUses(ReservedSpace);
242 }
243 
245  unsigned OpNo = getNumOperands();
246  growOperands(1);
247  assert(OpNo < ReservedSpace && "Growing didn't work!");
249  getOperandList()[OpNo] = Val;
250 }
251 
252 //===----------------------------------------------------------------------===//
253 // CallBase Implementation
254 //===----------------------------------------------------------------------===//
255 
257  Instruction *InsertPt) {
258  switch (CB->getOpcode()) {
259  case Instruction::Call:
260  return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
261  case Instruction::Invoke:
262  return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
263  case Instruction::CallBr:
264  return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
265  default:
266  llvm_unreachable("Unknown CallBase sub-class!");
267  }
268 }
269 
271  Instruction *InsertPt) {
273  for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
274  auto ChildOB = CI->getOperandBundleAt(i);
275  if (ChildOB.getTagName() != OpB.getTag())
276  OpDefs.emplace_back(ChildOB);
277  }
278  OpDefs.emplace_back(OpB);
279  return CallBase::Create(CI, OpDefs, InsertPt);
280 }
281 
282 
284 
286  assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
287  return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
288 }
289 
291  const Value *V = getCalledOperand();
292  if (isa<Function>(V) || isa<Constant>(V))
293  return false;
294  return !isInlineAsm();
295 }
296 
297 /// Tests if this call site must be tail call optimized. Only a CallInst can
298 /// be tail call optimized.
300  if (auto *CI = dyn_cast<CallInst>(this))
301  return CI->isMustTailCall();
302  return false;
303 }
304 
305 /// Tests if this call site is marked as a tail call.
306 bool CallBase::isTailCall() const {
307  if (auto *CI = dyn_cast<CallInst>(this))
308  return CI->isTailCall();
309  return false;
310 }
311 
313  if (auto *F = getCalledFunction())
314  return F->getIntrinsicID();
316 }
317 
319  if (hasRetAttr(Attribute::NonNull))
320  return true;
321 
322  if (getRetDereferenceableBytes() > 0 &&
323  !NullPointerIsDefined(getCaller(), getType()->getPointerAddressSpace()))
324  return true;
325 
326  return false;
327 }
328 
330  unsigned Index;
331 
334  if (const Function *F = getCalledFunction())
335  if (F->getAttributes().hasAttrSomewhere(Kind, &Index))
337 
338  return nullptr;
339 }
340 
341 /// Determine whether the argument or parameter has the given attribute.
342 bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
343  assert(ArgNo < arg_size() && "Param index out of bounds!");
344 
345  if (Attrs.hasParamAttr(ArgNo, Kind))
346  return true;
347  if (const Function *F = getCalledFunction())
348  return F->getAttributes().hasParamAttr(ArgNo, Kind);
349  return false;
350 }
351 
352 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
353  Value *V = getCalledOperand();
354  if (auto *CE = dyn_cast<ConstantExpr>(V))
355  if (CE->getOpcode() == BitCast)
356  V = CE->getOperand(0);
357 
358  if (auto *F = dyn_cast<Function>(V))
359  return F->getAttributes().hasFnAttr(Kind);
360 
361  return false;
362 }
363 
364 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
365  Value *V = getCalledOperand();
366  if (auto *CE = dyn_cast<ConstantExpr>(V))
367  if (CE->getOpcode() == BitCast)
368  V = CE->getOperand(0);
369 
370  if (auto *F = dyn_cast<Function>(V))
371  return F->getAttributes().hasFnAttr(Kind);
372 
373  return false;
374 }
375 
376 template <typename AK>
377 Attribute CallBase::getFnAttrOnCalledFunction(AK Kind) const {
378  // Operand bundles override attributes on the called function, but don't
379  // override attributes directly present on the call instruction.
381  return Attribute();
382  Value *V = getCalledOperand();
383  if (auto *CE = dyn_cast<ConstantExpr>(V))
384  if (CE->getOpcode() == BitCast)
385  V = CE->getOperand(0);
386 
387  if (auto *F = dyn_cast<Function>(V))
388  return F->getAttributes().getFnAttr(Kind);
389 
390  return Attribute();
391 }
392 
393 template Attribute
394 CallBase::getFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
395 template Attribute CallBase::getFnAttrOnCalledFunction(StringRef Kind) const;
396 
398  SmallVectorImpl<OperandBundleDef> &Defs) const {
399  for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
401 }
402 
405  const unsigned BeginIndex) {
406  auto It = op_begin() + BeginIndex;
407  for (auto &B : Bundles)
408  It = std::copy(B.input_begin(), B.input_end(), It);
409 
410  auto *ContextImpl = getContext().pImpl;
411  auto BI = Bundles.begin();
412  unsigned CurrentIndex = BeginIndex;
413 
414  for (auto &BOI : bundle_op_infos()) {
415  assert(BI != Bundles.end() && "Incorrect allocation?");
416 
417  BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
418  BOI.Begin = CurrentIndex;
419  BOI.End = CurrentIndex + BI->input_size();
420  CurrentIndex = BOI.End;
421  BI++;
422  }
423 
424  assert(BI == Bundles.end() && "Incorrect allocation?");
425 
426  return It;
427 }
428 
430  /// When there isn't many bundles, we do a simple linear search.
431  /// Else fallback to a binary-search that use the fact that bundles usually
432  /// have similar number of argument to get faster convergence.
434  for (auto &BOI : bundle_op_infos())
435  if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
436  return BOI;
437 
438  llvm_unreachable("Did not find operand bundle for operand!");
439  }
440 
441  assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
443  OpIdx < std::prev(bundle_op_info_end())->End &&
444  "The Idx isn't in the operand bundle");
445 
446  /// We need a decimal number below and to prevent using floating point numbers
447  /// we use an intergal value multiplied by this constant.
448  constexpr unsigned NumberScaling = 1024;
449 
452  bundle_op_iterator Current = Begin;
453 
454  while (Begin != End) {
455  unsigned ScaledOperandPerBundle =
456  NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
457  Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
458  ScaledOperandPerBundle);
459  if (Current >= End)
460  Current = std::prev(End);
461  assert(Current < End && Current >= Begin &&
462  "the operand bundle doesn't cover every value in the range");
463  if (OpIdx >= Current->Begin && OpIdx < Current->End)
464  break;
465  if (OpIdx >= Current->End)
466  Begin = Current + 1;
467  else
468  End = Current;
469  }
470 
471  assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
472  "the operand bundle doesn't cover every value in the range");
473  return *Current;
474 }
475 
478  Instruction *InsertPt) {
479  if (CB->getOperandBundle(ID))
480  return CB;
481 
483  CB->getOperandBundlesAsDefs(Bundles);
484  Bundles.push_back(OB);
485  return Create(CB, Bundles, InsertPt);
486 }
487 
489  Instruction *InsertPt) {
491  bool CreateNew = false;
492 
493  for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
494  auto Bundle = CB->getOperandBundleAt(I);
495  if (Bundle.getTagID() == ID) {
496  CreateNew = true;
497  continue;
498  }
499  Bundles.emplace_back(Bundle);
500  }
501 
502  return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
503 }
504 
506  // Implementation note: this is a conservative implementation of operand
507  // bundle semantics, where *any* non-assume operand bundle (other than
508  // ptrauth) forces a callsite to be at least readonly.
511  getIntrinsicID() != Intrinsic::assume;
512 }
513 
514 //===----------------------------------------------------------------------===//
515 // CallInst Implementation
516 //===----------------------------------------------------------------------===//
517 
518 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
519  ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
520  this->FTy = FTy;
521  assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
522  "NumOperands not set up?");
523 
524 #ifndef NDEBUG
525  assert((Args.size() == FTy->getNumParams() ||
526  (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
527  "Calling a function with bad signature!");
528 
529  for (unsigned i = 0; i != Args.size(); ++i)
530  assert((i >= FTy->getNumParams() ||
531  FTy->getParamType(i) == Args[i]->getType()) &&
532  "Calling a function with a bad signature!");
533 #endif
534 
535  // Set operands in order of their index to match use-list-order
536  // prediction.
538  setCalledOperand(Func);
539 
540  auto It = populateBundleOperandInfos(Bundles, Args.size());
541  (void)It;
542  assert(It + 1 == op_end() && "Should add up!");
543 
544  setName(NameStr);
545 }
546 
547 void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
548  this->FTy = FTy;
549  assert(getNumOperands() == 1 && "NumOperands not set up?");
550  setCalledOperand(Func);
551 
552  assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
553 
554  setName(NameStr);
555 }
556 
557 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
558  Instruction *InsertBefore)
559  : CallBase(Ty->getReturnType(), Instruction::Call,
560  OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
561  init(Ty, Func, Name);
562 }
563 
564 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
565  BasicBlock *InsertAtEnd)
566  : CallBase(Ty->getReturnType(), Instruction::Call,
567  OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
568  init(Ty, Func, Name);
569 }
570 
571 CallInst::CallInst(const CallInst &CI)
572  : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
573  OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
574  CI.getNumOperands()) {
575  setTailCallKind(CI.getTailCallKind());
577 
578  std::copy(CI.op_begin(), CI.op_end(), op_begin());
582 }
583 
585  Instruction *InsertPt) {
586  std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
587 
588  auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
589  Args, OpB, CI->getName(), InsertPt);
590  NewCI->setTailCallKind(CI->getTailCallKind());
591  NewCI->setCallingConv(CI->getCallingConv());
592  NewCI->SubclassOptionalData = CI->SubclassOptionalData;
593  NewCI->setAttributes(CI->getAttributes());
594  NewCI->setDebugLoc(CI->getDebugLoc());
595  return NewCI;
596 }
597 
598 // Update profile weight for call instruction by scaling it using the ratio
599 // of S/T. The meaning of "branch_weights" meta data for call instruction is
600 // transfered to represent call count.
602  auto *ProfileData = getMetadata(LLVMContext::MD_prof);
603  if (ProfileData == nullptr)
604  return;
605 
606  auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
607  if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
608  !ProfDataName->getString().equals("VP")))
609  return;
610 
611  if (T == 0) {
612  LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
613  "div by 0. Ignoring. Likely the function "
614  << getParent()->getParent()->getName()
615  << " has 0 entry count, and contains call instructions "
616  "with non-zero prof info.");
617  return;
618  }
619 
620  MDBuilder MDB(getContext());
622  Vals.push_back(ProfileData->getOperand(0));
623  APInt APS(128, S), APT(128, T);
624  if (ProfDataName->getString().equals("branch_weights") &&
625  ProfileData->getNumOperands() > 0) {
626  // Using APInt::div may be expensive, but most cases should fit 64 bits.
627  APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
628  ->getValue()
629  .getZExtValue());
630  Val *= APS;
631  Vals.push_back(MDB.createConstant(
633  Val.udiv(APT).getLimitedValue(UINT32_MAX))));
634  } else if (ProfDataName->getString().equals("VP"))
635  for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
636  // The first value is the key of the value profile, which will not change.
637  Vals.push_back(ProfileData->getOperand(i));
638  uint64_t Count =
639  mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
640  ->getValue()
641  .getZExtValue();
642  // Don't scale the magic number.
643  if (Count == NOMORE_ICP_MAGICNUM) {
644  Vals.push_back(ProfileData->getOperand(i + 1));
645  continue;
646  }
647  // Using APInt::div may be expensive, but most cases should fit 64 bits.
648  APInt Val(128, Count);
649  Val *= APS;
650  Vals.push_back(MDB.createConstant(
652  Val.udiv(APT).getLimitedValue())));
653  }
654  setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
655 }
656 
657 /// IsConstantOne - Return true only if val is constant int 1
658 static bool IsConstantOne(Value *val) {
659  assert(val && "IsConstantOne does not work with nullptr val");
660  const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
661  return CVal && CVal->isOne();
662 }
663 
664 static Instruction *createMalloc(Instruction *InsertBefore,
665  BasicBlock *InsertAtEnd, Type *IntPtrTy,
666  Type *AllocTy, Value *AllocSize,
667  Value *ArraySize,
669  Function *MallocF, const Twine &Name) {
670  assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
671  "createMalloc needs either InsertBefore or InsertAtEnd");
672 
673  // malloc(type) becomes:
674  // bitcast (i8* malloc(typeSize)) to type*
675  // malloc(type, arraySize) becomes:
676  // bitcast (i8* malloc(typeSize*arraySize)) to type*
677  if (!ArraySize)
678  ArraySize = ConstantInt::get(IntPtrTy, 1);
679  else if (ArraySize->getType() != IntPtrTy) {
680  if (InsertBefore)
681  ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
682  "", InsertBefore);
683  else
684  ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
685  "", InsertAtEnd);
686  }
687 
688  if (!IsConstantOne(ArraySize)) {
689  if (IsConstantOne(AllocSize)) {
690  AllocSize = ArraySize; // Operand * 1 = Operand
691  } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
692  Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
693  false /*ZExt*/);
694  // Malloc arg is constant product of type size and array size
695  AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
696  } else {
697  // Multiply type size by the array size...
698  if (InsertBefore)
699  AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
700  "mallocsize", InsertBefore);
701  else
702  AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
703  "mallocsize", InsertAtEnd);
704  }
705  }
706 
707  assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
708  // Create the call to Malloc.
709  BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
710  Module *M = BB->getParent()->getParent();
711  Type *BPTy = Type::getInt8PtrTy(BB->getContext());
712  FunctionCallee MallocFunc = MallocF;
713  if (!MallocFunc)
714  // prototype malloc as "void *malloc(size_t)"
715  MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
716  PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
717  CallInst *MCall = nullptr;
718  Instruction *Result = nullptr;
719  if (InsertBefore) {
720  MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
721  InsertBefore);
722  Result = MCall;
723  if (Result->getType() != AllocPtrType)
724  // Create a cast instruction to convert to the right type...
725  Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
726  } else {
727  MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
728  Result = MCall;
729  if (Result->getType() != AllocPtrType) {
730  InsertAtEnd->getInstList().push_back(MCall);
731  // Create a cast instruction to convert to the right type...
732  Result = new BitCastInst(MCall, AllocPtrType, Name);
733  }
734  }
735  MCall->setTailCall();
736  if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
737  MCall->setCallingConv(F->getCallingConv());
738  if (!F->returnDoesNotAlias())
739  F->setReturnDoesNotAlias();
740  }
741  assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
742 
743  return Result;
744 }
745 
746 /// CreateMalloc - Generate the IR for a call to malloc:
747 /// 1. Compute the malloc call's argument as the specified type's size,
748 /// possibly multiplied by the array size if the array size is not
749 /// constant 1.
750 /// 2. Call malloc with that argument.
751 /// 3. Bitcast the result of the malloc call to the specified type.
753  Type *IntPtrTy, Type *AllocTy,
754  Value *AllocSize, Value *ArraySize,
755  Function *MallocF,
756  const Twine &Name) {
757  return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
758  ArraySize, None, MallocF, Name);
759 }
761  Type *IntPtrTy, Type *AllocTy,
762  Value *AllocSize, Value *ArraySize,
764  Function *MallocF,
765  const Twine &Name) {
766  return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
767  ArraySize, OpB, MallocF, Name);
768 }
769 
770 /// CreateMalloc - Generate the IR for a call to malloc:
771 /// 1. Compute the malloc call's argument as the specified type's size,
772 /// possibly multiplied by the array size if the array size is not
773 /// constant 1.
774 /// 2. Call malloc with that argument.
775 /// 3. Bitcast the result of the malloc call to the specified type.
776 /// Note: This function does not add the bitcast to the basic block, that is the
777 /// responsibility of the caller.
779  Type *IntPtrTy, Type *AllocTy,
780  Value *AllocSize, Value *ArraySize,
781  Function *MallocF, const Twine &Name) {
782  return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
783  ArraySize, None, MallocF, Name);
784 }
786  Type *IntPtrTy, Type *AllocTy,
787  Value *AllocSize, Value *ArraySize,
789  Function *MallocF, const Twine &Name) {
790  return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
791  ArraySize, OpB, MallocF, Name);
792 }
793 
796  Instruction *InsertBefore,
797  BasicBlock *InsertAtEnd) {
798  assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
799  "createFree needs either InsertBefore or InsertAtEnd");
800  assert(Source->getType()->isPointerTy() &&
801  "Can not free something of nonpointer type!");
802 
803  BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
804  Module *M = BB->getParent()->getParent();
805 
806  Type *VoidTy = Type::getVoidTy(M->getContext());
807  Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
808  // prototype free as "void free(void*)"
809  FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
810  CallInst *Result = nullptr;
811  Value *PtrCast = Source;
812  if (InsertBefore) {
813  if (Source->getType() != IntPtrTy)
814  PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
815  Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
816  } else {
817  if (Source->getType() != IntPtrTy)
818  PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
819  Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
820  }
821  Result->setTailCall();
822  if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
823  Result->setCallingConv(F->getCallingConv());
824 
825  return Result;
826 }
827 
828 /// CreateFree - Generate the IR for a call to the builtin free function.
830  return createFree(Source, None, InsertBefore, nullptr);
831 }
834  Instruction *InsertBefore) {
835  return createFree(Source, Bundles, InsertBefore, nullptr);
836 }
837 
838 /// CreateFree - Generate the IR for a call to the builtin free function.
839 /// Note: This function does not add the call to the basic block, that is the
840 /// responsibility of the caller.
842  Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
843  assert(FreeCall && "CreateFree did not create a CallInst");
844  return FreeCall;
845 }
848  BasicBlock *InsertAtEnd) {
849  Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
850  assert(FreeCall && "CreateFree did not create a CallInst");
851  return FreeCall;
852 }
853 
854 //===----------------------------------------------------------------------===//
855 // InvokeInst Implementation
856 //===----------------------------------------------------------------------===//
857 
858 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
859  BasicBlock *IfException, ArrayRef<Value *> Args,
861  const Twine &NameStr) {
862  this->FTy = FTy;
863 
864  assert((int)getNumOperands() ==
865  ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
866  "NumOperands not set up?");
867 
868 #ifndef NDEBUG
869  assert(((Args.size() == FTy->getNumParams()) ||
870  (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
871  "Invoking a function with bad signature");
872 
873  for (unsigned i = 0, e = Args.size(); i != e; i++)
874  assert((i >= FTy->getNumParams() ||
875  FTy->getParamType(i) == Args[i]->getType()) &&
876  "Invoking a function with a bad signature!");
877 #endif
878 
879  // Set operands in order of their index to match use-list-order
880  // prediction.
882  setNormalDest(IfNormal);
883  setUnwindDest(IfException);
884  setCalledOperand(Fn);
885 
886  auto It = populateBundleOperandInfos(Bundles, Args.size());
887  (void)It;
888  assert(It + 3 == op_end() && "Should add up!");
889 
890  setName(NameStr);
891 }
892 
893 InvokeInst::InvokeInst(const InvokeInst &II)
894  : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
895  OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
896  II.getNumOperands()) {
898  std::copy(II.op_begin(), II.op_end(), op_begin());
902 }
903 
905  Instruction *InsertPt) {
906  std::vector<Value *> Args(II->arg_begin(), II->arg_end());
907 
908  auto *NewII = InvokeInst::Create(
909  II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
910  II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
911  NewII->setCallingConv(II->getCallingConv());
912  NewII->SubclassOptionalData = II->SubclassOptionalData;
913  NewII->setAttributes(II->getAttributes());
914  NewII->setDebugLoc(II->getDebugLoc());
915  return NewII;
916 }
917 
919  return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
920 }
921 
922 //===----------------------------------------------------------------------===//
923 // CallBrInst Implementation
924 //===----------------------------------------------------------------------===//
925 
926 void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
927  ArrayRef<BasicBlock *> IndirectDests,
930  const Twine &NameStr) {
931  this->FTy = FTy;
932 
933  assert((int)getNumOperands() ==
934  ComputeNumOperands(Args.size(), IndirectDests.size(),
935  CountBundleInputs(Bundles)) &&
936  "NumOperands not set up?");
937 
938 #ifndef NDEBUG
939  assert(((Args.size() == FTy->getNumParams()) ||
940  (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
941  "Calling a function with bad signature");
942 
943  for (unsigned i = 0, e = Args.size(); i != e; i++)
944  assert((i >= FTy->getNumParams() ||
945  FTy->getParamType(i) == Args[i]->getType()) &&
946  "Calling a function with a bad signature!");
947 #endif
948 
949  // Set operands in order of their index to match use-list-order
950  // prediction.
951  std::copy(Args.begin(), Args.end(), op_begin());
952  NumIndirectDests = IndirectDests.size();
953  setDefaultDest(Fallthrough);
954  for (unsigned i = 0; i != NumIndirectDests; ++i)
955  setIndirectDest(i, IndirectDests[i]);
956  setCalledOperand(Fn);
957 
958  auto It = populateBundleOperandInfos(Bundles, Args.size());
959  (void)It;
960  assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
961 
962  setName(NameStr);
963 }
964 
965 CallBrInst::CallBrInst(const CallBrInst &CBI)
966  : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
967  OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
968  CBI.getNumOperands()) {
970  std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
974  NumIndirectDests = CBI.NumIndirectDests;
975 }
976 
978  Instruction *InsertPt) {
979  std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
980 
981  auto *NewCBI = CallBrInst::Create(
982  CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
983  CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
984  NewCBI->setCallingConv(CBI->getCallingConv());
985  NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
986  NewCBI->setAttributes(CBI->getAttributes());
987  NewCBI->setDebugLoc(CBI->getDebugLoc());
988  NewCBI->NumIndirectDests = CBI->NumIndirectDests;
989  return NewCBI;
990 }
991 
992 //===----------------------------------------------------------------------===//
993 // ReturnInst Implementation
994 //===----------------------------------------------------------------------===//
995 
996 ReturnInst::ReturnInst(const ReturnInst &RI)
997  : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
998  OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
999  RI.getNumOperands()) {
1000  if (RI.getNumOperands())
1001  Op<0>() = RI.Op<0>();
1003 }
1004 
1005 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
1006  : Instruction(Type::getVoidTy(C), Instruction::Ret,
1007  OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
1008  InsertBefore) {
1009  if (retVal)
1010  Op<0>() = retVal;
1011 }
1012 
1013 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
1014  : Instruction(Type::getVoidTy(C), Instruction::Ret,
1015  OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
1016  InsertAtEnd) {
1017  if (retVal)
1018  Op<0>() = retVal;
1019 }
1020 
1021 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1022  : Instruction(Type::getVoidTy(Context), Instruction::Ret,
1023  OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {}
1024 
1025 //===----------------------------------------------------------------------===//
1026 // ResumeInst Implementation
1027 //===----------------------------------------------------------------------===//
1028 
1029 ResumeInst::ResumeInst(const ResumeInst &RI)
1030  : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
1031  OperandTraits<ResumeInst>::op_begin(this), 1) {
1032  Op<0>() = RI.Op<0>();
1033 }
1034 
1035 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
1036  : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
1037  OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
1038  Op<0>() = Exn;
1039 }
1040 
1041 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
1042  : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
1043  OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
1044  Op<0>() = Exn;
1045 }
1046 
1047 //===----------------------------------------------------------------------===//
1048 // CleanupReturnInst Implementation
1049 //===----------------------------------------------------------------------===//
1050 
1051 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
1052  : Instruction(CRI.getType(), Instruction::CleanupRet,
1054  CRI.getNumOperands(),
1055  CRI.getNumOperands()) {
1056  setSubclassData<Instruction::OpaqueField>(
1058  Op<0>() = CRI.Op<0>();
1059  if (CRI.hasUnwindDest())
1060  Op<1>() = CRI.Op<1>();
1061 }
1062 
1063 void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
1064  if (UnwindBB)
1065  setSubclassData<UnwindDestField>(true);
1066 
1067  Op<0>() = CleanupPad;
1068  if (UnwindBB)
1069  Op<1>() = UnwindBB;
1070 }
1071 
1072 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
1073  unsigned Values, Instruction *InsertBefore)
1074  : Instruction(Type::getVoidTy(CleanupPad->getContext()),
1075  Instruction::CleanupRet,
1076  OperandTraits<CleanupReturnInst>::op_end(this) - Values,
1077  Values, InsertBefore) {
1078  init(CleanupPad, UnwindBB);
1079 }
1080 
1081 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
1082  unsigned Values, BasicBlock *InsertAtEnd)
1083  : Instruction(Type::getVoidTy(CleanupPad->getContext()),
1084  Instruction::CleanupRet,
1085  OperandTraits<CleanupReturnInst>::op_end(this) - Values,
1086  Values, InsertAtEnd) {
1087  init(CleanupPad, UnwindBB);
1088 }
1089 
1090 //===----------------------------------------------------------------------===//
1091 // CatchReturnInst Implementation
1092 //===----------------------------------------------------------------------===//
1093 void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
1094  Op<0>() = CatchPad;
1095  Op<1>() = BB;
1096 }
1097 
1098 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
1099  : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
1100  OperandTraits<CatchReturnInst>::op_begin(this), 2) {
1101  Op<0>() = CRI.Op<0>();
1102  Op<1>() = CRI.Op<1>();
1103 }
1104 
1105 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
1106  Instruction *InsertBefore)
1107  : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
1108  OperandTraits<CatchReturnInst>::op_begin(this), 2,
1109  InsertBefore) {
1110  init(CatchPad, BB);
1111 }
1112 
1113 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
1114  BasicBlock *InsertAtEnd)
1115  : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
1116  OperandTraits<CatchReturnInst>::op_begin(this), 2,
1117  InsertAtEnd) {
1118  init(CatchPad, BB);
1119 }
1120 
1121 //===----------------------------------------------------------------------===//
1122 // CatchSwitchInst Implementation
1123 //===----------------------------------------------------------------------===//
1124 
1125 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1126  unsigned NumReservedValues,
1127  const Twine &NameStr,
1128  Instruction *InsertBefore)
1129  : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
1130  InsertBefore) {
1131  if (UnwindDest)
1132  ++NumReservedValues;
1133  init(ParentPad, UnwindDest, NumReservedValues + 1);
1134  setName(NameStr);
1135 }
1136 
1137 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1138  unsigned NumReservedValues,
1139  const Twine &NameStr, BasicBlock *InsertAtEnd)
1140  : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
1141  InsertAtEnd) {
1142  if (UnwindDest)
1143  ++NumReservedValues;
1144  init(ParentPad, UnwindDest, NumReservedValues + 1);
1145  setName(NameStr);
1146 }
1147 
1148 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
1149  : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr,
1150  CSI.getNumOperands()) {
1151  init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
1152  setNumHungOffUseOperands(ReservedSpace);
1153  Use *OL = getOperandList();
1154  const Use *InOL = CSI.getOperandList();
1155  for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
1156  OL[I] = InOL[I];
1157 }
1158 
1159 void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
1160  unsigned NumReservedValues) {
1161  assert(ParentPad && NumReservedValues);
1162 
1163  ReservedSpace = NumReservedValues;
1164  setNumHungOffUseOperands(UnwindDest ? 2 : 1);
1165  allocHungoffUses(ReservedSpace);
1166 
1167  Op<0>() = ParentPad;
1168  if (UnwindDest) {
1169  setSubclassData<UnwindDestField>(true);
1170  setUnwindDest(UnwindDest);
1171  }
1172 }
1173 
1174 /// growOperands - grow operands - This grows the operand list in response to a
1175 /// push_back style of operation. This grows the number of ops by 2 times.
1176 void CatchSwitchInst::growOperands(unsigned Size) {
1177  unsigned NumOperands = getNumOperands();
1178  assert(NumOperands >= 1);
1179  if (ReservedSpace >= NumOperands + Size)
1180  return;
1181  ReservedSpace = (NumOperands + Size / 2) * 2;
1182  growHungoffUses(ReservedSpace);
1183 }
1184 
1186  unsigned OpNo = getNumOperands();
1187  growOperands(1);
1188  assert(OpNo < ReservedSpace && "Growing didn't work!");
1190  getOperandList()[OpNo] = Handler;
1191 }
1192 
1194  // Move all subsequent handlers up one.
1195  Use *EndDst = op_end() - 1;
1196  for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
1197  *CurDst = *(CurDst + 1);
1198  // Null out the last handler use.
1199  *EndDst = nullptr;
1200 
1202 }
1203 
1204 //===----------------------------------------------------------------------===//
1205 // FuncletPadInst Implementation
1206 //===----------------------------------------------------------------------===//
1207 void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
1208  const Twine &NameStr) {
1209  assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
1210  llvm::copy(Args, op_begin());
1211  setParentPad(ParentPad);
1212  setName(NameStr);
1213 }
1214 
1215 FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
1216  : Instruction(FPI.getType(), FPI.getOpcode(),
1217  OperandTraits<FuncletPadInst>::op_end(this) -
1218  FPI.getNumOperands(),
1219  FPI.getNumOperands()) {
1220  std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
1221  setParentPad(FPI.getParentPad());
1222 }
1223 
1224 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1225  ArrayRef<Value *> Args, unsigned Values,
1226  const Twine &NameStr, Instruction *InsertBefore)
1227  : Instruction(ParentPad->getType(), Op,
1228  OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
1229  InsertBefore) {
1230  init(ParentPad, Args, NameStr);
1231 }
1232 
1233 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1234  ArrayRef<Value *> Args, unsigned Values,
1235  const Twine &NameStr, BasicBlock *InsertAtEnd)
1236  : Instruction(ParentPad->getType(), Op,
1237  OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
1238  InsertAtEnd) {
1239  init(ParentPad, Args, NameStr);
1240 }
1241 
1242 //===----------------------------------------------------------------------===//
1243 // UnreachableInst Implementation
1244 //===----------------------------------------------------------------------===//
1245 
1247  Instruction *InsertBefore)
1248  : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1249  0, InsertBefore) {}
1251  : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1252  0, InsertAtEnd) {}
1253 
1254 //===----------------------------------------------------------------------===//
1255 // BranchInst Implementation
1256 //===----------------------------------------------------------------------===//
1257 
1258 void BranchInst::AssertOK() {
1259  if (isConditional())
1260  assert(getCondition()->getType()->isIntegerTy(1) &&
1261  "May only branch on boolean predicates!");
1262 }
1263 
1264 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1265  : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1266  OperandTraits<BranchInst>::op_end(this) - 1, 1,
1267  InsertBefore) {
1268  assert(IfTrue && "Branch destination may not be null!");
1269  Op<-1>() = IfTrue;
1270 }
1271 
1272 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1273  Instruction *InsertBefore)
1274  : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1275  OperandTraits<BranchInst>::op_end(this) - 3, 3,
1276  InsertBefore) {
1277  // Assign in order of operand index to make use-list order predictable.
1278  Op<-3>() = Cond;
1279  Op<-2>() = IfFalse;
1280  Op<-1>() = IfTrue;
1281 #ifndef NDEBUG
1282  AssertOK();
1283 #endif
1284 }
1285 
1286 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1287  : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1288  OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) {
1289  assert(IfTrue && "Branch destination may not be null!");
1290  Op<-1>() = IfTrue;
1291 }
1292 
1293 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1294  BasicBlock *InsertAtEnd)
1295  : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1296  OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) {
1297  // Assign in order of operand index to make use-list order predictable.
1298  Op<-3>() = Cond;
1299  Op<-2>() = IfFalse;
1300  Op<-1>() = IfTrue;
1301 #ifndef NDEBUG
1302  AssertOK();
1303 #endif
1304 }
1305 
1306 BranchInst::BranchInst(const BranchInst &BI)
1307  : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br,
1308  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1309  BI.getNumOperands()) {
1310  // Assign in order of operand index to make use-list order predictable.
1311  if (BI.getNumOperands() != 1) {
1312  assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1313  Op<-3>() = BI.Op<-3>();
1314  Op<-2>() = BI.Op<-2>();
1315  }
1316  Op<-1>() = BI.Op<-1>();
1318 }
1319 
1321  assert(isConditional() &&
1322  "Cannot swap successors of an unconditional branch");
1323  Op<-1>().swap(Op<-2>());
1324 
1325  // Update profile metadata if present and it matches our structural
1326  // expectations.
1327  swapProfMetadata();
1328 }
1329 
1330 //===----------------------------------------------------------------------===//
1331 // AllocaInst Implementation
1332 //===----------------------------------------------------------------------===//
1333 
1335  if (!Amt)
1337  else {
1338  assert(!isa<BasicBlock>(Amt) &&
1339  "Passed basic block into allocation size parameter! Use other ctor");
1340  assert(Amt->getType()->isIntegerTy() &&
1341  "Allocation array size is not an integer!");
1342  }
1343  return Amt;
1344 }
1345 
1347  assert(BB && "Insertion BB cannot be null when alignment not provided!");
1348  assert(BB->getParent() &&
1349  "BB must be in a Function when alignment not provided!");
1350  const DataLayout &DL = BB->getModule()->getDataLayout();
1351  return DL.getPrefTypeAlign(Ty);
1352 }
1353 
1355  assert(I && "Insertion position cannot be null when alignment not provided!");
1356  return computeAllocaDefaultAlign(Ty, I->getParent());
1357 }
1358 
1359 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1360  Instruction *InsertBefore)
1361  : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1362 
1363 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1364  BasicBlock *InsertAtEnd)
1365  : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1366 
1367 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1368  const Twine &Name, Instruction *InsertBefore)
1369  : AllocaInst(Ty, AddrSpace, ArraySize,
1370  computeAllocaDefaultAlign(Ty, InsertBefore), Name,
1371  InsertBefore) {}
1372 
1373 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1374  const Twine &Name, BasicBlock *InsertAtEnd)
1375  : AllocaInst(Ty, AddrSpace, ArraySize,
1376  computeAllocaDefaultAlign(Ty, InsertAtEnd), Name,
1377  InsertAtEnd) {}
1378 
1379 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1380  Align Align, const Twine &Name,
1381  Instruction *InsertBefore)
1382  : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1383  getAISize(Ty->getContext(), ArraySize), InsertBefore),
1384  AllocatedType(Ty) {
1386  assert(!Ty->isVoidTy() && "Cannot allocate void!");
1387  setName(Name);
1388 }
1389 
1390 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1391  Align Align, const Twine &Name, BasicBlock *InsertAtEnd)
1392  : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1393  getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1394  AllocatedType(Ty) {
1396  assert(!Ty->isVoidTy() && "Cannot allocate void!");
1397  setName(Name);
1398 }
1399 
1400 
1402  if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1403  return !CI->isOne();
1404  return true;
1405 }
1406 
1407 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1408 /// function and is a constant size. If so, the code generator will fold it
1409 /// into the prolog/epilog code, so it is basically free.
1411  // Must be constant size.
1412  if (!isa<ConstantInt>(getArraySize())) return false;
1413 
1414  // Must be in the entry block.
1415  const BasicBlock *Parent = getParent();
1416  return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1417 }
1418 
1419 //===----------------------------------------------------------------------===//
1420 // LoadInst Implementation
1421 //===----------------------------------------------------------------------===//
1422 
1423 void LoadInst::AssertOK() {
1424  assert(getOperand(0)->getType()->isPointerTy() &&
1425  "Ptr must have pointer type.");
1426 }
1427 
1429  assert(BB && "Insertion BB cannot be null when alignment not provided!");
1430  assert(BB->getParent() &&
1431  "BB must be in a Function when alignment not provided!");
1432  const DataLayout &DL = BB->getModule()->getDataLayout();
1433  return DL.getABITypeAlign(Ty);
1434 }
1435 
1437  assert(I && "Insertion position cannot be null when alignment not provided!");
1438  return computeLoadStoreDefaultAlign(Ty, I->getParent());
1439 }
1440 
1442  Instruction *InsertBef)
1443  : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1444 
1446  BasicBlock *InsertAE)
1447  : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1448 
1449 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1450  Instruction *InsertBef)
1451  : LoadInst(Ty, Ptr, Name, isVolatile,
1452  computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
1453 
1454 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1455  BasicBlock *InsertAE)
1456  : LoadInst(Ty, Ptr, Name, isVolatile,
1457  computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {}
1458 
1459 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1460  Align Align, Instruction *InsertBef)
1461  : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1462  SyncScope::System, InsertBef) {}
1463 
1464 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1465  Align Align, BasicBlock *InsertAE)
1466  : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1467  SyncScope::System, InsertAE) {}
1468 
1469 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1470  Align Align, AtomicOrdering Order, SyncScope::ID SSID,
1471  Instruction *InsertBef)
1472  : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1473  assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
1476  setAtomic(Order, SSID);
1477  AssertOK();
1478  setName(Name);
1479 }
1480 
1481 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1482  Align Align, AtomicOrdering Order, SyncScope::ID SSID,
1483  BasicBlock *InsertAE)
1484  : UnaryInstruction(Ty, Load, Ptr, InsertAE) {
1485  assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
1488  setAtomic(Order, SSID);
1489  AssertOK();
1490  setName(Name);
1491 }
1492 
1493 //===----------------------------------------------------------------------===//
1494 // StoreInst Implementation
1495 //===----------------------------------------------------------------------===//
1496 
1497 void StoreInst::AssertOK() {
1498  assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1499  assert(getOperand(1)->getType()->isPointerTy() &&
1500  "Ptr must have pointer type!");
1501  assert(cast<PointerType>(getOperand(1)->getType())
1502  ->isOpaqueOrPointeeTypeMatches(getOperand(0)->getType()) &&
1503  "Ptr must be a pointer to Val type!");
1504 }
1505 
1507  : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1508 
1510  : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1511 
1512 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1513  Instruction *InsertBefore)
1514  : StoreInst(val, addr, isVolatile,
1515  computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
1516  InsertBefore) {}
1517 
1518 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1519  BasicBlock *InsertAtEnd)
1520  : StoreInst(val, addr, isVolatile,
1521  computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd),
1522  InsertAtEnd) {}
1523 
1524 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
1525  Instruction *InsertBefore)
1526  : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1527  SyncScope::System, InsertBefore) {}
1528 
1529 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
1530  BasicBlock *InsertAtEnd)
1531  : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1532  SyncScope::System, InsertAtEnd) {}
1533 
1534 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
1535  AtomicOrdering Order, SyncScope::ID SSID,
1536  Instruction *InsertBefore)
1537  : Instruction(Type::getVoidTy(val->getContext()), Store,
1538  OperandTraits<StoreInst>::op_begin(this),
1539  OperandTraits<StoreInst>::operands(this), InsertBefore) {
1540  Op<0>() = val;
1541  Op<1>() = addr;
1544  setAtomic(Order, SSID);
1545  AssertOK();
1546 }
1547 
1548 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
1549  AtomicOrdering Order, SyncScope::ID SSID,
1550  BasicBlock *InsertAtEnd)
1551  : Instruction(Type::getVoidTy(val->getContext()), Store,
1552  OperandTraits<StoreInst>::op_begin(this),
1553  OperandTraits<StoreInst>::operands(this), InsertAtEnd) {
1554  Op<0>() = val;
1555  Op<1>() = addr;
1558  setAtomic(Order, SSID);
1559  AssertOK();
1560 }
1561 
1562 
1563 //===----------------------------------------------------------------------===//
1564 // AtomicCmpXchgInst Implementation
1565 //===----------------------------------------------------------------------===//
1566 
1567 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1568  Align Alignment, AtomicOrdering SuccessOrdering,
1569  AtomicOrdering FailureOrdering,
1570  SyncScope::ID SSID) {
1571  Op<0>() = Ptr;
1572  Op<1>() = Cmp;
1573  Op<2>() = NewVal;
1574  setSuccessOrdering(SuccessOrdering);
1575  setFailureOrdering(FailureOrdering);
1576  setSyncScopeID(SSID);
1577  setAlignment(Alignment);
1578 
1579  assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1580  "All operands must be non-null!");
1581  assert(getOperand(0)->getType()->isPointerTy() &&
1582  "Ptr must have pointer type!");
1583  assert(cast<PointerType>(getOperand(0)->getType())
1584  ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
1585  "Ptr must be a pointer to Cmp type!");
1586  assert(cast<PointerType>(getOperand(0)->getType())
1587  ->isOpaqueOrPointeeTypeMatches(getOperand(2)->getType()) &&
1588  "Ptr must be a pointer to NewVal type!");
1589  assert(getOperand(1)->getType() == getOperand(2)->getType() &&
1590  "Cmp type and NewVal type must be same!");
1591 }
1592 
1594  Align Alignment,
1595  AtomicOrdering SuccessOrdering,
1596  AtomicOrdering FailureOrdering,
1597  SyncScope::ID SSID,
1598  Instruction *InsertBefore)
1599  : Instruction(
1600  StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1601  AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1602  OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1603  Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
1604 }
1605 
1607  Align Alignment,
1608  AtomicOrdering SuccessOrdering,
1609  AtomicOrdering FailureOrdering,
1610  SyncScope::ID SSID,
1611  BasicBlock *InsertAtEnd)
1612  : Instruction(
1613  StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1614  AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1615  OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1616  Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
1617 }
1618 
1619 //===----------------------------------------------------------------------===//
1620 // AtomicRMWInst Implementation
1621 //===----------------------------------------------------------------------===//
1622 
1623 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1624  Align Alignment, AtomicOrdering Ordering,
1625  SyncScope::ID SSID) {
1626  assert(Ordering != AtomicOrdering::NotAtomic &&
1627  "atomicrmw instructions can only be atomic.");
1628  assert(Ordering != AtomicOrdering::Unordered &&
1629  "atomicrmw instructions cannot be unordered.");
1630  Op<0>() = Ptr;
1631  Op<1>() = Val;
1633  setOrdering(Ordering);
1634  setSyncScopeID(SSID);
1635  setAlignment(Alignment);
1636 
1637  assert(getOperand(0) && getOperand(1) &&
1638  "All operands must be non-null!");
1639  assert(getOperand(0)->getType()->isPointerTy() &&
1640  "Ptr must have pointer type!");
1641  assert(cast<PointerType>(getOperand(0)->getType())
1642  ->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
1643  "Ptr must be a pointer to Val type!");
1644  assert(Ordering != AtomicOrdering::NotAtomic &&
1645  "AtomicRMW instructions must be atomic!");
1646 }
1647 
1649  Align Alignment, AtomicOrdering Ordering,
1650  SyncScope::ID SSID, Instruction *InsertBefore)
1651  : Instruction(Val->getType(), AtomicRMW,
1652  OperandTraits<AtomicRMWInst>::op_begin(this),
1653  OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) {
1654  Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
1655 }
1656 
1658  Align Alignment, AtomicOrdering Ordering,
1659  SyncScope::ID SSID, BasicBlock *InsertAtEnd)
1660  : Instruction(Val->getType(), AtomicRMW,
1661  OperandTraits<AtomicRMWInst>::op_begin(this),
1662  OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) {
1663  Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
1664 }
1665 
1667  switch (Op) {
1668  case AtomicRMWInst::Xchg:
1669  return "xchg";
1670  case AtomicRMWInst::Add:
1671  return "add";
1672  case AtomicRMWInst::Sub:
1673  return "sub";
1674  case AtomicRMWInst::And:
1675  return "and";
1676  case AtomicRMWInst::Nand:
1677  return "nand";
1678  case AtomicRMWInst::Or:
1679  return "or";
1680  case AtomicRMWInst::Xor:
1681  return "xor";
1682  case AtomicRMWInst::Max:
1683  return "max";
1684  case AtomicRMWInst::Min:
1685  return "min";
1686  case AtomicRMWInst::UMax:
1687  return "umax";
1688  case AtomicRMWInst::UMin:
1689  return "umin";
1690  case AtomicRMWInst::FAdd:
1691  return "fadd";
1692  case AtomicRMWInst::FSub:
1693  return "fsub";
1694  case AtomicRMWInst::FMax:
1695  return "fmax";
1696  case AtomicRMWInst::FMin:
1697  return "fmin";
1699  return "<invalid operation>";
1700  }
1701 
1702  llvm_unreachable("invalid atomicrmw operation");
1703 }
1704 
1705 //===----------------------------------------------------------------------===//
1706 // FenceInst Implementation
1707 //===----------------------------------------------------------------------===//
1708 
1710  SyncScope::ID SSID,
1711  Instruction *InsertBefore)
1712  : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1713  setOrdering(Ordering);
1714  setSyncScopeID(SSID);
1715 }
1716 
1718  SyncScope::ID SSID,
1719  BasicBlock *InsertAtEnd)
1720  : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1721  setOrdering(Ordering);
1722  setSyncScopeID(SSID);
1723 }
1724 
1725 //===----------------------------------------------------------------------===//
1726 // GetElementPtrInst Implementation
1727 //===----------------------------------------------------------------------===//
1728 
1729 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1730  const Twine &Name) {
1731  assert(getNumOperands() == 1 + IdxList.size() &&
1732  "NumOperands not initialized?");
1733  Op<0>() = Ptr;
1734  llvm::copy(IdxList, op_begin() + 1);
1735  setName(Name);
1736 }
1737 
1738 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1739  : Instruction(GEPI.getType(), GetElementPtr,
1741  GEPI.getNumOperands(),
1742  GEPI.getNumOperands()),
1743  SourceElementType(GEPI.SourceElementType),
1744  ResultElementType(GEPI.ResultElementType) {
1745  std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1747 }
1748 
1750  if (auto *Struct = dyn_cast<StructType>(Ty)) {
1751  if (!Struct->indexValid(Idx))
1752  return nullptr;
1753  return Struct->getTypeAtIndex(Idx);
1754  }
1755  if (!Idx->getType()->isIntOrIntVectorTy())
1756  return nullptr;
1757  if (auto *Array = dyn_cast<ArrayType>(Ty))
1758  return Array->getElementType();
1759  if (auto *Vector = dyn_cast<VectorType>(Ty))
1760  return Vector->getElementType();
1761  return nullptr;
1762 }
1763 
1765  if (auto *Struct = dyn_cast<StructType>(Ty)) {
1766  if (Idx >= Struct->getNumElements())
1767  return nullptr;
1768  return Struct->getElementType(Idx);
1769  }
1770  if (auto *Array = dyn_cast<ArrayType>(Ty))
1771  return Array->getElementType();
1772  if (auto *Vector = dyn_cast<VectorType>(Ty))
1773  return Vector->getElementType();
1774  return nullptr;
1775 }
1776 
1777 template <typename IndexTy>
1779  if (IdxList.empty())
1780  return Ty;
1781  for (IndexTy V : IdxList.slice(1)) {
1783  if (!Ty)
1784  return Ty;
1785  }
1786  return Ty;
1787 }
1788 
1790  return getIndexedTypeInternal(Ty, IdxList);
1791 }
1792 
1794  ArrayRef<Constant *> IdxList) {
1795  return getIndexedTypeInternal(Ty, IdxList);
1796 }
1797 
1799  return getIndexedTypeInternal(Ty, IdxList);
1800 }
1801 
1802 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1803 /// zeros. If so, the result pointer and the first operand have the same
1804 /// value, just potentially different types.
1806  for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1807  if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1808  if (!CI->isZero()) return false;
1809  } else {
1810  return false;
1811  }
1812  }
1813  return true;
1814 }
1815 
1816 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1817 /// constant integers. If so, the result pointer and the first operand have
1818 /// a constant offset between them.
1820  for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1821  if (!isa<ConstantInt>(getOperand(i)))
1822  return false;
1823  }
1824  return true;
1825 }
1826 
1828  cast<GEPOperator>(this)->setIsInBounds(B);
1829 }
1830 
1832  return cast<GEPOperator>(this)->isInBounds();
1833 }
1834 
1836  APInt &Offset) const {
1837  // Delegate to the generic GEPOperator implementation.
1838  return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1839 }
1840 
1842  const DataLayout &DL, unsigned BitWidth,
1843  MapVector<Value *, APInt> &VariableOffsets,
1844  APInt &ConstantOffset) const {
1845  // Delegate to the generic GEPOperator implementation.
1846  return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets,
1847  ConstantOffset);
1848 }
1849 
1850 //===----------------------------------------------------------------------===//
1851 // ExtractElementInst Implementation
1852 //===----------------------------------------------------------------------===//
1853 
1854 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1855  const Twine &Name,
1856  Instruction *InsertBef)
1857  : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1858  ExtractElement,
1860  2, InsertBef) {
1861  assert(isValidOperands(Val, Index) &&
1862  "Invalid extractelement instruction operands!");
1863  Op<0>() = Val;
1864  Op<1>() = Index;
1865  setName(Name);
1866 }
1867 
1868 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1869  const Twine &Name,
1870  BasicBlock *InsertAE)
1871  : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1872  ExtractElement,
1874  2, InsertAE) {
1875  assert(isValidOperands(Val, Index) &&
1876  "Invalid extractelement instruction operands!");
1877 
1878  Op<0>() = Val;
1879  Op<1>() = Index;
1880  setName(Name);
1881 }
1882 
1884  if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1885  return false;
1886  return true;
1887 }
1888 
1889 //===----------------------------------------------------------------------===//
1890 // InsertElementInst Implementation
1891 //===----------------------------------------------------------------------===//
1892 
1893 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1894  const Twine &Name,
1895  Instruction *InsertBef)
1896  : Instruction(Vec->getType(), InsertElement,
1897  OperandTraits<InsertElementInst>::op_begin(this),
1898  3, InsertBef) {
1899  assert(isValidOperands(Vec, Elt, Index) &&
1900  "Invalid insertelement instruction operands!");
1901  Op<0>() = Vec;
1902  Op<1>() = Elt;
1903  Op<2>() = Index;
1904  setName(Name);
1905 }
1906 
1907 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1908  const Twine &Name,
1909  BasicBlock *InsertAE)
1910  : Instruction(Vec->getType(), InsertElement,
1911  OperandTraits<InsertElementInst>::op_begin(this),
1912  3, InsertAE) {
1913  assert(isValidOperands(Vec, Elt, Index) &&
1914  "Invalid insertelement instruction operands!");
1915 
1916  Op<0>() = Vec;
1917  Op<1>() = Elt;
1918  Op<2>() = Index;
1919  setName(Name);
1920 }
1921 
1922 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1923  const Value *Index) {
1924  if (!Vec->getType()->isVectorTy())
1925  return false; // First operand of insertelement must be vector type.
1926 
1927  if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1928  return false;// Second operand of insertelement must be vector element type.
1929 
1930  if (!Index->getType()->isIntegerTy())
1931  return false; // Third operand of insertelement must be i32.
1932  return true;
1933 }
1934 
1935 //===----------------------------------------------------------------------===//
1936 // ShuffleVectorInst Implementation
1937 //===----------------------------------------------------------------------===//
1938 
1940  assert(V && "Cannot create placeholder of nullptr V");
1941  return PoisonValue::get(V->getType());
1942 }
1943 
1945  Instruction *InsertBefore)
1947  InsertBefore) {}
1948 
1950  BasicBlock *InsertAtEnd)
1952  InsertAtEnd) {}
1953 
1955  const Twine &Name,
1956  Instruction *InsertBefore)
1958  InsertBefore) {}
1959 
1961  const Twine &Name, BasicBlock *InsertAtEnd)
1963  InsertAtEnd) {}
1964 
1966  const Twine &Name,
1967  Instruction *InsertBefore)
1968  : Instruction(
1969  VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1970  cast<VectorType>(Mask->getType())->getElementCount()),
1971  ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1972  OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
1973  assert(isValidOperands(V1, V2, Mask) &&
1974  "Invalid shuffle vector instruction operands!");
1975 
1976  Op<0>() = V1;
1977  Op<1>() = V2;
1978  SmallVector<int, 16> MaskArr;
1979  getShuffleMask(cast<Constant>(Mask), MaskArr);
1980  setShuffleMask(MaskArr);
1981  setName(Name);
1982 }
1983 
1985  const Twine &Name, BasicBlock *InsertAtEnd)
1986  : Instruction(
1987  VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1988  cast<VectorType>(Mask->getType())->getElementCount()),
1989  ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1990  OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
1991  assert(isValidOperands(V1, V2, Mask) &&
1992  "Invalid shuffle vector instruction operands!");
1993 
1994  Op<0>() = V1;
1995  Op<1>() = V2;
1996  SmallVector<int, 16> MaskArr;
1997  getShuffleMask(cast<Constant>(Mask), MaskArr);
1998  setShuffleMask(MaskArr);
1999  setName(Name);
2000 }
2001 
2003  const Twine &Name,
2004  Instruction *InsertBefore)
2005  : Instruction(
2006  VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
2007  Mask.size(), isa<ScalableVectorType>(V1->getType())),
2008  ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
2009  OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
2010  assert(isValidOperands(V1, V2, Mask) &&
2011  "Invalid shuffle vector instruction operands!");
2012  Op<0>() = V1;
2013  Op<1>() = V2;
2015  setName(Name);
2016 }
2017 
2019  const Twine &Name, BasicBlock *InsertAtEnd)
2020  : Instruction(
2021  VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
2022  Mask.size(), isa<ScalableVectorType>(V1->getType())),
2023  ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
2024  OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
2025  assert(isValidOperands(V1, V2, Mask) &&
2026  "Invalid shuffle vector instruction operands!");
2027 
2028  Op<0>() = V1;
2029  Op<1>() = V2;
2031  setName(Name);
2032 }
2033 
2035  int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2036  int NumMaskElts = ShuffleMask.size();
2037  SmallVector<int, 16> NewMask(NumMaskElts);
2038  for (int i = 0; i != NumMaskElts; ++i) {
2039  int MaskElt = getMaskValue(i);
2040  if (MaskElt == UndefMaskElem) {
2041  NewMask[i] = UndefMaskElem;
2042  continue;
2043  }
2044  assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
2045  MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
2046  NewMask[i] = MaskElt;
2047  }
2048  setShuffleMask(NewMask);
2049  Op<0>().swap(Op<1>());
2050 }
2051 
2053  ArrayRef<int> Mask) {
2054  // V1 and V2 must be vectors of the same type.
2055  if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
2056  return false;
2057 
2058  // Make sure the mask elements make sense.
2059  int V1Size =
2060  cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
2061  for (int Elem : Mask)
2062  if (Elem != UndefMaskElem && Elem >= V1Size * 2)
2063  return false;
2064 
2065  if (isa<ScalableVectorType>(V1->getType()))
2066  if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !all_equal(Mask))
2067  return false;
2068 
2069  return true;
2070 }
2071 
2073  const Value *Mask) {
2074  // V1 and V2 must be vectors of the same type.
2075  if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
2076  return false;
2077 
2078  // Mask must be vector of i32, and must be the same kind of vector as the
2079  // input vectors
2080  auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
2081  if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
2082  isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType()))
2083  return false;
2084 
2085  // Check to see if Mask is valid.
2086  if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
2087  return true;
2088 
2089  if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
2090  unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
2091  for (Value *Op : MV->operands()) {
2092  if (auto *CI = dyn_cast<ConstantInt>(Op)) {
2093  if (CI->uge(V1Size*2))
2094  return false;
2095  } else if (!isa<UndefValue>(Op)) {
2096  return false;
2097  }
2098  }
2099  return true;
2100  }
2101 
2102  if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
2103  unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
2104  for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
2105  i != e; ++i)
2106  if (CDS->getElementAsInteger(i) >= V1Size*2)
2107  return false;
2108  return true;
2109  }
2110 
2111  return false;
2112 }
2113 
2115  SmallVectorImpl<int> &Result) {
2116  ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
2117 
2118  if (isa<ConstantAggregateZero>(Mask)) {
2119  Result.resize(EC.getKnownMinValue(), 0);
2120  return;
2121  }
2122 
2123  Result.reserve(EC.getKnownMinValue());
2124 
2125  if (EC.isScalable()) {
2126  assert((isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) &&
2127  "Scalable vector shuffle mask must be undef or zeroinitializer");
2128  int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
2129  for (unsigned I = 0; I < EC.getKnownMinValue(); ++I)
2130  Result.emplace_back(MaskVal);
2131  return;
2132  }
2133 
2134  unsigned NumElts = EC.getKnownMinValue();
2135 
2136  if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
2137  for (unsigned i = 0; i != NumElts; ++i)
2138  Result.push_back(CDS->getElementAsInteger(i));
2139  return;
2140  }
2141  for (unsigned i = 0; i != NumElts; ++i) {
2142  Constant *C = Mask->getAggregateElement(i);
2143  Result.push_back(isa<UndefValue>(C) ? -1 :
2144  cast<ConstantInt>(C)->getZExtValue());
2145  }
2146 }
2147 
2149  ShuffleMask.assign(Mask.begin(), Mask.end());
2150  ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
2151 }
2152 
2154  Type *ResultTy) {
2155  Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
2156  if (isa<ScalableVectorType>(ResultTy)) {
2157  assert(all_equal(Mask) && "Unexpected shuffle");
2158  Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
2159  if (Mask[0] == 0)
2160  return Constant::getNullValue(VecTy);
2161  return UndefValue::get(VecTy);
2162  }
2163  SmallVector<Constant *, 16> MaskConst;
2164  for (int Elem : Mask) {
2165  if (Elem == UndefMaskElem)
2166  MaskConst.push_back(UndefValue::get(Int32Ty));
2167  else
2168  MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
2169  }
2170  return ConstantVector::get(MaskConst);
2171 }
2172 
2173 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
2174  assert(!Mask.empty() && "Shuffle mask must contain elements");
2175  bool UsesLHS = false;
2176  bool UsesRHS = false;
2177  for (int I : Mask) {
2178  if (I == -1)
2179  continue;
2180  assert(I >= 0 && I < (NumOpElts * 2) &&
2181  "Out-of-bounds shuffle mask element");
2182  UsesLHS |= (I < NumOpElts);
2183  UsesRHS |= (I >= NumOpElts);
2184  if (UsesLHS && UsesRHS)
2185  return false;
2186  }
2187  // Allow for degenerate case: completely undef mask means neither source is used.
2188  return UsesLHS || UsesRHS;
2189 }
2190 
2192  // We don't have vector operand size information, so assume operands are the
2193  // same size as the mask.
2194  return isSingleSourceMaskImpl(Mask, Mask.size());
2195 }
2196 
2197 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
2198  if (!isSingleSourceMaskImpl(Mask, NumOpElts))
2199  return false;
2200  for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
2201  if (Mask[i] == -1)
2202  continue;
2203  if (Mask[i] != i && Mask[i] != (NumOpElts + i))
2204  return false;
2205  }
2206  return true;
2207 }
2208 
2210  // We don't have vector operand size information, so assume operands are the
2211  // same size as the mask.
2212  return isIdentityMaskImpl(Mask, Mask.size());
2213 }
2214 
2216  if (!isSingleSourceMask(Mask))
2217  return false;
2218 
2219  // The number of elements in the mask must be at least 2.
2220  int NumElts = Mask.size();
2221  if (NumElts < 2)
2222  return false;
2223 
2224  for (int i = 0; i < NumElts; ++i) {
2225  if (Mask[i] == -1)
2226  continue;
2227  if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
2228  return false;
2229  }
2230  return true;
2231 }
2232 
2234  if (!isSingleSourceMask(Mask))
2235  return false;
2236  for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
2237  if (Mask[i] == -1)
2238  continue;
2239  if (Mask[i] != 0 && Mask[i] != NumElts)
2240  return false;
2241  }
2242  return true;
2243 }
2244 
2246  // Select is differentiated from identity. It requires using both sources.
2247  if (isSingleSourceMask(Mask))
2248  return false;
2249  for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
2250  if (Mask[i] == -1)
2251  continue;
2252  if (Mask[i] != i && Mask[i] != (NumElts + i))
2253  return false;
2254  }
2255  return true;
2256 }
2257 
2259  // Example masks that will return true:
2260  // v1 = <a, b, c, d>
2261  // v2 = <e, f, g, h>
2262  // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2263  // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2264 
2265  // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2266  int NumElts = Mask.size();
2267  if (NumElts < 2 || !isPowerOf2_32(NumElts))
2268  return false;
2269 
2270  // 2. The first element of the mask must be either a 0 or a 1.
2271  if (Mask[0] != 0 && Mask[0] != 1)
2272  return false;
2273 
2274  // 3. The difference between the first 2 elements must be equal to the
2275  // number of elements in the mask.
2276  if ((Mask[1] - Mask[0]) != NumElts)
2277  return false;
2278 
2279  // 4. The difference between consecutive even-numbered and odd-numbered
2280  // elements must be equal to 2.
2281  for (int i = 2; i < NumElts; ++i) {
2282  int MaskEltVal = Mask[i];
2283  if (MaskEltVal == -1)
2284  return false;
2285  int MaskEltPrevVal = Mask[i - 2];
2286  if (MaskEltVal - MaskEltPrevVal != 2)
2287  return false;
2288  }
2289  return true;
2290 }
2291 
2293  // Example: shufflevector <4 x n> A, <4 x n> B, <1,2,3,4>
2294  int StartIndex = -1;
2295  for (int I = 0, E = Mask.size(); I != E; ++I) {
2296  int MaskEltVal = Mask[I];
2297  if (MaskEltVal == -1)
2298  continue;
2299 
2300  if (StartIndex == -1) {
2301  // Don't support a StartIndex that begins in the second input, or if the
2302  // first non-undef index would access below the StartIndex.
2303  if (MaskEltVal < I || E <= (MaskEltVal - I))
2304  return false;
2305 
2306  StartIndex = MaskEltVal - I;
2307  continue;
2308  }
2309 
2310  // Splice is sequential starting from StartIndex.
2311  if (MaskEltVal != (StartIndex + I))
2312  return false;
2313  }
2314 
2315  if (StartIndex == -1)
2316  return false;
2317 
2318  // NOTE: This accepts StartIndex == 0 (COPY).
2319  Index = StartIndex;
2320  return true;
2321 }
2322 
2324  int NumSrcElts, int &Index) {
2325  // Must extract from a single source.
2326  if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2327  return false;
2328 
2329  // Must be smaller (else this is an Identity shuffle).
2330  if (NumSrcElts <= (int)Mask.size())
2331  return false;
2332 
2333  // Find start of extraction, accounting that we may start with an UNDEF.
2334  int SubIndex = -1;
2335  for (int i = 0, e = Mask.size(); i != e; ++i) {
2336  int M = Mask[i];
2337  if (M < 0)
2338  continue;
2339  int Offset = (M % NumSrcElts) - i;
2340  if (0 <= SubIndex && SubIndex != Offset)
2341  return false;
2342  SubIndex = Offset;
2343  }
2344 
2345  if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
2346  Index = SubIndex;
2347  return true;
2348  }
2349  return false;
2350 }
2351 
2353  int NumSrcElts, int &NumSubElts,
2354  int &Index) {
2355  int NumMaskElts = Mask.size();
2356 
2357  // Don't try to match if we're shuffling to a smaller size.
2358  if (NumMaskElts < NumSrcElts)
2359  return false;
2360 
2361  // TODO: We don't recognize self-insertion/widening.
2362  if (isSingleSourceMaskImpl(Mask, NumSrcElts))
2363  return false;
2364 
2365  // Determine which mask elements are attributed to which source.
2366  APInt UndefElts = APInt::getZero(NumMaskElts);
2367  APInt Src0Elts = APInt::getZero(NumMaskElts);
2368  APInt Src1Elts = APInt::getZero(NumMaskElts);
2369  bool Src0Identity = true;
2370  bool Src1Identity = true;
2371 
2372  for (int i = 0; i != NumMaskElts; ++i) {
2373  int M = Mask[i];
2374  if (M < 0) {
2375  UndefElts.setBit(i);
2376  continue;
2377  }
2378  if (M < NumSrcElts) {
2379  Src0Elts.setBit(i);
2380  Src0Identity &= (M == i);
2381  continue;
2382  }
2383  Src1Elts.setBit(i);
2384  Src1Identity &= (M == (i + NumSrcElts));
2385  }
2386  assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() &&
2387  "unknown shuffle elements");
2388  assert(!Src0Elts.isZero() && !Src1Elts.isZero() &&
2389  "2-source shuffle not found");
2390 
2391  // Determine lo/hi span ranges.
2392  // TODO: How should we handle undefs at the start of subvector insertions?
2393  int Src0Lo = Src0Elts.countTrailingZeros();
2394  int Src1Lo = Src1Elts.countTrailingZeros();
2395  int Src0Hi = NumMaskElts - Src0Elts.countLeadingZeros();
2396  int Src1Hi = NumMaskElts - Src1Elts.countLeadingZeros();
2397 
2398  // If src0 is in place, see if the src1 elements is inplace within its own
2399  // span.
2400  if (Src0Identity) {
2401  int NumSub1Elts = Src1Hi - Src1Lo;
2402  ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts);
2403  if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) {
2404  NumSubElts = NumSub1Elts;
2405  Index = Src1Lo;
2406  return true;
2407  }
2408  }
2409 
2410  // If src1 is in place, see if the src0 elements is inplace within its own
2411  // span.
2412  if (Src1Identity) {
2413  int NumSub0Elts = Src0Hi - Src0Lo;
2414  ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts);
2415  if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) {
2416  NumSubElts = NumSub0Elts;
2417  Index = Src0Lo;
2418  return true;
2419  }
2420  }
2421 
2422  return false;
2423 }
2424 
2426  if (isa<UndefValue>(Op<2>()))
2427  return false;
2428 
2429  // FIXME: Not currently possible to express a shuffle mask for a scalable
2430  // vector for this case.
2431  if (isa<ScalableVectorType>(getType()))
2432  return false;
2433 
2434  int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2435  int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2436  if (NumMaskElts <= NumOpElts)
2437  return false;
2438 
2439  // The first part of the mask must choose elements from exactly 1 source op.
2441  if (!isIdentityMaskImpl(Mask, NumOpElts))
2442  return false;
2443 
2444  // All extending must be with undef elements.
2445  for (int i = NumOpElts; i < NumMaskElts; ++i)
2446  if (Mask[i] != -1)
2447  return false;
2448 
2449  return true;
2450 }
2451 
2453  if (isa<UndefValue>(Op<2>()))
2454  return false;
2455 
2456  // FIXME: Not currently possible to express a shuffle mask for a scalable
2457  // vector for this case.
2458  if (isa<ScalableVectorType>(getType()))
2459  return false;
2460 
2461  int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2462  int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2463  if (NumMaskElts >= NumOpElts)
2464  return false;
2465 
2466  return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2467 }
2468 
2470  // Vector concatenation is differentiated from identity with padding.
2471  if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) ||
2472  isa<UndefValue>(Op<2>()))
2473  return false;
2474 
2475  // FIXME: Not currently possible to express a shuffle mask for a scalable
2476  // vector for this case.
2477  if (isa<ScalableVectorType>(getType()))
2478  return false;
2479 
2480  int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2481  int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2482  if (NumMaskElts != NumOpElts * 2)
2483  return false;
2484 
2485  // Use the mask length rather than the operands' vector lengths here. We
2486  // already know that the shuffle returns a vector twice as long as the inputs,
2487  // and neither of the inputs are undef vectors. If the mask picks consecutive
2488  // elements from both inputs, then this is a concatenation of the inputs.
2489  return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2490 }
2491 
2493  int ReplicationFactor, int VF) {
2494  assert(Mask.size() == (unsigned)ReplicationFactor * VF &&
2495  "Unexpected mask size.");
2496 
2497  for (int CurrElt : seq(0, VF)) {
2498  ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor);
2499  assert(CurrSubMask.size() == (unsigned)ReplicationFactor &&
2500  "Run out of mask?");
2501  Mask = Mask.drop_front(ReplicationFactor);
2502  if (!all_of(CurrSubMask, [CurrElt](int MaskElt) {
2503  return MaskElt == UndefMaskElem || MaskElt == CurrElt;
2504  }))
2505  return false;
2506  }
2507  assert(Mask.empty() && "Did not consume the whole mask?");
2508 
2509  return true;
2510 }
2511 
2513  int &ReplicationFactor, int &VF) {
2514  // undef-less case is trivial.
2516  ReplicationFactor =
2517  Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size();
2518  if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0)
2519  return false;
2520  VF = Mask.size() / ReplicationFactor;
2521  return isReplicationMaskWithParams(Mask, ReplicationFactor, VF);
2522  }
2523 
2524  // However, if the mask contains undef's, we have to enumerate possible tuples
2525  // and pick one. There are bounds on replication factor: [1, mask size]
2526  // (where RF=1 is an identity shuffle, RF=mask size is a broadcast shuffle)
2527  // Additionally, mask size is a replication factor multiplied by vector size,
2528  // which further significantly reduces the search space.
2529 
2530  // Before doing that, let's perform basic correctness checking first.
2531  int Largest = -1;
2532  for (int MaskElt : Mask) {
2533  if (MaskElt == UndefMaskElem)
2534  continue;
2535  // Elements must be in non-decreasing order.
2536  if (MaskElt < Largest)
2537  return false;
2538  Largest = std::max(Largest, MaskElt);
2539  }
2540 
2541  // Prefer larger replication factor if all else equal.
2542  for (int PossibleReplicationFactor :
2543  reverse(seq_inclusive<unsigned>(1, Mask.size()))) {
2544  if (Mask.size() % PossibleReplicationFactor != 0)
2545  continue;
2546  int PossibleVF = Mask.size() / PossibleReplicationFactor;
2547  if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor,
2548  PossibleVF))
2549  continue;
2550  ReplicationFactor = PossibleReplicationFactor;
2551  VF = PossibleVF;
2552  return true;
2553  }
2554 
2555  return false;
2556 }
2557 
2558 bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor,
2559  int &VF) const {
2560  // Not possible to express a shuffle mask for a scalable vector for this
2561  // case.
2562  if (isa<ScalableVectorType>(getType()))
2563  return false;
2564 
2565  VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2566  if (ShuffleMask.size() % VF != 0)
2567  return false;
2568  ReplicationFactor = ShuffleMask.size() / VF;
2569 
2570  return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF);
2571 }
2572 
2574  if (VF <= 0 || Mask.size() < static_cast<unsigned>(VF) ||
2575  Mask.size() % VF != 0)
2576  return false;
2577  for (unsigned K = 0, Sz = Mask.size(); K < Sz; K += VF) {
2578  ArrayRef<int> SubMask = Mask.slice(K, VF);
2579  if (all_of(SubMask, [](int Idx) { return Idx == UndefMaskElem; }))
2580  continue;
2581  SmallBitVector Used(VF, false);
2582  for_each(SubMask, [&Used, VF](int Idx) {
2583  if (Idx != UndefMaskElem && Idx < VF)
2584  Used.set(Idx);
2585  });
2586  if (!Used.all())
2587  return false;
2588  }
2589  return true;
2590 }
2591 
2592 /// Return true if this shuffle mask is a replication mask.
2594  // Not possible to express a shuffle mask for a scalable vector for this
2595  // case.
2596  if (isa<ScalableVectorType>(getType()))
2597  return false;
2598  if (!isSingleSourceMask(ShuffleMask))
2599  return false;
2600 
2601  return isOneUseSingleSourceMask(ShuffleMask, VF);
2602 }
2603 
2604 //===----------------------------------------------------------------------===//
2605 // InsertValueInst Class
2606 //===----------------------------------------------------------------------===//
2607 
2608 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2609  const Twine &Name) {
2610  assert(getNumOperands() == 2 && "NumOperands not initialized?");
2611 
2612  // There's no fundamental reason why we require at least one index
2613  // (other than weirdness with &*IdxBegin being invalid; see
2614  // getelementptr's init routine for example). But there's no
2615  // present need to support it.
2616  assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2617 
2619  Val->getType() && "Inserted value must match indexed type!");
2620  Op<0>() = Agg;
2621  Op<1>() = Val;
2622 
2623  Indices.append(Idxs.begin(), Idxs.end());
2624  setName(Name);
2625 }
2626 
2627 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2628  : Instruction(IVI.getType(), InsertValue,
2629  OperandTraits<InsertValueInst>::op_begin(this), 2),
2630  Indices(IVI.Indices) {
2631  Op<0>() = IVI.getOperand(0);
2632  Op<1>() = IVI.getOperand(1);
2634 }
2635 
2636 //===----------------------------------------------------------------------===//
2637 // ExtractValueInst Class
2638 //===----------------------------------------------------------------------===//
2639 
2640 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2641  assert(getNumOperands() == 1 && "NumOperands not initialized?");
2642 
2643  // There's no fundamental reason why we require at least one index.
2644  // But there's no present need to support it.
2645  assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2646 
2647  Indices.append(Idxs.begin(), Idxs.end());
2648  setName(Name);
2649 }
2650 
2651 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2652  : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
2653  Indices(EVI.Indices) {
2655 }
2656 
2657 // getIndexedType - Returns the type of the element that would be extracted
2658 // with an extractvalue instruction with the specified parameters.
2659 //
2660 // A null type is returned if the indices are invalid for the specified
2661 // pointer type.
2662 //
2664  ArrayRef<unsigned> Idxs) {
2665  for (unsigned Index : Idxs) {
2666  // We can't use CompositeType::indexValid(Index) here.
2667  // indexValid() always returns true for arrays because getelementptr allows
2668  // out-of-bounds indices. Since we don't allow those for extractvalue and
2669  // insertvalue we need to check array indexing manually.
2670  // Since the only other types we can index into are struct types it's just
2671  // as easy to check those manually as well.
2672  if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2673  if (Index >= AT->getNumElements())
2674  return nullptr;
2675  Agg = AT->getElementType();
2676  } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2677  if (Index >= ST->getNumElements())
2678  return nullptr;
2679  Agg = ST->getElementType(Index);
2680  } else {
2681  // Not a valid type to index into.
2682  return nullptr;
2683  }
2684  }
2685  return const_cast<Type*>(Agg);
2686 }
2687 
2688 //===----------------------------------------------------------------------===//
2689 // UnaryOperator Class
2690 //===----------------------------------------------------------------------===//
2691 
2693  Type *Ty, const Twine &Name,
2694  Instruction *InsertBefore)
2695  : UnaryInstruction(Ty, iType, S, InsertBefore) {
2696  Op<0>() = S;
2697  setName(Name);
2698  AssertOK();
2699 }
2700 
2702  Type *Ty, const Twine &Name,
2703  BasicBlock *InsertAtEnd)
2704  : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
2705  Op<0>() = S;
2706  setName(Name);
2707  AssertOK();
2708 }
2709 
2711  const Twine &Name,
2712  Instruction *InsertBefore) {
2713  return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2714 }
2715 
2717  const Twine &Name,
2718  BasicBlock *InsertAtEnd) {
2719  UnaryOperator *Res = Create(Op, S, Name);
2720  InsertAtEnd->getInstList().push_back(Res);
2721  return Res;
2722 }
2723 
2724 void UnaryOperator::AssertOK() {
2725  Value *LHS = getOperand(0);
2726  (void)LHS; // Silence warnings.
2727 #ifndef NDEBUG
2728  switch (getOpcode()) {
2729  case FNeg:
2730  assert(getType() == LHS->getType() &&
2731  "Unary operation should return same type as operand!");
2732  assert(getType()->isFPOrFPVectorTy() &&
2733  "Tried to create a floating-point operation on a "
2734  "non-floating-point type!");
2735  break;
2736  default: llvm_unreachable("Invalid opcode provided");
2737  }
2738 #endif
2739 }
2740 
2741 //===----------------------------------------------------------------------===//
2742 // BinaryOperator Class
2743 //===----------------------------------------------------------------------===//
2744 
2746  Type *Ty, const Twine &Name,
2747  Instruction *InsertBefore)
2748  : Instruction(Ty, iType,
2749  OperandTraits<BinaryOperator>::op_begin(this),
2750  OperandTraits<BinaryOperator>::operands(this),
2751  InsertBefore) {
2752  Op<0>() = S1;
2753  Op<1>() = S2;
2754  setName(Name);
2755  AssertOK();
2756 }
2757 
2759  Type *Ty, const Twine &Name,
2760  BasicBlock *InsertAtEnd)
2761  : Instruction(Ty, iType,
2762  OperandTraits<BinaryOperator>::op_begin(this),
2763  OperandTraits<BinaryOperator>::operands(this),
2764  InsertAtEnd) {
2765  Op<0>() = S1;
2766  Op<1>() = S2;
2767  setName(Name);
2768  AssertOK();
2769 }
2770 
2771 void BinaryOperator::AssertOK() {
2772  Value *LHS = getOperand(0), *RHS = getOperand(1);
2773  (void)LHS; (void)RHS; // Silence warnings.
2774  assert(LHS->getType() == RHS->getType() &&
2775  "Binary operator operand types must match!");
2776 #ifndef NDEBUG
2777  switch (getOpcode()) {
2778  case Add: case Sub:
2779  case Mul:
2780  assert(getType() == LHS->getType() &&
2781  "Arithmetic operation should return same type as operands!");
2782  assert(getType()->isIntOrIntVectorTy() &&
2783  "Tried to create an integer operation on a non-integer type!");
2784  break;
2785  case FAdd: case FSub:
2786  case FMul:
2787  assert(getType() == LHS->getType() &&
2788  "Arithmetic operation should return same type as operands!");
2789  assert(getType()->isFPOrFPVectorTy() &&
2790  "Tried to create a floating-point operation on a "
2791  "non-floating-point type!");
2792  break;
2793  case UDiv:
2794  case SDiv:
2795  assert(getType() == LHS->getType() &&
2796  "Arithmetic operation should return same type as operands!");
2797  assert(getType()->isIntOrIntVectorTy() &&
2798  "Incorrect operand type (not integer) for S/UDIV");
2799  break;
2800  case FDiv:
2801  assert(getType() == LHS->getType() &&
2802  "Arithmetic operation should return same type as operands!");
2803  assert(getType()->isFPOrFPVectorTy() &&
2804  "Incorrect operand type (not floating point) for FDIV");
2805  break;
2806  case URem:
2807  case SRem:
2808  assert(getType() == LHS->getType() &&
2809  "Arithmetic operation should return same type as operands!");
2810  assert(getType()->isIntOrIntVectorTy() &&
2811  "Incorrect operand type (not integer) for S/UREM");
2812  break;
2813  case FRem:
2814  assert(getType() == LHS->getType() &&
2815  "Arithmetic operation should return same type as operands!");
2816  assert(getType()->isFPOrFPVectorTy() &&
2817  "Incorrect operand type (not floating point) for FREM");
2818  break;
2819  case Shl:
2820  case LShr:
2821  case AShr:
2822  assert(getType() == LHS->getType() &&
2823  "Shift operation should return same type as operands!");
2824  assert(getType()->isIntOrIntVectorTy() &&
2825  "Tried to create a shift operation on a non-integral type!");
2826  break;
2827  case And: case Or:
2828  case Xor:
2829  assert(getType() == LHS->getType() &&
2830  "Logical operation should return same type as operands!");
2831  assert(getType()->isIntOrIntVectorTy() &&
2832  "Tried to create a logical operation on a non-integral type!");
2833  break;
2834  default: llvm_unreachable("Invalid opcode provided");
2835  }
2836 #endif
2837 }
2838 
2840  const Twine &Name,
2841  Instruction *InsertBefore) {
2842  assert(S1->getType() == S2->getType() &&
2843  "Cannot create binary operator with two operands of differing type!");
2844  return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2845 }
2846 
2848  const Twine &Name,
2849  BasicBlock *InsertAtEnd) {
2850  BinaryOperator *Res = Create(Op, S1, S2, Name);
2851  InsertAtEnd->getInstList().push_back(Res);
2852  return Res;
2853 }
2854 
2856  Instruction *InsertBefore) {
2858  return new BinaryOperator(Instruction::Sub,
2859  zero, Op,
2860  Op->getType(), Name, InsertBefore);
2861 }
2862 
2864  BasicBlock *InsertAtEnd) {
2866  return new BinaryOperator(Instruction::Sub,
2867  zero, Op,
2868  Op->getType(), Name, InsertAtEnd);
2869 }
2870 
2872  Instruction *InsertBefore) {
2874  return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2875 }
2876 
2878  BasicBlock *InsertAtEnd) {
2880  return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2881 }
2882 
2884  Instruction *InsertBefore) {
2886  return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2887 }
2888 
2890  BasicBlock *InsertAtEnd) {
2892  return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2893 }
2894 
2896  Instruction *InsertBefore) {
2898  return new BinaryOperator(Instruction::Xor, Op, C,
2899  Op->getType(), Name, InsertBefore);
2900 }
2901 
2903  BasicBlock *InsertAtEnd) {
2905  return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2906  Op->getType(), Name, InsertAtEnd);
2907 }
2908 
2909 // Exchange the two operands to this instruction. This instruction is safe to
2910 // use on any binary instruction and does not modify the semantics of the
2911 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2912 // is changed.
2914  if (!isCommutative())
2915  return true; // Can't commute operands
2916  Op<0>().swap(Op<1>());
2917  return false;
2918 }
2919 
2920 //===----------------------------------------------------------------------===//
2921 // FPMathOperator Class
2922 //===----------------------------------------------------------------------===//
2923 
2925  const MDNode *MD =
2926  cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2927  if (!MD)
2928  return 0.0;
2929  ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2930  return Accuracy->getValueAPF().convertToFloat();
2931 }
2932 
2933 //===----------------------------------------------------------------------===//
2934 // CastInst Class
2935 //===----------------------------------------------------------------------===//
2936 
2937 // Just determine if this cast only deals with integral->integral conversion.
2939  switch (getOpcode()) {
2940  default: return false;
2941  case Instruction::ZExt:
2942  case Instruction::SExt:
2943  case Instruction::Trunc:
2944  return true;
2945  case Instruction::BitCast:
2946  return getOperand(0)->getType()->isIntegerTy() &&
2947  getType()->isIntegerTy();
2948  }
2949 }
2950 
2952  // Only BitCast can be lossless, exit fast if we're not BitCast
2953  if (getOpcode() != Instruction::BitCast)
2954  return false;
2955 
2956  // Identity cast is always lossless
2957  Type *SrcTy = getOperand(0)->getType();
2958  Type *DstTy = getType();
2959  if (SrcTy == DstTy)
2960  return true;
2961 
2962  // Pointer to pointer is always lossless.
2963  if (SrcTy->isPointerTy())
2964  return DstTy->isPointerTy();
2965  return false; // Other types have no identity values
2966 }
2967 
2968 /// This function determines if the CastInst does not require any bits to be
2969 /// changed in order to effect the cast. Essentially, it identifies cases where
2970 /// no code gen is necessary for the cast, hence the name no-op cast. For
2971 /// example, the following are all no-op casts:
2972 /// # bitcast i32* %x to i8*
2973 /// # bitcast <2 x i32> %x to <4 x i16>
2974 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2975 /// Determine if the described cast is a no-op.
2977  Type *SrcTy,
2978  Type *DestTy,
2979  const DataLayout &DL) {
2980  assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
2981  switch (Opcode) {
2982  default: llvm_unreachable("Invalid CastOp");
2983  case Instruction::Trunc:
2984  case Instruction::ZExt:
2985  case Instruction::SExt:
2986  case Instruction::FPTrunc:
2987  case Instruction::FPExt:
2988  case Instruction::UIToFP:
2989  case Instruction::SIToFP:
2990  case Instruction::FPToUI:
2991  case Instruction::FPToSI:
2992  case Instruction::AddrSpaceCast:
2993  // TODO: Target informations may give a more accurate answer here.
2994  return false;
2995  case Instruction::BitCast:
2996  return true; // BitCast never modifies bits.
2997  case Instruction::PtrToInt:
2998  return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2999  DestTy->getScalarSizeInBits();
3000  case Instruction::IntToPtr:
3001  return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
3002  SrcTy->getScalarSizeInBits();
3003  }
3004 }
3005 
3006 bool CastInst::isNoopCast(const DataLayout &DL) const {
3007  return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
3008 }
3009 
3010 /// This function determines if a pair of casts can be eliminated and what
3011 /// opcode should be used in the elimination. This assumes that there are two
3012 /// instructions like this:
3013 /// * %F = firstOpcode SrcTy %x to MidTy
3014 /// * %S = secondOpcode MidTy %F to DstTy
3015 /// The function returns a resultOpcode so these two casts can be replaced with:
3016 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
3017 /// If no such cast is permitted, the function returns 0.
3019  Instruction::CastOps firstOp, Instruction::CastOps secondOp,
3020  Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
3021  Type *DstIntPtrTy) {
3022  // Define the 144 possibilities for these two cast instructions. The values
3023  // in this matrix determine what to do in a given situation and select the
3024  // case in the switch below. The rows correspond to firstOp, the columns
3025  // correspond to secondOp. In looking at the table below, keep in mind
3026  // the following cast properties:
3027  //
3028  // Size Compare Source Destination
3029  // Operator Src ? Size Type Sign Type Sign
3030  // -------- ------------ ------------------- ---------------------
3031  // TRUNC > Integer Any Integral Any
3032  // ZEXT < Integral Unsigned Integer Any
3033  // SEXT < Integral Signed Integer Any
3034  // FPTOUI n/a FloatPt n/a Integral Unsigned
3035  // FPTOSI n/a FloatPt n/a Integral Signed
3036  // UITOFP n/a Integral Unsigned FloatPt n/a
3037  // SITOFP n/a Integral Signed FloatPt n/a
3038  // FPTRUNC > FloatPt n/a FloatPt n/a
3039  // FPEXT < FloatPt n/a FloatPt n/a
3040  // PTRTOINT n/a Pointer n/a Integral Unsigned
3041  // INTTOPTR n/a Integral Unsigned Pointer n/a
3042  // BITCAST = FirstClass n/a FirstClass n/a
3043  // ADDRSPCST n/a Pointer n/a Pointer n/a
3044  //
3045  // NOTE: some transforms are safe, but we consider them to be non-profitable.
3046  // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
3047  // into "fptoui double to i64", but this loses information about the range
3048  // of the produced value (we no longer know the top-part is all zeros).
3049  // Further this conversion is often much more expensive for typical hardware,
3050  // and causes issues when building libgcc. We disallow fptosi+sext for the
3051  // same reason.
3052  const unsigned numCastOps =
3053  Instruction::CastOpsEnd - Instruction::CastOpsBegin;
3054  static const uint8_t CastResults[numCastOps][numCastOps] = {
3055  // T F F U S F F P I B A -+
3056  // R Z S P P I I T P 2 N T S |
3057  // U E E 2 2 2 2 R E I T C C +- secondOp
3058  // N X X U S F F N X N 2 V V |
3059  // C T T I I P P C T T P T T -+
3060  { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
3061  { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
3062  { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
3063  { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
3064  { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
3065  { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
3066  { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
3067  { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
3068  { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
3069  { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
3070  { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
3071  { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
3072  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
3073  };
3074 
3075  // TODO: This logic could be encoded into the table above and handled in the
3076  // switch below.
3077  // If either of the casts are a bitcast from scalar to vector, disallow the
3078  // merging. However, any pair of bitcasts are allowed.
3079  bool IsFirstBitcast = (firstOp == Instruction::BitCast);
3080  bool IsSecondBitcast = (secondOp == Instruction::BitCast);
3081  bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
3082 
3083  // Check if any of the casts convert scalars <-> vectors.
3084  if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
3085  (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
3086  if (!AreBothBitcasts)
3087  return 0;
3088 
3089  int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
3090  [secondOp-Instruction::CastOpsBegin];
3091  switch (ElimCase) {
3092  case 0:
3093  // Categorically disallowed.
3094  return 0;
3095  case 1:
3096  // Allowed, use first cast's opcode.
3097  return firstOp;
3098  case 2:
3099  // Allowed, use second cast's opcode.
3100  return secondOp;
3101  case 3:
3102  // No-op cast in second op implies firstOp as long as the DestTy
3103  // is integer and we are not converting between a vector and a
3104  // non-vector type.
3105  if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
3106  return firstOp;
3107  return 0;
3108  case 4:
3109  // No-op cast in second op implies firstOp as long as the DestTy
3110  // is floating point.
3111  if (DstTy->isFloatingPointTy())
3112  return firstOp;
3113  return 0;
3114  case 5:
3115  // No-op cast in first op implies secondOp as long as the SrcTy
3116  // is an integer.
3117  if (SrcTy->isIntegerTy())
3118  return secondOp;
3119  return 0;
3120  case 6:
3121  // No-op cast in first op implies secondOp as long as the SrcTy
3122  // is a floating point.
3123  if (SrcTy->isFloatingPointTy())
3124  return secondOp;
3125  return 0;
3126  case 7: {
3127  // Disable inttoptr/ptrtoint optimization if enabled.
3128  if (DisableI2pP2iOpt)
3129  return 0;
3130 
3131  // Cannot simplify if address spaces are different!
3132  if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
3133  return 0;
3134 
3135  unsigned MidSize = MidTy->getScalarSizeInBits();
3136  // We can still fold this without knowing the actual sizes as long we
3137  // know that the intermediate pointer is the largest possible
3138  // pointer size.
3139  // FIXME: Is this always true?
3140  if (MidSize == 64)
3141  return Instruction::BitCast;
3142 
3143  // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
3144  if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
3145  return 0;
3146  unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
3147  if (MidSize >= PtrSize)
3148  return Instruction::BitCast;
3149  return 0;
3150  }
3151  case 8: {
3152  // ext, trunc -> bitcast, if the SrcTy and DstTy are the same
3153  // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
3154  // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
3155  unsigned SrcSize = SrcTy->getScalarSizeInBits();
3156  unsigned DstSize = DstTy->getScalarSizeInBits();
3157  if (SrcTy == DstTy)
3158  return Instruction::BitCast;
3159  if (SrcSize < DstSize)
3160  return firstOp;
3161  if (SrcSize > DstSize)
3162  return secondOp;
3163  return 0;
3164  }
3165  case 9:
3166  // zext, sext -> zext, because sext can't sign extend after zext
3167  return Instruction::ZExt;
3168  case 11: {
3169  // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
3170  if (!MidIntPtrTy)
3171  return 0;
3172  unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
3173  unsigned SrcSize = SrcTy->getScalarSizeInBits();
3174  unsigned DstSize = DstTy->getScalarSizeInBits();
3175  if (SrcSize <= PtrSize && SrcSize == DstSize)
3176  return Instruction::BitCast;
3177  return 0;
3178  }
3179  case 12:
3180  // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
3181  // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
3182  if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
3183  return Instruction::AddrSpaceCast;
3184  return Instruction::BitCast;
3185  case 13:
3186  // FIXME: this state can be merged with (1), but the following assert
3187  // is useful to check the correcteness of the sequence due to semantic
3188  // change of bitcast.
3189  assert(
3190  SrcTy->isPtrOrPtrVectorTy() &&
3191  MidTy->isPtrOrPtrVectorTy() &&
3192  DstTy->isPtrOrPtrVectorTy() &&
3193  SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
3194  MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3195  "Illegal addrspacecast, bitcast sequence!");
3196  // Allowed, use first cast's opcode
3197  return firstOp;
3198  case 14: {
3199  // bitcast, addrspacecast -> addrspacecast if the element type of
3200  // bitcast's source is the same as that of addrspacecast's destination.
3201  PointerType *SrcPtrTy = cast<PointerType>(SrcTy->getScalarType());
3202  PointerType *DstPtrTy = cast<PointerType>(DstTy->getScalarType());
3203  if (SrcPtrTy->hasSameElementTypeAs(DstPtrTy))
3204  return Instruction::AddrSpaceCast;
3205  return 0;
3206  }
3207  case 15:
3208  // FIXME: this state can be merged with (1), but the following assert
3209  // is useful to check the correcteness of the sequence due to semantic
3210  // change of bitcast.
3211  assert(
3212  SrcTy->isIntOrIntVectorTy() &&
3213  MidTy->isPtrOrPtrVectorTy() &&
3214  DstTy->isPtrOrPtrVectorTy() &&
3215  MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
3216  "Illegal inttoptr, bitcast sequence!");
3217  // Allowed, use first cast's opcode
3218  return firstOp;
3219  case 16:
3220  // FIXME: this state can be merged with (2), but the following assert
3221  // is useful to check the correcteness of the sequence due to semantic
3222  // change of bitcast.
3223  assert(
3224  SrcTy->isPtrOrPtrVectorTy() &&
3225  MidTy->isPtrOrPtrVectorTy() &&
3226  DstTy->isIntOrIntVectorTy() &&
3227  SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
3228  "Illegal bitcast, ptrtoint sequence!");
3229  // Allowed, use second cast's opcode
3230  return secondOp;
3231  case 17:
3232  // (sitofp (zext x)) -> (uitofp x)
3233  return Instruction::UIToFP;
3234  case 99:
3235  // Cast combination can't happen (error in input). This is for all cases
3236  // where the MidTy is not the same for the two cast instructions.
3237  llvm_unreachable("Invalid Cast Combination");
3238  default:
3239  llvm_unreachable("Error in CastResults table!!!");
3240  }
3241 }
3242 
3244  const Twine &Name, Instruction *InsertBefore) {
3245  assert(castIsValid(op, S, Ty) && "Invalid cast!");
3246  // Construct and return the appropriate CastInst subclass
3247  switch (op) {
3248  case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
3249  case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
3250  case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
3251  case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
3252  case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
3253  case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
3254  case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
3255  case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
3256  case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
3257  case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
3258  case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
3259  case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
3260  case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
3261  default: llvm_unreachable("Invalid opcode provided");
3262  }
3263 }
3264 
3266  const Twine &Name, BasicBlock *InsertAtEnd) {
3267  assert(castIsValid(op, S, Ty) && "Invalid cast!");
3268  // Construct and return the appropriate CastInst subclass
3269  switch (op) {
3270  case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
3271  case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
3272  case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
3273  case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
3274  case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
3275  case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
3276  case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
3277  case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
3278  case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
3279  case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
3280  case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
3281  case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
3282  case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
3283  default: llvm_unreachable("Invalid opcode provided");
3284  }
3285 }
3286 
3288  const Twine &Name,
3289  Instruction *InsertBefore) {
3290  if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3291  return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3292  return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
3293 }
3294 
3296  const Twine &Name,
3297  BasicBlock *InsertAtEnd) {
3298  if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3299  return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
3300  return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
3301 }
3302 
3304  const Twine &Name,
3305  Instruction *InsertBefore) {
3306  if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3307  return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3308  return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
3309 }
3310 
3312  const Twine &Name,
3313  BasicBlock *InsertAtEnd) {
3314  if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3315  return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
3316  return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
3317 }
3318 
3320  const Twine &Name,
3321  Instruction *InsertBefore) {
3322  if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3323  return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3324  return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
3325 }
3326 
3328  const Twine &Name,
3329  BasicBlock *InsertAtEnd) {
3330  if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3331  return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
3332  return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
3333 }
3334 
3336  const Twine &Name,
3337  BasicBlock *InsertAtEnd) {
3338  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3339  assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
3340  "Invalid cast");
3341  assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
3342  assert((!Ty->isVectorTy() ||
3343  cast<VectorType>(Ty)->getElementCount() ==
3344  cast<VectorType>(S->getType())->getElementCount()) &&
3345  "Invalid cast");
3346 
3347  if (Ty->isIntOrIntVectorTy())
3348  return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
3349 
3350  return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
3351 }
3352 
3353 /// Create a BitCast or a PtrToInt cast instruction
3355  const Twine &Name,
3356  Instruction *InsertBefore) {
3357  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3358  assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
3359  "Invalid cast");
3360  assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
3361  assert((!Ty->isVectorTy() ||
3362  cast<VectorType>(Ty)->getElementCount() ==
3363  cast<VectorType>(S->getType())->getElementCount()) &&
3364  "Invalid cast");
3365 
3366  if (Ty->isIntOrIntVectorTy())
3367  return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3368 
3369  return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
3370 }
3371 
3373  Value *S, Type *Ty,
3374  const Twine &Name,
3375  BasicBlock *InsertAtEnd) {
3376  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3377  assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
3378 
3379  if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
3380  return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
3381 
3382  return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
3383 }
3384 
3386  Value *S, Type *Ty,
3387  const Twine &Name,
3388  Instruction *InsertBefore) {
3389  assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3390  assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
3391 
3392  if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
3393  return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
3394 
3395  return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3396 }
3397 
3399  const Twine &Name,
3400  Instruction *InsertBefore) {
3401  if (S->getType()->isPointerTy() && Ty->isIntegerTy())
3402  return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3403  if (S->getType()->isIntegerTy() && Ty->isPointerTy())
3404  return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
3405 
3406  return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3407 }
3408 
3410  bool isSigned, const Twine &Name,
3411  Instruction *InsertBefore) {
3412  assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
3413  "Invalid integer cast");
3414  unsigned SrcBits = C->getType()->getScalarSizeInBits();
3415  unsigned DstBits = Ty->getScalarSizeInBits();
3416  Instruction::CastOps opcode =
3417  (SrcBits == DstBits ? Instruction::BitCast :
3418  (SrcBits > DstBits ? Instruction::Trunc :
3419  (isSigned ? Instruction::SExt : Instruction::ZExt)));
3420  return Create(opcode, C, Ty, Name, InsertBefore);
3421 }
3422 
3424  bool isSigned, const Twine &Name,
3425  BasicBlock *InsertAtEnd) {
3426  assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
3427  "Invalid cast");
3428  unsigned SrcBits = C->getType()->getScalarSizeInBits();
3429  unsigned DstBits = Ty->getScalarSizeInBits();
3430  Instruction::CastOps opcode =
3431  (SrcBits == DstBits ? Instruction::BitCast :
3432  (SrcBits > DstBits ? Instruction::Trunc :
3433  (isSigned ? Instruction::SExt : Instruction::ZExt)));
3434  return Create(opcode, C, Ty, Name, InsertAtEnd);
3435 }
3436 
3438  const Twine &Name,
3439  Instruction *InsertBefore) {
3440  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
3441  "Invalid cast");
3442  unsigned SrcBits = C->getType()->getScalarSizeInBits();
3443  unsigned DstBits = Ty->getScalarSizeInBits();
3444  Instruction::CastOps opcode =
3445  (SrcBits == DstBits ? Instruction::BitCast :
3446  (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
3447  return Create(opcode, C, Ty, Name, InsertBefore);
3448 }
3449 
3451  const Twine &Name,
3452  BasicBlock *InsertAtEnd) {
3453  assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
3454  "Invalid cast");
3455  unsigned SrcBits = C->getType()->getScalarSizeInBits();
3456  unsigned DstBits = Ty->getScalarSizeInBits();
3457  Instruction::CastOps opcode =
3458  (SrcBits == DstBits ? Instruction::BitCast :
3459  (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
3460  return Create(opcode, C, Ty, Name, InsertAtEnd);
3461 }
3462 
3463 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3464  if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3465  return false;
3466 
3467  if (SrcTy == DestTy)
3468  return true;
3469 
3470  if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3471  if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3472  if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3473  // An element by element cast. Valid if casting the elements is valid.
3474  SrcTy = SrcVecTy->getElementType();
3475  DestTy = DestVecTy->getElementType();
3476  }
3477  }
3478  }
3479 
3480  if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3481  if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3482  return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3483  }
3484  }
3485 
3486  TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3487  TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3488 
3489  // Could still have vectors of pointers if the number of elements doesn't
3490  // match
3491  if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
3492  return false;
3493 
3494  if (SrcBits != DestBits)
3495  return false;
3496 
3497  if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
3498  return false;
3499 
3500  return true;
3501 }
3502 
3504  const DataLayout &DL) {
3505  // ptrtoint and inttoptr are not allowed on non-integral pointers
3506  if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3507  if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3508  return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3509  !DL.isNonIntegralPointerType(PtrTy));
3510  if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3511  if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3512  return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3513  !DL.isNonIntegralPointerType(PtrTy));
3514 
3515  return isBitCastable(SrcTy, DestTy);
3516 }
3517 
3518 // Provide a way to get a "cast" where the cast opcode is inferred from the
3519 // types and size of the operand. This, basically, is a parallel of the
3520 // logic in the castIsValid function below. This axiom should hold:
3521 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3522 // should not assert in castIsValid. In other words, this produces a "correct"
3523 // casting opcode for the arguments passed to it.
3526  const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3527  Type *SrcTy = Src->getType();
3528 
3529  assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3530  "Only first class types are castable!");
3531 
3532  if (SrcTy == DestTy)
3533  return BitCast;
3534 
3535  // FIXME: Check address space sizes here
3536  if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3537  if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3538  if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3539  // An element by element cast. Find the appropriate opcode based on the
3540  // element types.
3541  SrcTy = SrcVecTy->getElementType();
3542  DestTy = DestVecTy->getElementType();
3543  }
3544 
3545  // Get the bit sizes, we'll need these
3546  unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3547  unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3548 
3549  // Run through the possibilities ...
3550  if (DestTy->isIntegerTy()) { // Casting to integral
3551  if (SrcTy->isIntegerTy()) { // Casting from integral
3552  if (DestBits < SrcBits)
3553  return Trunc; // int -> smaller int
3554  else if (DestBits > SrcBits) { // its an extension
3555  if (SrcIsSigned)
3556  return SExt; // signed -> SEXT
3557  else
3558  return ZExt; // unsigned -> ZEXT
3559  } else {
3560  return BitCast; // Same size, No-op cast
3561  }
3562  } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3563  if (DestIsSigned)
3564  return FPToSI; // FP -> sint
3565  else
3566  return FPToUI; // FP -> uint
3567  } else if (SrcTy->isVectorTy()) {
3568  assert(DestBits == SrcBits &&
3569  "Casting vector to integer of different width");
3570  return BitCast; // Same size, no-op cast
3571  } else {
3572  assert(SrcTy->isPointerTy() &&
3573  "Casting from a value that is not first-class type");
3574  return PtrToInt; // ptr -> int
3575  }
3576  } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3577  if (SrcTy->isIntegerTy()) { // Casting from integral
3578  if (SrcIsSigned)
3579  return SIToFP; // sint -> FP
3580  else
3581  return UIToFP; // uint -> FP
3582  } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3583  if (DestBits < SrcBits) {
3584  return FPTrunc; // FP -> smaller FP
3585  } else if (DestBits > SrcBits) {
3586  return FPExt; // FP -> larger FP
3587  } else {
3588  return BitCast; // same size, no-op cast
3589  }
3590  } else if (SrcTy->isVectorTy()) {
3591  assert(DestBits == SrcBits &&
3592  "Casting vector to floating point of different width");
3593  return BitCast; // same size, no-op cast
3594  }
3595  llvm_unreachable("Casting pointer or non-first class to float");
3596  } else if (DestTy->isVectorTy()) {
3597  assert(DestBits == SrcBits &&
3598  "Illegal cast to vector (wrong type or size)");
3599  return BitCast;
3600  } else if (DestTy->isPointerTy()) {
3601  if (SrcTy->isPointerTy()) {
3602  if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3603  return AddrSpaceCast;
3604  return BitCast; // ptr -> ptr
3605  } else if (SrcTy->isIntegerTy()) {
3606  return IntToPtr; // int -> ptr
3607  }
3608  llvm_unreachable("Casting pointer to other than pointer or int");
3609  } else if (DestTy->isX86_MMXTy()) {
3610  if (SrcTy->isVectorTy()) {
3611  assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3612  return BitCast; // 64-bit vector to MMX
3613  }
3614  llvm_unreachable("Illegal cast to X86_MMX");
3615  }
3616  llvm_unreachable("Casting to type that is not first-class");
3617 }
3618 
3619 //===----------------------------------------------------------------------===//
3620 // CastInst SubClass Constructors
3621 //===----------------------------------------------------------------------===//
3622 
3623 /// Check that the construction parameters for a CastInst are correct. This
3624 /// could be broken out into the separate constructors but it is useful to have
3625 /// it in one place and to eliminate the redundant code for getting the sizes
3626 /// of the types involved.
3627 bool
3629  if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3630  SrcTy->isAggregateType() || DstTy->isAggregateType())
3631  return false;
3632 
3633  // Get the size of the types in bits, and whether we are dealing
3634  // with vector types, we'll need this later.
3635  bool SrcIsVec = isa<VectorType>(SrcTy);
3636  bool DstIsVec = isa<VectorType>(DstTy);
3637  unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
3638  unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
3639 
3640  // If these are vector types, get the lengths of the vectors (using zero for
3641  // scalar types means that checking that vector lengths match also checks that
3642  // scalars are not being converted to vectors or vectors to scalars).
3643  ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
3645  ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
3647 
3648  // Switch on the opcode provided
3649  switch (op) {
3650  default: return false; // This is an input error
3651  case Instruction::Trunc:
3652  return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3653  SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3654  case Instruction::ZExt:
3655  return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3656  SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3657  case Instruction::SExt:
3658  return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3659  SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3660  case Instruction::FPTrunc:
3661  return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3662  SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3663  case Instruction::FPExt:
3664  return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3665  SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3666  case Instruction::UIToFP:
3667  case Instruction::SIToFP:
3668  return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3669  SrcEC == DstEC;
3670  case Instruction::FPToUI:
3671  case Instruction::FPToSI:
3672  return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3673  SrcEC == DstEC;
3674  case Instruction::PtrToInt:
3675  if (SrcEC != DstEC)
3676  return false;
3677  return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3678  case Instruction::IntToPtr:
3679  if (SrcEC != DstEC)
3680  return false;
3681  return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3682  case Instruction::BitCast: {
3683  PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3684  PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3685 
3686  // BitCast implies a no-op cast of type only. No bits change.
3687  // However, you can't cast pointers to anything but pointers.
3688  if (!SrcPtrTy != !DstPtrTy)
3689  return false;
3690 
3691  // For non-pointer cases, the cast is okay if the source and destination bit
3692  // widths are identical.
3693  if (!SrcPtrTy)
3694  return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3695 
3696  // If both are pointers then the address spaces must match.
3697  if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3698  return false;
3699 
3700  // A vector of pointers must have the same number of elements.
3701  if (SrcIsVec && DstIsVec)
3702  return SrcEC == DstEC;
3703  if (SrcIsVec)
3704  return SrcEC == ElementCount::getFixed(1);
3705  if (DstIsVec)
3706  return DstEC == ElementCount::getFixed(1);
3707 
3708  return true;
3709  }
3710  case Instruction::AddrSpaceCast: {
3711  PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3712  if (!SrcPtrTy)
3713  return false;
3714 
3715  PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3716  if (!DstPtrTy)
3717  return false;
3718 
3719  if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3720  return false;
3721 
3722  return SrcEC == DstEC;
3723  }
3724  }
3725 }
3726 
3728  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3729 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3730  assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3731 }
3732 
3734  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3735 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3736  assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3737 }
3738 
3740  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3741 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3742  assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3743 }
3744 
3746  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3747 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3748  assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3749 }
3751  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3752 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3753  assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3754 }
3755 
3757  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3758 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3759  assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3760 }
3761 
3763  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3764 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3765  assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3766 }
3767 
3769  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3770 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3771  assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3772 }
3773 
3775  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3776 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3777  assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3778 }
3779 
3781  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3782 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3783  assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3784 }
3785 
3787  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3788 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3789  assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3790 }
3791 
3793  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3794 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3795  assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3796 }
3797 
3799  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3800 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3801  assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3802 }
3803 
3805  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3806 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3807  assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3808 }
3809 
3811  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3812 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3813  assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3814 }
3815 
3817  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3818 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3819  assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3820 }
3821 
3823  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3824 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3825  assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3826 }
3827 
3829  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3830 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3831  assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3832 }
3833 
3835  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3836 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3837  assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3838 }
3839 
3841  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3842 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3843  assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3844 }
3845 
3847  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3848 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3849  assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3850 }
3851 
3853  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3854 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3855  assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3856 }
3857 
3859  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3860 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3861  assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3862 }
3863 
3865  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3866 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3867  assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3868 }
3869 
3871  Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3872 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3873  assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3874 }
3875 
3877  Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3878 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3879  assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3880 }
3881 
3882 //===----------------------------------------------------------------------===//
3883 // CmpInst Classes
3884 //===----------------------------------------------------------------------===//
3885 
3887  Value *RHS, const Twine &Name, Instruction *InsertBefore,
3888  Instruction *FlagsSource)
3889  : Instruction(ty, op,
3890  OperandTraits<CmpInst>::op_begin(this),
3891  OperandTraits<CmpInst>::operands(this),
3892  InsertBefore) {
3893  Op<0>() = LHS;
3894  Op<1>() = RHS;
3895  setPredicate((Predicate)predicate);
3896  setName(Name);
3897  if (FlagsSource)
3898  copyIRFlags(FlagsSource);
3899 }
3900 
3902  Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
3903  : Instruction(ty, op,
3904  OperandTraits<CmpInst>::op_begin(this),
3905  OperandTraits<CmpInst>::operands(this),
3906  InsertAtEnd) {
3907  Op<0>() = LHS;
3908  Op<1>() = RHS;
3909  setPredicate((Predicate)predicate);
3910  setName(Name);
3911 }
3912 
3913 CmpInst *
3915  const Twine &Name, Instruction *InsertBefore) {
3916  if (Op == Instruction::ICmp) {
3917  if (InsertBefore)
3918  return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3919  S1, S2, Name);
3920  else
3921  return new ICmpInst(CmpInst::Predicate(predicate),
3922  S1, S2, Name);
3923  }
3924 
3925  if (InsertBefore)
3926  return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3927  S1, S2, Name);
3928  else
3929  return new FCmpInst(CmpInst::Predicate(predicate),
3930  S1, S2, Name);
3931 }
3932 
3933 CmpInst *
3935  const Twine &Name, BasicBlock *InsertAtEnd) {
3936  if (Op == Instruction::ICmp) {
3937  return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3938  S1, S2, Name);
3939  }
3940  return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3941  S1, S2, Name);
3942 }
3943 
3945  if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3946  IC->swapOperands();
3947  else
3948  cast<FCmpInst>(this)->swapOperands();
3949 }
3950 
3952  if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3953  return IC->isCommutative();
3954  return cast<FCmpInst>(this)->isCommutative();
3955 }
3956 
3959  return ICmpInst::isEquality(P);
3961  return FCmpInst::isEquality(P);
3962  llvm_unreachable("Unsupported predicate kind");
3963 }
3964 
3966  switch (pred) {
3967  default: llvm_unreachable("Unknown cmp predicate!");
3968  case ICMP_EQ: return ICMP_NE;
3969  case ICMP_NE: return ICMP_EQ;
3970  case ICMP_UGT: return ICMP_ULE;
3971  case ICMP_ULT: return ICMP_UGE;
3972  case ICMP_UGE: return ICMP_ULT;
3973  case ICMP_ULE: return ICMP_UGT;
3974  case ICMP_SGT: return ICMP_SLE;
3975  case ICMP_SLT: return ICMP_SGE;
3976  case ICMP_SGE: return ICMP_SLT;
3977  case ICMP_SLE: return ICMP_SGT;
3978 
3979  case FCMP_OEQ: return FCMP_UNE;
3980  case FCMP_ONE: return FCMP_UEQ;
3981  case FCMP_OGT: return FCMP_ULE;
3982  case FCMP_OLT: return FCMP_UGE;
3983  case FCMP_OGE: return FCMP_ULT;
3984  case FCMP_OLE: return FCMP_UGT;
3985  case FCMP_UEQ: return FCMP_ONE;
3986  case FCMP_UNE: return FCMP_OEQ;
3987  case FCMP_UGT: return FCMP_OLE;
3988  case FCMP_ULT: return FCMP_OGE;
3989  case FCMP_UGE: return FCMP_OLT;
3990  case FCMP_ULE: return FCMP_OGT;
3991  case FCMP_ORD: return FCMP_UNO;
3992  case FCMP_UNO: return FCMP_ORD;
3993  case FCMP_TRUE: return FCMP_FALSE;
3994  case FCMP_FALSE: return FCMP_TRUE;
3995  }
3996 }
3997 
3999  switch (Pred) {
4000  default: return "unknown";
4001  case FCmpInst::FCMP_FALSE: return "false";
4002  case FCmpInst::FCMP_OEQ: return "oeq";
4003  case FCmpInst::FCMP_OGT: return "ogt";
4004  case FCmpInst::FCMP_OGE: return "oge";
4005  case FCmpInst::FCMP_OLT: return "olt";
4006  case FCmpInst::FCMP_OLE: return "ole";
4007  case FCmpInst::FCMP_ONE: return "one";
4008  case FCmpInst::FCMP_ORD: return "ord";
4009  case FCmpInst::FCMP_UNO: return "uno";
4010  case FCmpInst::FCMP_UEQ: return "ueq";
4011  case FCmpInst::FCMP_UGT: return "ugt";
4012  case FCmpInst::FCMP_UGE: return "uge";
4013  case FCmpInst::FCMP_ULT: return "ult";
4014  case FCmpInst::FCMP_ULE: return "ule";
4015  case FCmpInst::FCMP_UNE: return "une";
4016  case FCmpInst::FCMP_TRUE: return "true";
4017  case ICmpInst::ICMP_EQ: return "eq";
4018  case ICmpInst::ICMP_NE: return "ne";
4019  case ICmpInst::ICMP_SGT: return "sgt";
4020  case ICmpInst::ICMP_SGE: return "sge";
4021  case ICmpInst::ICMP_SLT: return "slt";
4022  case ICmpInst::ICMP_SLE: return "sle";
4023  case ICmpInst::ICMP_UGT: return "ugt";
4024  case ICmpInst::ICMP_UGE: return "uge";
4025  case ICmpInst::ICMP_ULT: return "ult";
4026  case ICmpInst::ICMP_ULE: return "ule";
4027  }
4028 }
4029 
4031  switch (pred) {
4032  default: llvm_unreachable("Unknown icmp predicate!");
4033  case ICMP_EQ: case ICMP_NE:
4034  case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
4035  return pred;
4036  case ICMP_UGT: return ICMP_SGT;
4037  case ICMP_ULT: return ICMP_SLT;
4038  case ICMP_UGE: return ICMP_SGE;
4039  case ICMP_ULE: return ICMP_SLE;
4040  }
4041 }
4042 
4044  switch (pred) {
4045  default: llvm_unreachable("Unknown icmp predicate!");
4046  case ICMP_EQ: case ICMP_NE:
4047  case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
4048  return pred;
4049  case ICMP_SGT: return ICMP_UGT;
4050  case ICMP_SLT: return ICMP_ULT;
4051  case ICMP_SGE: return ICMP_UGE;
4052  case ICMP_SLE: return ICMP_ULE;
4053  }
4054 }
4055 
4057  switch (pred) {
4058  default: llvm_unreachable("Unknown cmp predicate!");
4059  case ICMP_EQ: case ICMP_NE:
4060  return pred;
4061  case ICMP_SGT: return ICMP_SLT;
4062  case ICMP_SLT: return ICMP_SGT;
4063  case ICMP_SGE: return ICMP_SLE;
4064  case ICMP_SLE: return ICMP_SGE;
4065  case ICMP_UGT: return ICMP_ULT;
4066  case ICMP_ULT: return ICMP_UGT;
4067  case ICMP_UGE: return ICMP_ULE;
4068  case ICMP_ULE: return ICMP_UGE;
4069 
4070  case FCMP_FALSE: case FCMP_TRUE:
4071  case FCMP_OEQ: case FCMP_ONE:
4072  case FCMP_UEQ: case FCMP_UNE:
4073  case FCMP_ORD: case FCMP_UNO:
4074  return pred;
4075  case FCMP_OGT: return FCMP_OLT;
4076  case FCMP_OLT: return FCMP_OGT;
4077  case FCMP_OGE: return FCMP_OLE;
4078  case FCMP_OLE: return FCMP_OGE;
4079  case FCMP_UGT: return FCMP_ULT;
4080  case FCMP_ULT: return FCMP_UGT;
4081  case FCMP_UGE: return FCMP_ULE;
4082  case FCMP_ULE: return FCMP_UGE;
4083  }
4084 }
4085 
4087  switch (pred) {
4088  case ICMP_SGE:
4089  case ICMP_SLE:
4090  case ICMP_UGE:
4091  case ICMP_ULE:
4092  case FCMP_OGE:
4093  case FCMP_OLE:
4094  case FCMP_UGE:
4095  case FCMP_ULE:
4096  return true;
4097  default:
4098  return false;
4099  }
4100 }
4101 
4103  switch (pred) {
4104  case ICMP_SGT:
4105  case ICMP_SLT:
4106  case ICMP_UGT:
4107  case ICMP_ULT:
4108  case FCMP_OGT:
4109  case FCMP_OLT:
4110  case FCMP_UGT:
4111  case FCMP_ULT:
4112  return true;
4113  default:
4114  return false;
4115  }
4116 }
4117 
4119  switch (pred) {
4120  case ICMP_SGE:
4121  return ICMP_SGT;
4122  case ICMP_SLE:
4123  return ICMP_SLT;
4124  case ICMP_UGE:
4125  return ICMP_UGT;
4126  case ICMP_ULE:
4127  return ICMP_ULT;
4128  case FCMP_OGE:
4129  return FCMP_OGT;
4130  case FCMP_OLE:
4131  return FCMP_OLT;
4132  case FCMP_UGE:
4133  return FCMP_UGT;
4134  case FCMP_ULE:
4135  return FCMP_ULT;
4136  default:
4137  return pred;
4138  }
4139 }
4140 
4142  switch (pred) {
4143  case ICMP_SGT:
4144  return ICMP_SGE;
4145  case ICMP_SLT:
4146  return ICMP_SLE;
4147  case ICMP_UGT:
4148  return ICMP_UGE;
4149  case ICMP_ULT:
4150  return ICMP_ULE;
4151  case FCMP_OGT:
4152  return FCMP_OGE;
4153  case FCMP_OLT:
4154  return FCMP_OLE;
4155  case FCMP_UGT:
4156  return FCMP_UGE;
4157  case FCMP_ULT:
4158  return FCMP_ULE;
4159  default:
4160  return pred;
4161  }
4162 }
4163 
4165  assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
4166 
4167  if (isStrictPredicate(pred))
4168  return getNonStrictPredicate(pred);
4170  return getStrictPredicate(pred);
4171 
4172  llvm_unreachable("Unknown predicate!");
4173 }
4174 
4176  assert(CmpInst::isUnsigned(pred) && "Call only with unsigned predicates!");
4177 
4178  switch (pred) {
4179  default:
4180  llvm_unreachable("Unknown predicate!");
4181  case CmpInst::ICMP_ULT:
4182  return CmpInst::ICMP_SLT;
4183  case CmpInst::ICMP_ULE:
4184  return CmpInst::ICMP_SLE;
4185  case CmpInst::ICMP_UGT:
4186  return CmpInst::ICMP_SGT;
4187  case CmpInst::ICMP_UGE:
4188  return CmpInst::ICMP_SGE;
4189  }
4190 }
4191 
4193  assert(CmpInst::isSigned(pred) && "Call only with signed predicates!");
4194 
4195  switch (pred) {
4196  default:
4197  llvm_unreachable("Unknown predicate!");
4198  case CmpInst::ICMP_SLT:
4199  return CmpInst::ICMP_ULT;
4200  case CmpInst::ICMP_SLE:
4201  return CmpInst::ICMP_ULE;
4202  case CmpInst::ICMP_SGT:
4203  return CmpInst::ICMP_UGT;
4204  case CmpInst::ICMP_SGE:
4205  return CmpInst::ICMP_UGE;
4206  }
4207 }
4208 
4210  switch (predicate) {
4211  default: return false;
4213  case ICmpInst::ICMP_UGE: return true;
4214  }
4215 }
4216 
4217 bool CmpInst::isSigned(Predicate predicate) {
4218  switch (predicate) {
4219  default: return false;
4221  case ICmpInst::ICMP_SGE: return true;
4222  }
4223 }
4224 
4225 bool ICmpInst::compare(const APInt &LHS, const APInt &RHS,
4226  ICmpInst::Predicate Pred) {
4227  assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!");
4228  switch (Pred) {
4229  case ICmpInst::Predicate::ICMP_EQ:
4230  return LHS.eq(RHS);
4231  case ICmpInst::Predicate::ICMP_NE:
4232  return LHS.ne(RHS);
4233  case ICmpInst::Predicate::ICMP_UGT:
4234  return LHS.ugt(RHS);
4235  case ICmpInst::Predicate::ICMP_UGE:
4236  return LHS.uge(RHS);
4237  case ICmpInst::Predicate::ICMP_ULT:
4238  return LHS.ult(RHS);
4239  case ICmpInst::Predicate::ICMP_ULE:
4240  return LHS.ule(RHS);
4241  case ICmpInst::Predicate::ICMP_SGT:
4242  return LHS.sgt(RHS);
4243  case ICmpInst::Predicate::ICMP_SGE:
4244  return LHS.sge(RHS);
4245  case ICmpInst::Predicate::ICMP_SLT:
4246  return LHS.slt(RHS);
4247  case ICmpInst::Predicate::ICMP_SLE:
4248  return LHS.sle(RHS);
4249  default:
4250  llvm_unreachable("Unexpected non-integer predicate.");
4251  };
4252 }
4253 
4255  FCmpInst::Predicate Pred) {
4256  APFloat::cmpResult R = LHS.compare(RHS);
4257  switch (Pred) {
4258  default:
4259  llvm_unreachable("Invalid FCmp Predicate");
4260  case FCmpInst::FCMP_FALSE:
4261  return false;
4262  case FCmpInst::FCMP_TRUE:
4263  return true;
4264  case FCmpInst::FCMP_UNO:
4265  return R == APFloat::cmpUnordered;
4266  case FCmpInst::FCMP_ORD:
4267  return R != APFloat::cmpUnordered;
4268  case FCmpInst::FCMP_UEQ:
4269  return R == APFloat::cmpUnordered || R == APFloat::cmpEqual;
4270  case FCmpInst::FCMP_OEQ:
4271  return R == APFloat::cmpEqual;
4272  case FCmpInst::FCMP_UNE:
4273  return R != APFloat::cmpEqual;
4274  case FCmpInst::FCMP_ONE:
4275  return R == APFloat::cmpLessThan || R == APFloat::cmpGreaterThan;
4276  case FCmpInst::FCMP_ULT:
4277  return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan;
4278  case FCmpInst::FCMP_OLT:
4279  return R == APFloat::cmpLessThan;
4280  case FCmpInst::FCMP_UGT:
4281  return R == APFloat::cmpUnordered || R == APFloat::cmpGreaterThan;
4282  case FCmpInst::FCMP_OGT:
4283  return R == APFloat::cmpGreaterThan;
4284  case FCmpInst::FCMP_ULE:
4285  return R != APFloat::cmpGreaterThan;
4286  case FCmpInst::FCMP_OLE:
4287  return R == APFloat::cmpLessThan || R == APFloat::cmpEqual;
4288  case FCmpInst::FCMP_UGE:
4289  return R != APFloat::cmpLessThan;
4290  case FCmpInst::FCMP_OGE:
4291  return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual;
4292  }
4293 }
4294 
4297  "Call only with non-equality predicates!");
4298 
4299  if (isSigned(pred))
4300  return getUnsignedPredicate(pred);
4301  if (isUnsigned(pred))
4302  return getSignedPredicate(pred);
4303 
4304  llvm_unreachable("Unknown predicate!");
4305 }
4306 
4308  switch (predicate) {
4309  default: return false;
4312  case FCmpInst::FCMP_ORD: return true;
4313  }
4314 }
4315 
4317  switch (predicate) {
4318  default: return false;
4321  case FCmpInst::FCMP_UNO: return true;
4322  }
4323 }
4324 
4326  switch(predicate) {
4327  default: return false;
4328  case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
4329  case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
4330  }
4331 }
4332 
4334  switch(predicate) {
4335  case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
4336  case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
4337  default: return false;
4338  }
4339 }
4340 
4342  // If the predicates match, then we know the first condition implies the
4343  // second is true.
4344  if (Pred1 == Pred2)
4345  return true;
4346 
4347  switch (Pred1) {
4348  default:
4349  break;
4350  case ICMP_EQ:
4351  // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
4352  return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
4353  Pred2 == ICMP_SLE;
4354  case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
4355  return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
4356  case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
4357  return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
4358  case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
4359  return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
4360  case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
4361  return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
4362  }
4363  return false;
4364 }
4365 
4367  return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
4368 }
4369 
4370 //===----------------------------------------------------------------------===//
4371 // SwitchInst Implementation
4372 //===----------------------------------------------------------------------===//
4373 
4374 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
4375  assert(Value && Default && NumReserved);
4376  ReservedSpace = NumReserved;
4378  allocHungoffUses(ReservedSpace);
4379 
4380  Op<0>() = Value;
4381  Op<1>() = Default;
4382 }
4383 
4384 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
4385 /// switch on and a default destination. The number of additional cases can
4386 /// be specified here to make memory allocation more efficient. This
4387 /// constructor can also autoinsert before another instruction.
4388 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
4389  Instruction *InsertBefore)
4390  : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
4391  nullptr, 0, InsertBefore) {
4392  init(Value, Default, 2+NumCases*2);
4393 }
4394 
4395 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
4396 /// switch on and a default destination. The number of additional cases can
4397 /// be specified here to make memory allocation more efficient. This
4398 /// constructor also autoinserts at the end of the specified BasicBlock.
4399 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
4400  BasicBlock *InsertAtEnd)
4401  : Instruction(