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