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