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