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