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   if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask))
1891     return CDS->getElementAsInteger(i);
1892   Constant *C = Mask->getAggregateElement(i);
1893   if (isa<UndefValue>(C))
1894     return -1;
1895   return cast<ConstantInt>(C)->getZExtValue();
1896 }
1897 
1898 void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
1899                                        SmallVectorImpl<int> &Result) {
1900   unsigned NumElts = Mask->getType()->getVectorNumElements();
1901 
1902   if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1903     for (unsigned i = 0; i != NumElts; ++i)
1904       Result.push_back(CDS->getElementAsInteger(i));
1905     return;
1906   }
1907   for (unsigned i = 0; i != NumElts; ++i) {
1908     Constant *C = Mask->getAggregateElement(i);
1909     Result.push_back(isa<UndefValue>(C) ? -1 :
1910                      cast<ConstantInt>(C)->getZExtValue());
1911   }
1912 }
1913 
1914 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1915   assert(!Mask.empty() && "Shuffle mask must contain elements");
1916   bool UsesLHS = false;
1917   bool UsesRHS = false;
1918   for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
1919     if (Mask[i] == -1)
1920       continue;
1921     assert(Mask[i] >= 0 && Mask[i] < (NumOpElts * 2) &&
1922            "Out-of-bounds shuffle mask element");
1923     UsesLHS |= (Mask[i] < NumOpElts);
1924     UsesRHS |= (Mask[i] >= NumOpElts);
1925     if (UsesLHS && UsesRHS)
1926       return false;
1927   }
1928   assert((UsesLHS ^ UsesRHS) && "Should have selected from exactly 1 source");
1929   return true;
1930 }
1931 
1932 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
1933   // We don't have vector operand size information, so assume operands are the
1934   // same size as the mask.
1935   return isSingleSourceMaskImpl(Mask, Mask.size());
1936 }
1937 
1938 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
1939   if (!isSingleSourceMaskImpl(Mask, NumOpElts))
1940     return false;
1941   for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
1942     if (Mask[i] == -1)
1943       continue;
1944     if (Mask[i] != i && Mask[i] != (NumOpElts + i))
1945       return false;
1946   }
1947   return true;
1948 }
1949 
1950 bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
1951   // We don't have vector operand size information, so assume operands are the
1952   // same size as the mask.
1953   return isIdentityMaskImpl(Mask, Mask.size());
1954 }
1955 
1956 bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
1957   if (!isSingleSourceMask(Mask))
1958     return false;
1959   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1960     if (Mask[i] == -1)
1961       continue;
1962     if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
1963       return false;
1964   }
1965   return true;
1966 }
1967 
1968 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
1969   if (!isSingleSourceMask(Mask))
1970     return false;
1971   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1972     if (Mask[i] == -1)
1973       continue;
1974     if (Mask[i] != 0 && Mask[i] != NumElts)
1975       return false;
1976   }
1977   return true;
1978 }
1979 
1980 bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
1981   // Select is differentiated from identity. It requires using both sources.
1982   if (isSingleSourceMask(Mask))
1983     return false;
1984   for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
1985     if (Mask[i] == -1)
1986       continue;
1987     if (Mask[i] != i && Mask[i] != (NumElts + i))
1988       return false;
1989   }
1990   return true;
1991 }
1992 
1993 bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
1994   // Example masks that will return true:
1995   // v1 = <a, b, c, d>
1996   // v2 = <e, f, g, h>
1997   // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
1998   // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
1999 
2000   // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2001   int NumElts = Mask.size();
2002   if (NumElts < 2 || !isPowerOf2_32(NumElts))
2003     return false;
2004 
2005   // 2. The first element of the mask must be either a 0 or a 1.
2006   if (Mask[0] != 0 && Mask[0] != 1)
2007     return false;
2008 
2009   // 3. The difference between the first 2 elements must be equal to the
2010   // number of elements in the mask.
2011   if ((Mask[1] - Mask[0]) != NumElts)
2012     return false;
2013 
2014   // 4. The difference between consecutive even-numbered and odd-numbered
2015   // elements must be equal to 2.
2016   for (int i = 2; i < NumElts; ++i) {
2017     int MaskEltVal = Mask[i];
2018     if (MaskEltVal == -1)
2019       return false;
2020     int MaskEltPrevVal = Mask[i - 2];
2021     if (MaskEltVal - MaskEltPrevVal != 2)
2022       return false;
2023   }
2024   return true;
2025 }
2026 
2027 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
2028                                                int NumSrcElts, int &Index) {
2029   // Must extract from a single source.
2030   if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2031     return false;
2032 
2033   // Must be smaller (else this is an Identity shuffle).
2034   if (NumSrcElts <= (int)Mask.size())
2035     return false;
2036 
2037   // Find start of extraction, accounting that we may start with an UNDEF.
2038   int SubIndex = -1;
2039   for (int i = 0, e = Mask.size(); i != e; ++i) {
2040     int M = Mask[i];
2041     if (M < 0)
2042       continue;
2043     int Offset = (M % NumSrcElts) - i;
2044     if (0 <= SubIndex && SubIndex != Offset)
2045       return false;
2046     SubIndex = Offset;
2047   }
2048 
2049   if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
2050     Index = SubIndex;
2051     return true;
2052   }
2053   return false;
2054 }
2055 
2056 bool ShuffleVectorInst::isIdentityWithPadding() const {
2057   int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2058   int NumMaskElts = getType()->getVectorNumElements();
2059   if (NumMaskElts <= NumOpElts)
2060     return false;
2061 
2062   // The first part of the mask must choose elements from exactly 1 source op.
2063   SmallVector<int, 16> Mask = getShuffleMask();
2064   if (!isIdentityMaskImpl(Mask, NumOpElts))
2065     return false;
2066 
2067   // All extending must be with undef elements.
2068   for (int i = NumOpElts; i < NumMaskElts; ++i)
2069     if (Mask[i] != -1)
2070       return false;
2071 
2072   return true;
2073 }
2074 
2075 bool ShuffleVectorInst::isIdentityWithExtract() const {
2076   int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2077   int NumMaskElts = getType()->getVectorNumElements();
2078   if (NumMaskElts >= NumOpElts)
2079     return false;
2080 
2081   return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2082 }
2083 
2084 bool ShuffleVectorInst::isConcat() const {
2085   // Vector concatenation is differentiated from identity with padding.
2086   if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()))
2087     return false;
2088 
2089   int NumOpElts = Op<0>()->getType()->getVectorNumElements();
2090   int NumMaskElts = getType()->getVectorNumElements();
2091   if (NumMaskElts != NumOpElts * 2)
2092     return false;
2093 
2094   // Use the mask length rather than the operands' vector lengths here. We
2095   // already know that the shuffle returns a vector twice as long as the inputs,
2096   // and neither of the inputs are undef vectors. If the mask picks consecutive
2097   // elements from both inputs, then this is a concatenation of the inputs.
2098   return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2099 }
2100 
2101 //===----------------------------------------------------------------------===//
2102 //                             InsertValueInst Class
2103 //===----------------------------------------------------------------------===//
2104 
2105 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2106                            const Twine &Name) {
2107   assert(getNumOperands() == 2 && "NumOperands not initialized?");
2108 
2109   // There's no fundamental reason why we require at least one index
2110   // (other than weirdness with &*IdxBegin being invalid; see
2111   // getelementptr's init routine for example). But there's no
2112   // present need to support it.
2113   assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2114 
2115   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
2116          Val->getType() && "Inserted value must match indexed type!");
2117   Op<0>() = Agg;
2118   Op<1>() = Val;
2119 
2120   Indices.append(Idxs.begin(), Idxs.end());
2121   setName(Name);
2122 }
2123 
2124 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2125   : Instruction(IVI.getType(), InsertValue,
2126                 OperandTraits<InsertValueInst>::op_begin(this), 2),
2127     Indices(IVI.Indices) {
2128   Op<0>() = IVI.getOperand(0);
2129   Op<1>() = IVI.getOperand(1);
2130   SubclassOptionalData = IVI.SubclassOptionalData;
2131 }
2132 
2133 //===----------------------------------------------------------------------===//
2134 //                             ExtractValueInst Class
2135 //===----------------------------------------------------------------------===//
2136 
2137 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2138   assert(getNumOperands() == 1 && "NumOperands not initialized?");
2139 
2140   // There's no fundamental reason why we require at least one index.
2141   // But there's no present need to support it.
2142   assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2143 
2144   Indices.append(Idxs.begin(), Idxs.end());
2145   setName(Name);
2146 }
2147 
2148 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2149   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
2150     Indices(EVI.Indices) {
2151   SubclassOptionalData = EVI.SubclassOptionalData;
2152 }
2153 
2154 // getIndexedType - Returns the type of the element that would be extracted
2155 // with an extractvalue instruction with the specified parameters.
2156 //
2157 // A null type is returned if the indices are invalid for the specified
2158 // pointer type.
2159 //
2160 Type *ExtractValueInst::getIndexedType(Type *Agg,
2161                                        ArrayRef<unsigned> Idxs) {
2162   for (unsigned Index : Idxs) {
2163     // We can't use CompositeType::indexValid(Index) here.
2164     // indexValid() always returns true for arrays because getelementptr allows
2165     // out-of-bounds indices. Since we don't allow those for extractvalue and
2166     // insertvalue we need to check array indexing manually.
2167     // Since the only other types we can index into are struct types it's just
2168     // as easy to check those manually as well.
2169     if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2170       if (Index >= AT->getNumElements())
2171         return nullptr;
2172     } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2173       if (Index >= ST->getNumElements())
2174         return nullptr;
2175     } else {
2176       // Not a valid type to index into.
2177       return nullptr;
2178     }
2179 
2180     Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
2181   }
2182   return const_cast<Type*>(Agg);
2183 }
2184 
2185 //===----------------------------------------------------------------------===//
2186 //                             UnaryOperator Class
2187 //===----------------------------------------------------------------------===//
2188 
2189 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2190                              Type *Ty, const Twine &Name,
2191                              Instruction *InsertBefore)
2192   : UnaryInstruction(Ty, iType, S, InsertBefore) {
2193   Op<0>() = S;
2194   setName(Name);
2195   AssertOK();
2196 }
2197 
2198 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2199                              Type *Ty, const Twine &Name,
2200                              BasicBlock *InsertAtEnd)
2201   : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
2202   Op<0>() = S;
2203   setName(Name);
2204   AssertOK();
2205 }
2206 
2207 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2208                                      const Twine &Name,
2209                                      Instruction *InsertBefore) {
2210   return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2211 }
2212 
2213 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2214                                      const Twine &Name,
2215                                      BasicBlock *InsertAtEnd) {
2216   UnaryOperator *Res = Create(Op, S, Name);
2217   InsertAtEnd->getInstList().push_back(Res);
2218   return Res;
2219 }
2220 
2221 void UnaryOperator::AssertOK() {
2222   Value *LHS = getOperand(0);
2223   (void)LHS; // Silence warnings.
2224 #ifndef NDEBUG
2225   switch (getOpcode()) {
2226   case FNeg:
2227     assert(getType() == LHS->getType() &&
2228            "Unary operation should return same type as operand!");
2229     assert(getType()->isFPOrFPVectorTy() &&
2230            "Tried to create a floating-point operation on a "
2231            "non-floating-point type!");
2232     break;
2233   default: llvm_unreachable("Invalid opcode provided");
2234   }
2235 #endif
2236 }
2237 
2238 //===----------------------------------------------------------------------===//
2239 //                             BinaryOperator Class
2240 //===----------------------------------------------------------------------===//
2241 
2242 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2243                                Type *Ty, const Twine &Name,
2244                                Instruction *InsertBefore)
2245   : Instruction(Ty, iType,
2246                 OperandTraits<BinaryOperator>::op_begin(this),
2247                 OperandTraits<BinaryOperator>::operands(this),
2248                 InsertBefore) {
2249   Op<0>() = S1;
2250   Op<1>() = S2;
2251   setName(Name);
2252   AssertOK();
2253 }
2254 
2255 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2256                                Type *Ty, const Twine &Name,
2257                                BasicBlock *InsertAtEnd)
2258   : Instruction(Ty, iType,
2259                 OperandTraits<BinaryOperator>::op_begin(this),
2260                 OperandTraits<BinaryOperator>::operands(this),
2261                 InsertAtEnd) {
2262   Op<0>() = S1;
2263   Op<1>() = S2;
2264   setName(Name);
2265   AssertOK();
2266 }
2267 
2268 void BinaryOperator::AssertOK() {
2269   Value *LHS = getOperand(0), *RHS = getOperand(1);
2270   (void)LHS; (void)RHS; // Silence warnings.
2271   assert(LHS->getType() == RHS->getType() &&
2272          "Binary operator operand types must match!");
2273 #ifndef NDEBUG
2274   switch (getOpcode()) {
2275   case Add: case Sub:
2276   case Mul:
2277     assert(getType() == LHS->getType() &&
2278            "Arithmetic operation should return same type as operands!");
2279     assert(getType()->isIntOrIntVectorTy() &&
2280            "Tried to create an integer operation on a non-integer type!");
2281     break;
2282   case FAdd: case FSub:
2283   case FMul:
2284     assert(getType() == LHS->getType() &&
2285            "Arithmetic operation should return same type as operands!");
2286     assert(getType()->isFPOrFPVectorTy() &&
2287            "Tried to create a floating-point operation on a "
2288            "non-floating-point type!");
2289     break;
2290   case UDiv:
2291   case SDiv:
2292     assert(getType() == LHS->getType() &&
2293            "Arithmetic operation should return same type as operands!");
2294     assert(getType()->isIntOrIntVectorTy() &&
2295            "Incorrect operand type (not integer) for S/UDIV");
2296     break;
2297   case FDiv:
2298     assert(getType() == LHS->getType() &&
2299            "Arithmetic operation should return same type as operands!");
2300     assert(getType()->isFPOrFPVectorTy() &&
2301            "Incorrect operand type (not floating point) for FDIV");
2302     break;
2303   case URem:
2304   case SRem:
2305     assert(getType() == LHS->getType() &&
2306            "Arithmetic operation should return same type as operands!");
2307     assert(getType()->isIntOrIntVectorTy() &&
2308            "Incorrect operand type (not integer) for S/UREM");
2309     break;
2310   case FRem:
2311     assert(getType() == LHS->getType() &&
2312            "Arithmetic operation should return same type as operands!");
2313     assert(getType()->isFPOrFPVectorTy() &&
2314            "Incorrect operand type (not floating point) for FREM");
2315     break;
2316   case Shl:
2317   case LShr:
2318   case AShr:
2319     assert(getType() == LHS->getType() &&
2320            "Shift operation should return same type as operands!");
2321     assert(getType()->isIntOrIntVectorTy() &&
2322            "Tried to create a shift operation on a non-integral type!");
2323     break;
2324   case And: case Or:
2325   case Xor:
2326     assert(getType() == LHS->getType() &&
2327            "Logical operation should return same type as operands!");
2328     assert(getType()->isIntOrIntVectorTy() &&
2329            "Tried to create a logical operation on a non-integral type!");
2330     break;
2331   default: llvm_unreachable("Invalid opcode provided");
2332   }
2333 #endif
2334 }
2335 
2336 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2337                                        const Twine &Name,
2338                                        Instruction *InsertBefore) {
2339   assert(S1->getType() == S2->getType() &&
2340          "Cannot create binary operator with two operands of differing type!");
2341   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2342 }
2343 
2344 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2345                                        const Twine &Name,
2346                                        BasicBlock *InsertAtEnd) {
2347   BinaryOperator *Res = Create(Op, S1, S2, Name);
2348   InsertAtEnd->getInstList().push_back(Res);
2349   return Res;
2350 }
2351 
2352 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2353                                           Instruction *InsertBefore) {
2354   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2355   return new BinaryOperator(Instruction::Sub,
2356                             zero, Op,
2357                             Op->getType(), Name, InsertBefore);
2358 }
2359 
2360 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2361                                           BasicBlock *InsertAtEnd) {
2362   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2363   return new BinaryOperator(Instruction::Sub,
2364                             zero, Op,
2365                             Op->getType(), Name, InsertAtEnd);
2366 }
2367 
2368 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2369                                              Instruction *InsertBefore) {
2370   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2371   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2372 }
2373 
2374 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2375                                              BasicBlock *InsertAtEnd) {
2376   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2377   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2378 }
2379 
2380 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2381                                              Instruction *InsertBefore) {
2382   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2383   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2384 }
2385 
2386 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2387                                              BasicBlock *InsertAtEnd) {
2388   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2389   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2390 }
2391 
2392 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2393                                            Instruction *InsertBefore) {
2394   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2395   return new BinaryOperator(Instruction::FSub, zero, Op,
2396                             Op->getType(), Name, InsertBefore);
2397 }
2398 
2399 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2400                                            BasicBlock *InsertAtEnd) {
2401   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2402   return new BinaryOperator(Instruction::FSub, zero, Op,
2403                             Op->getType(), Name, InsertAtEnd);
2404 }
2405 
2406 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2407                                           Instruction *InsertBefore) {
2408   Constant *C = Constant::getAllOnesValue(Op->getType());
2409   return new BinaryOperator(Instruction::Xor, Op, C,
2410                             Op->getType(), Name, InsertBefore);
2411 }
2412 
2413 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2414                                           BasicBlock *InsertAtEnd) {
2415   Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2416   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2417                             Op->getType(), Name, InsertAtEnd);
2418 }
2419 
2420 // Exchange the two operands to this instruction. This instruction is safe to
2421 // use on any binary instruction and does not modify the semantics of the
2422 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2423 // is changed.
2424 bool BinaryOperator::swapOperands() {
2425   if (!isCommutative())
2426     return true; // Can't commute operands
2427   Op<0>().swap(Op<1>());
2428   return false;
2429 }
2430 
2431 //===----------------------------------------------------------------------===//
2432 //                             FPMathOperator Class
2433 //===----------------------------------------------------------------------===//
2434 
2435 float FPMathOperator::getFPAccuracy() const {
2436   const MDNode *MD =
2437       cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2438   if (!MD)
2439     return 0.0;
2440   ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2441   return Accuracy->getValueAPF().convertToFloat();
2442 }
2443 
2444 //===----------------------------------------------------------------------===//
2445 //                                CastInst Class
2446 //===----------------------------------------------------------------------===//
2447 
2448 // Just determine if this cast only deals with integral->integral conversion.
2449 bool CastInst::isIntegerCast() const {
2450   switch (getOpcode()) {
2451     default: return false;
2452     case Instruction::ZExt:
2453     case Instruction::SExt:
2454     case Instruction::Trunc:
2455       return true;
2456     case Instruction::BitCast:
2457       return getOperand(0)->getType()->isIntegerTy() &&
2458         getType()->isIntegerTy();
2459   }
2460 }
2461 
2462 bool CastInst::isLosslessCast() const {
2463   // Only BitCast can be lossless, exit fast if we're not BitCast
2464   if (getOpcode() != Instruction::BitCast)
2465     return false;
2466 
2467   // Identity cast is always lossless
2468   Type *SrcTy = getOperand(0)->getType();
2469   Type *DstTy = getType();
2470   if (SrcTy == DstTy)
2471     return true;
2472 
2473   // Pointer to pointer is always lossless.
2474   if (SrcTy->isPointerTy())
2475     return DstTy->isPointerTy();
2476   return false;  // Other types have no identity values
2477 }
2478 
2479 /// This function determines if the CastInst does not require any bits to be
2480 /// changed in order to effect the cast. Essentially, it identifies cases where
2481 /// no code gen is necessary for the cast, hence the name no-op cast.  For
2482 /// example, the following are all no-op casts:
2483 /// # bitcast i32* %x to i8*
2484 /// # bitcast <2 x i32> %x to <4 x i16>
2485 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
2486 /// Determine if the described cast is a no-op.
2487 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2488                           Type *SrcTy,
2489                           Type *DestTy,
2490                           const DataLayout &DL) {
2491   switch (Opcode) {
2492     default: llvm_unreachable("Invalid CastOp");
2493     case Instruction::Trunc:
2494     case Instruction::ZExt:
2495     case Instruction::SExt:
2496     case Instruction::FPTrunc:
2497     case Instruction::FPExt:
2498     case Instruction::UIToFP:
2499     case Instruction::SIToFP:
2500     case Instruction::FPToUI:
2501     case Instruction::FPToSI:
2502     case Instruction::AddrSpaceCast:
2503       // TODO: Target informations may give a more accurate answer here.
2504       return false;
2505     case Instruction::BitCast:
2506       return true;  // BitCast never modifies bits.
2507     case Instruction::PtrToInt:
2508       return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2509              DestTy->getScalarSizeInBits();
2510     case Instruction::IntToPtr:
2511       return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2512              SrcTy->getScalarSizeInBits();
2513   }
2514 }
2515 
2516 bool CastInst::isNoopCast(const DataLayout &DL) const {
2517   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2518 }
2519 
2520 /// This function determines if a pair of casts can be eliminated and what
2521 /// opcode should be used in the elimination. This assumes that there are two
2522 /// instructions like this:
2523 /// *  %F = firstOpcode SrcTy %x to MidTy
2524 /// *  %S = secondOpcode MidTy %F to DstTy
2525 /// The function returns a resultOpcode so these two casts can be replaced with:
2526 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
2527 /// If no such cast is permitted, the function returns 0.
2528 unsigned CastInst::isEliminableCastPair(
2529   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2530   Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2531   Type *DstIntPtrTy) {
2532   // Define the 144 possibilities for these two cast instructions. The values
2533   // in this matrix determine what to do in a given situation and select the
2534   // case in the switch below.  The rows correspond to firstOp, the columns
2535   // correspond to secondOp.  In looking at the table below, keep in mind
2536   // the following cast properties:
2537   //
2538   //          Size Compare       Source               Destination
2539   // Operator  Src ? Size   Type       Sign         Type       Sign
2540   // -------- ------------ -------------------   ---------------------
2541   // TRUNC         >       Integer      Any        Integral     Any
2542   // ZEXT          <       Integral   Unsigned     Integer      Any
2543   // SEXT          <       Integral    Signed      Integer      Any
2544   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
2545   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed
2546   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a
2547   // SITOFP       n/a      Integral    Signed      FloatPt      n/a
2548   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a
2549   // FPEXT         <       FloatPt      n/a        FloatPt      n/a
2550   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
2551   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
2552   // BITCAST       =       FirstClass   n/a       FirstClass    n/a
2553   // ADDRSPCST    n/a      Pointer      n/a        Pointer      n/a
2554   //
2555   // NOTE: some transforms are safe, but we consider them to be non-profitable.
2556   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2557   // into "fptoui double to i64", but this loses information about the range
2558   // of the produced value (we no longer know the top-part is all zeros).
2559   // Further this conversion is often much more expensive for typical hardware,
2560   // and causes issues when building libgcc.  We disallow fptosi+sext for the
2561   // same reason.
2562   const unsigned numCastOps =
2563     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2564   static const uint8_t CastResults[numCastOps][numCastOps] = {
2565     // T        F  F  U  S  F  F  P  I  B  A  -+
2566     // R  Z  S  P  P  I  I  T  P  2  N  T  S   |
2567     // U  E  E  2  2  2  2  R  E  I  T  C  C   +- secondOp
2568     // N  X  X  U  S  F  F  N  X  N  2  V  V   |
2569     // C  T  T  I  I  P  P  C  T  T  P  T  T  -+
2570     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc         -+
2571     {  8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt           |
2572     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt           |
2573     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI         |
2574     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI         |
2575     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP         +- firstOp
2576     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP         |
2577     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc        |
2578     { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt          |
2579     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt       |
2580     { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr       |
2581     {  5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast        |
2582     {  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2583   };
2584 
2585   // TODO: This logic could be encoded into the table above and handled in the
2586   // switch below.
2587   // If either of the casts are a bitcast from scalar to vector, disallow the
2588   // merging. However, any pair of bitcasts are allowed.
2589   bool IsFirstBitcast  = (firstOp == Instruction::BitCast);
2590   bool IsSecondBitcast = (secondOp == Instruction::BitCast);
2591   bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
2592 
2593   // Check if any of the casts convert scalars <-> vectors.
2594   if ((IsFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2595       (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2596     if (!AreBothBitcasts)
2597       return 0;
2598 
2599   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2600                             [secondOp-Instruction::CastOpsBegin];
2601   switch (ElimCase) {
2602     case 0:
2603       // Categorically disallowed.
2604       return 0;
2605     case 1:
2606       // Allowed, use first cast's opcode.
2607       return firstOp;
2608     case 2:
2609       // Allowed, use second cast's opcode.
2610       return secondOp;
2611     case 3:
2612       // No-op cast in second op implies firstOp as long as the DestTy
2613       // is integer and we are not converting between a vector and a
2614       // non-vector type.
2615       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2616         return firstOp;
2617       return 0;
2618     case 4:
2619       // No-op cast in second op implies firstOp as long as the DestTy
2620       // is floating point.
2621       if (DstTy->isFloatingPointTy())
2622         return firstOp;
2623       return 0;
2624     case 5:
2625       // No-op cast in first op implies secondOp as long as the SrcTy
2626       // is an integer.
2627       if (SrcTy->isIntegerTy())
2628         return secondOp;
2629       return 0;
2630     case 6:
2631       // No-op cast in first op implies secondOp as long as the SrcTy
2632       // is a floating point.
2633       if (SrcTy->isFloatingPointTy())
2634         return secondOp;
2635       return 0;
2636     case 7: {
2637       // Cannot simplify if address spaces are different!
2638       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2639         return 0;
2640 
2641       unsigned MidSize = MidTy->getScalarSizeInBits();
2642       // We can still fold this without knowing the actual sizes as long we
2643       // know that the intermediate pointer is the largest possible
2644       // pointer size.
2645       // FIXME: Is this always true?
2646       if (MidSize == 64)
2647         return Instruction::BitCast;
2648 
2649       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2650       if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2651         return 0;
2652       unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2653       if (MidSize >= PtrSize)
2654         return Instruction::BitCast;
2655       return 0;
2656     }
2657     case 8: {
2658       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
2659       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
2660       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
2661       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2662       unsigned DstSize = DstTy->getScalarSizeInBits();
2663       if (SrcSize == DstSize)
2664         return Instruction::BitCast;
2665       else if (SrcSize < DstSize)
2666         return firstOp;
2667       return secondOp;
2668     }
2669     case 9:
2670       // zext, sext -> zext, because sext can't sign extend after zext
2671       return Instruction::ZExt;
2672     case 11: {
2673       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2674       if (!MidIntPtrTy)
2675         return 0;
2676       unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2677       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2678       unsigned DstSize = DstTy->getScalarSizeInBits();
2679       if (SrcSize <= PtrSize && SrcSize == DstSize)
2680         return Instruction::BitCast;
2681       return 0;
2682     }
2683     case 12:
2684       // addrspacecast, addrspacecast -> bitcast,       if SrcAS == DstAS
2685       // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2686       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2687         return Instruction::AddrSpaceCast;
2688       return Instruction::BitCast;
2689     case 13:
2690       // FIXME: this state can be merged with (1), but the following assert
2691       // is useful to check the correcteness of the sequence due to semantic
2692       // change of bitcast.
2693       assert(
2694         SrcTy->isPtrOrPtrVectorTy() &&
2695         MidTy->isPtrOrPtrVectorTy() &&
2696         DstTy->isPtrOrPtrVectorTy() &&
2697         SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2698         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2699         "Illegal addrspacecast, bitcast sequence!");
2700       // Allowed, use first cast's opcode
2701       return firstOp;
2702     case 14:
2703       // bitcast, addrspacecast -> addrspacecast if the element type of
2704       // bitcast's source is the same as that of addrspacecast's destination.
2705       if (SrcTy->getScalarType()->getPointerElementType() ==
2706           DstTy->getScalarType()->getPointerElementType())
2707         return Instruction::AddrSpaceCast;
2708       return 0;
2709     case 15:
2710       // FIXME: this state can be merged with (1), but the following assert
2711       // is useful to check the correcteness of the sequence due to semantic
2712       // change of bitcast.
2713       assert(
2714         SrcTy->isIntOrIntVectorTy() &&
2715         MidTy->isPtrOrPtrVectorTy() &&
2716         DstTy->isPtrOrPtrVectorTy() &&
2717         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2718         "Illegal inttoptr, bitcast sequence!");
2719       // Allowed, use first cast's opcode
2720       return firstOp;
2721     case 16:
2722       // FIXME: this state can be merged with (2), but the following assert
2723       // is useful to check the correcteness of the sequence due to semantic
2724       // change of bitcast.
2725       assert(
2726         SrcTy->isPtrOrPtrVectorTy() &&
2727         MidTy->isPtrOrPtrVectorTy() &&
2728         DstTy->isIntOrIntVectorTy() &&
2729         SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2730         "Illegal bitcast, ptrtoint sequence!");
2731       // Allowed, use second cast's opcode
2732       return secondOp;
2733     case 17:
2734       // (sitofp (zext x)) -> (uitofp x)
2735       return Instruction::UIToFP;
2736     case 99:
2737       // Cast combination can't happen (error in input). This is for all cases
2738       // where the MidTy is not the same for the two cast instructions.
2739       llvm_unreachable("Invalid Cast Combination");
2740     default:
2741       llvm_unreachable("Error in CastResults table!!!");
2742   }
2743 }
2744 
2745 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2746   const Twine &Name, Instruction *InsertBefore) {
2747   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2748   // Construct and return the appropriate CastInst subclass
2749   switch (op) {
2750   case Trunc:         return new TruncInst         (S, Ty, Name, InsertBefore);
2751   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertBefore);
2752   case SExt:          return new SExtInst          (S, Ty, Name, InsertBefore);
2753   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertBefore);
2754   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertBefore);
2755   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertBefore);
2756   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertBefore);
2757   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertBefore);
2758   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertBefore);
2759   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertBefore);
2760   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertBefore);
2761   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertBefore);
2762   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2763   default: llvm_unreachable("Invalid opcode provided");
2764   }
2765 }
2766 
2767 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2768   const Twine &Name, BasicBlock *InsertAtEnd) {
2769   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2770   // Construct and return the appropriate CastInst subclass
2771   switch (op) {
2772   case Trunc:         return new TruncInst         (S, Ty, Name, InsertAtEnd);
2773   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertAtEnd);
2774   case SExt:          return new SExtInst          (S, Ty, Name, InsertAtEnd);
2775   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertAtEnd);
2776   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertAtEnd);
2777   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertAtEnd);
2778   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertAtEnd);
2779   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertAtEnd);
2780   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertAtEnd);
2781   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertAtEnd);
2782   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertAtEnd);
2783   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertAtEnd);
2784   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2785   default: llvm_unreachable("Invalid opcode provided");
2786   }
2787 }
2788 
2789 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2790                                         const Twine &Name,
2791                                         Instruction *InsertBefore) {
2792   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2793     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2794   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2795 }
2796 
2797 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2798                                         const Twine &Name,
2799                                         BasicBlock *InsertAtEnd) {
2800   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2801     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2802   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2803 }
2804 
2805 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2806                                         const Twine &Name,
2807                                         Instruction *InsertBefore) {
2808   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2809     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2810   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2811 }
2812 
2813 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2814                                         const Twine &Name,
2815                                         BasicBlock *InsertAtEnd) {
2816   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2817     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2818   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2819 }
2820 
2821 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2822                                          const Twine &Name,
2823                                          Instruction *InsertBefore) {
2824   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2825     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2826   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2827 }
2828 
2829 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2830                                          const Twine &Name,
2831                                          BasicBlock *InsertAtEnd) {
2832   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2833     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2834   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2835 }
2836 
2837 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2838                                       const Twine &Name,
2839                                       BasicBlock *InsertAtEnd) {
2840   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2841   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2842          "Invalid cast");
2843   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2844   assert((!Ty->isVectorTy() ||
2845           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2846          "Invalid cast");
2847 
2848   if (Ty->isIntOrIntVectorTy())
2849     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2850 
2851   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2852 }
2853 
2854 /// Create a BitCast or a PtrToInt cast instruction
2855 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2856                                       const Twine &Name,
2857                                       Instruction *InsertBefore) {
2858   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2859   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2860          "Invalid cast");
2861   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2862   assert((!Ty->isVectorTy() ||
2863           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2864          "Invalid cast");
2865 
2866   if (Ty->isIntOrIntVectorTy())
2867     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2868 
2869   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2870 }
2871 
2872 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2873   Value *S, Type *Ty,
2874   const Twine &Name,
2875   BasicBlock *InsertAtEnd) {
2876   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2877   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2878 
2879   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2880     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2881 
2882   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2883 }
2884 
2885 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2886   Value *S, Type *Ty,
2887   const Twine &Name,
2888   Instruction *InsertBefore) {
2889   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2890   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2891 
2892   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2893     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2894 
2895   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2896 }
2897 
2898 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2899                                            const Twine &Name,
2900                                            Instruction *InsertBefore) {
2901   if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2902     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2903   if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2904     return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2905 
2906   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2907 }
2908 
2909 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2910                                       bool isSigned, const Twine &Name,
2911                                       Instruction *InsertBefore) {
2912   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2913          "Invalid integer cast");
2914   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2915   unsigned DstBits = Ty->getScalarSizeInBits();
2916   Instruction::CastOps opcode =
2917     (SrcBits == DstBits ? Instruction::BitCast :
2918      (SrcBits > DstBits ? Instruction::Trunc :
2919       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2920   return Create(opcode, C, Ty, Name, InsertBefore);
2921 }
2922 
2923 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2924                                       bool isSigned, const Twine &Name,
2925                                       BasicBlock *InsertAtEnd) {
2926   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2927          "Invalid cast");
2928   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2929   unsigned DstBits = Ty->getScalarSizeInBits();
2930   Instruction::CastOps opcode =
2931     (SrcBits == DstBits ? Instruction::BitCast :
2932      (SrcBits > DstBits ? Instruction::Trunc :
2933       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2934   return Create(opcode, C, Ty, Name, InsertAtEnd);
2935 }
2936 
2937 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2938                                  const Twine &Name,
2939                                  Instruction *InsertBefore) {
2940   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2941          "Invalid cast");
2942   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2943   unsigned DstBits = Ty->getScalarSizeInBits();
2944   Instruction::CastOps opcode =
2945     (SrcBits == DstBits ? Instruction::BitCast :
2946      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2947   return Create(opcode, C, Ty, Name, InsertBefore);
2948 }
2949 
2950 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2951                                  const Twine &Name,
2952                                  BasicBlock *InsertAtEnd) {
2953   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2954          "Invalid cast");
2955   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2956   unsigned DstBits = Ty->getScalarSizeInBits();
2957   Instruction::CastOps opcode =
2958     (SrcBits == DstBits ? Instruction::BitCast :
2959      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2960   return Create(opcode, C, Ty, Name, InsertAtEnd);
2961 }
2962 
2963 // Check whether it is valid to call getCastOpcode for these types.
2964 // This routine must be kept in sync with getCastOpcode.
2965 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2966   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2967     return false;
2968 
2969   if (SrcTy == DestTy)
2970     return true;
2971 
2972   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2973     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2974       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2975         // An element by element cast.  Valid if casting the elements is valid.
2976         SrcTy = SrcVecTy->getElementType();
2977         DestTy = DestVecTy->getElementType();
2978       }
2979 
2980   // Get the bit sizes, we'll need these
2981   TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2982   TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2983 
2984   // Run through the possibilities ...
2985   if (DestTy->isIntegerTy()) {               // Casting to integral
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 SrcTy->isPointerTy();
2994   }
2995   if (DestTy->isFloatingPointTy()) {  // Casting to floating pt
2996     if (SrcTy->isIntegerTy())                // Casting from integral
2997       return true;
2998     if (SrcTy->isFloatingPointTy())   // Casting from floating pt
2999       return true;
3000     if (SrcTy->isVectorTy())          // Casting from vector
3001       return DestBits == SrcBits;
3002                                     // Casting from something else
3003     return false;
3004   }
3005   if (DestTy->isVectorTy())         // Casting to vector
3006     return DestBits == SrcBits;
3007   if (DestTy->isPointerTy()) {        // Casting to pointer
3008     if (SrcTy->isPointerTy())                // Casting from pointer
3009       return true;
3010     return SrcTy->isIntegerTy();             // Casting from integral
3011   }
3012   if (DestTy->isX86_MMXTy()) {
3013     if (SrcTy->isVectorTy())
3014       return DestBits == SrcBits;       // 64-bit vector to MMX
3015     return false;
3016   }                                    // Casting to something else
3017   return false;
3018 }
3019 
3020 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3021   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3022     return false;
3023 
3024   if (SrcTy == DestTy)
3025     return true;
3026 
3027   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3028     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3029       if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3030         // An element by element cast. Valid if casting the elements is valid.
3031         SrcTy = SrcVecTy->getElementType();
3032         DestTy = DestVecTy->getElementType();
3033       }
3034     }
3035   }
3036 
3037   if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3038     if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3039       return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3040     }
3041   }
3042 
3043   TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
3044   TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3045 
3046   // Could still have vectors of pointers if the number of elements doesn't
3047   // match
3048   if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
3049     return false;
3050 
3051   if (SrcBits != DestBits)
3052     return false;
3053 
3054   if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
3055     return false;
3056 
3057   return true;
3058 }
3059 
3060 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
3061                                           const DataLayout &DL) {
3062   // ptrtoint and inttoptr are not allowed on non-integral pointers
3063   if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3064     if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3065       return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3066               !DL.isNonIntegralPointerType(PtrTy));
3067   if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3068     if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3069       return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3070               !DL.isNonIntegralPointerType(PtrTy));
3071 
3072   return isBitCastable(SrcTy, DestTy);
3073 }
3074 
3075 // Provide a way to get a "cast" where the cast opcode is inferred from the
3076 // types and size of the operand. This, basically, is a parallel of the
3077 // logic in the castIsValid function below.  This axiom should hold:
3078 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3079 // should not assert in castIsValid. In other words, this produces a "correct"
3080 // casting opcode for the arguments passed to it.
3081 // This routine must be kept in sync with isCastable.
3082 Instruction::CastOps
3083 CastInst::getCastOpcode(
3084   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3085   Type *SrcTy = Src->getType();
3086 
3087   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3088          "Only first class types are castable!");
3089 
3090   if (SrcTy == DestTy)
3091     return BitCast;
3092 
3093   // FIXME: Check address space sizes here
3094   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3095     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3096       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
3097         // An element by element cast.  Find the appropriate opcode based on the
3098         // element types.
3099         SrcTy = SrcVecTy->getElementType();
3100         DestTy = DestVecTy->getElementType();
3101       }
3102 
3103   // Get the bit sizes, we'll need these
3104   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
3105   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3106 
3107   // Run through the possibilities ...
3108   if (DestTy->isIntegerTy()) {                      // Casting to integral
3109     if (SrcTy->isIntegerTy()) {                     // Casting from integral
3110       if (DestBits < SrcBits)
3111         return Trunc;                               // int -> smaller int
3112       else if (DestBits > SrcBits) {                // its an extension
3113         if (SrcIsSigned)
3114           return SExt;                              // signed -> SEXT
3115         else
3116           return ZExt;                              // unsigned -> ZEXT
3117       } else {
3118         return BitCast;                             // Same size, No-op cast
3119       }
3120     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
3121       if (DestIsSigned)
3122         return FPToSI;                              // FP -> sint
3123       else
3124         return FPToUI;                              // FP -> uint
3125     } else if (SrcTy->isVectorTy()) {
3126       assert(DestBits == SrcBits &&
3127              "Casting vector to integer of different width");
3128       return BitCast;                             // Same size, no-op cast
3129     } else {
3130       assert(SrcTy->isPointerTy() &&
3131              "Casting from a value that is not first-class type");
3132       return PtrToInt;                              // ptr -> int
3133     }
3134   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
3135     if (SrcTy->isIntegerTy()) {                     // Casting from integral
3136       if (SrcIsSigned)
3137         return SIToFP;                              // sint -> FP
3138       else
3139         return UIToFP;                              // uint -> FP
3140     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
3141       if (DestBits < SrcBits) {
3142         return FPTrunc;                             // FP -> smaller FP
3143       } else if (DestBits > SrcBits) {
3144         return FPExt;                               // FP -> larger FP
3145       } else  {
3146         return BitCast;                             // same size, no-op cast
3147       }
3148     } else if (SrcTy->isVectorTy()) {
3149       assert(DestBits == SrcBits &&
3150              "Casting vector to floating point of different width");
3151       return BitCast;                             // same size, no-op cast
3152     }
3153     llvm_unreachable("Casting pointer or non-first class to float");
3154   } else if (DestTy->isVectorTy()) {
3155     assert(DestBits == SrcBits &&
3156            "Illegal cast to vector (wrong type or size)");
3157     return BitCast;
3158   } else if (DestTy->isPointerTy()) {
3159     if (SrcTy->isPointerTy()) {
3160       if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3161         return AddrSpaceCast;
3162       return BitCast;                               // ptr -> ptr
3163     } else if (SrcTy->isIntegerTy()) {
3164       return IntToPtr;                              // int -> ptr
3165     }
3166     llvm_unreachable("Casting pointer to other than pointer or int");
3167   } else if (DestTy->isX86_MMXTy()) {
3168     if (SrcTy->isVectorTy()) {
3169       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3170       return BitCast;                               // 64-bit vector to MMX
3171     }
3172     llvm_unreachable("Illegal cast to X86_MMX");
3173   }
3174   llvm_unreachable("Casting to type that is not first-class");
3175 }
3176 
3177 //===----------------------------------------------------------------------===//
3178 //                    CastInst SubClass Constructors
3179 //===----------------------------------------------------------------------===//
3180 
3181 /// Check that the construction parameters for a CastInst are correct. This
3182 /// could be broken out into the separate constructors but it is useful to have
3183 /// it in one place and to eliminate the redundant code for getting the sizes
3184 /// of the types involved.
3185 bool
3186 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3187   // Check for type sanity on the arguments
3188   Type *SrcTy = S->getType();
3189 
3190   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3191       SrcTy->isAggregateType() || DstTy->isAggregateType())
3192     return false;
3193 
3194   // Get the size of the types in bits, we'll need this later
3195   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3196   unsigned DstBitSize = DstTy->getScalarSizeInBits();
3197 
3198   // If these are vector types, get the lengths of the vectors (using zero for
3199   // scalar types means that checking that vector lengths match also checks that
3200   // scalars are not being converted to vectors or vectors to scalars).
3201   unsigned SrcLength = SrcTy->isVectorTy() ?
3202     cast<VectorType>(SrcTy)->getNumElements() : 0;
3203   unsigned DstLength = DstTy->isVectorTy() ?
3204     cast<VectorType>(DstTy)->getNumElements() : 0;
3205 
3206   // Switch on the opcode provided
3207   switch (op) {
3208   default: return false; // This is an input error
3209   case Instruction::Trunc:
3210     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3211       SrcLength == DstLength && SrcBitSize > DstBitSize;
3212   case Instruction::ZExt:
3213     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3214       SrcLength == DstLength && SrcBitSize < DstBitSize;
3215   case Instruction::SExt:
3216     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3217       SrcLength == DstLength && SrcBitSize < DstBitSize;
3218   case Instruction::FPTrunc:
3219     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3220       SrcLength == DstLength && SrcBitSize > DstBitSize;
3221   case Instruction::FPExt:
3222     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3223       SrcLength == DstLength && SrcBitSize < DstBitSize;
3224   case Instruction::UIToFP:
3225   case Instruction::SIToFP:
3226     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3227       SrcLength == DstLength;
3228   case Instruction::FPToUI:
3229   case Instruction::FPToSI:
3230     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3231       SrcLength == DstLength;
3232   case Instruction::PtrToInt:
3233     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3234       return false;
3235     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3236       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3237         return false;
3238     return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3239   case Instruction::IntToPtr:
3240     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3241       return false;
3242     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3243       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3244         return false;
3245     return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3246   case Instruction::BitCast: {
3247     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3248     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3249 
3250     // BitCast implies a no-op cast of type only. No bits change.
3251     // However, you can't cast pointers to anything but pointers.
3252     if (!SrcPtrTy != !DstPtrTy)
3253       return false;
3254 
3255     // For non-pointer cases, the cast is okay if the source and destination bit
3256     // widths are identical.
3257     if (!SrcPtrTy)
3258       return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3259 
3260     // If both are pointers then the address spaces must match.
3261     if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3262       return false;
3263 
3264     // A vector of pointers must have the same number of elements.
3265     VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy);
3266     VectorType *DstVecTy = dyn_cast<VectorType>(DstTy);
3267     if (SrcVecTy && DstVecTy)
3268       return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3269     if (SrcVecTy)
3270       return SrcVecTy->getNumElements() == 1;
3271     if (DstVecTy)
3272       return DstVecTy->getNumElements() == 1;
3273 
3274     return true;
3275   }
3276   case Instruction::AddrSpaceCast: {
3277     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3278     if (!SrcPtrTy)
3279       return false;
3280 
3281     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3282     if (!DstPtrTy)
3283       return false;
3284 
3285     if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3286       return false;
3287 
3288     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3289       if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3290         return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3291 
3292       return false;
3293     }
3294 
3295     return true;
3296   }
3297   }
3298 }
3299 
3300 TruncInst::TruncInst(
3301   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3302 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3303   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3304 }
3305 
3306 TruncInst::TruncInst(
3307   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3308 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3309   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3310 }
3311 
3312 ZExtInst::ZExtInst(
3313   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3314 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3315   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3316 }
3317 
3318 ZExtInst::ZExtInst(
3319   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3320 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3321   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3322 }
3323 SExtInst::SExtInst(
3324   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3325 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3326   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3327 }
3328 
3329 SExtInst::SExtInst(
3330   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3331 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3332   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3333 }
3334 
3335 FPTruncInst::FPTruncInst(
3336   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3337 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3338   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3339 }
3340 
3341 FPTruncInst::FPTruncInst(
3342   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3343 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3344   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3345 }
3346 
3347 FPExtInst::FPExtInst(
3348   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3349 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3350   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3351 }
3352 
3353 FPExtInst::FPExtInst(
3354   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3355 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3356   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3357 }
3358 
3359 UIToFPInst::UIToFPInst(
3360   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3361 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3362   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3363 }
3364 
3365 UIToFPInst::UIToFPInst(
3366   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3367 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3368   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3369 }
3370 
3371 SIToFPInst::SIToFPInst(
3372   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3373 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3374   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3375 }
3376 
3377 SIToFPInst::SIToFPInst(
3378   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3379 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3380   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3381 }
3382 
3383 FPToUIInst::FPToUIInst(
3384   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3385 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3386   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3387 }
3388 
3389 FPToUIInst::FPToUIInst(
3390   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3391 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3392   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3393 }
3394 
3395 FPToSIInst::FPToSIInst(
3396   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3397 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3398   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3399 }
3400 
3401 FPToSIInst::FPToSIInst(
3402   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3403 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3404   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3405 }
3406 
3407 PtrToIntInst::PtrToIntInst(
3408   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3409 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3410   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3411 }
3412 
3413 PtrToIntInst::PtrToIntInst(
3414   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3415 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3416   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3417 }
3418 
3419 IntToPtrInst::IntToPtrInst(
3420   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3421 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3422   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3423 }
3424 
3425 IntToPtrInst::IntToPtrInst(
3426   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3427 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3428   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3429 }
3430 
3431 BitCastInst::BitCastInst(
3432   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3433 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3434   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3435 }
3436 
3437 BitCastInst::BitCastInst(
3438   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3439 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3440   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3441 }
3442 
3443 AddrSpaceCastInst::AddrSpaceCastInst(
3444   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3445 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3446   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3447 }
3448 
3449 AddrSpaceCastInst::AddrSpaceCastInst(
3450   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3451 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3452   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3453 }
3454 
3455 //===----------------------------------------------------------------------===//
3456 //                               CmpInst Classes
3457 //===----------------------------------------------------------------------===//
3458 
3459 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3460                  Value *RHS, const Twine &Name, Instruction *InsertBefore,
3461                  Instruction *FlagsSource)
3462   : Instruction(ty, op,
3463                 OperandTraits<CmpInst>::op_begin(this),
3464                 OperandTraits<CmpInst>::operands(this),
3465                 InsertBefore) {
3466   Op<0>() = LHS;
3467   Op<1>() = RHS;
3468   setPredicate((Predicate)predicate);
3469   setName(Name);
3470   if (FlagsSource)
3471     copyIRFlags(FlagsSource);
3472 }
3473 
3474 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3475                  Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
3476   : Instruction(ty, op,
3477                 OperandTraits<CmpInst>::op_begin(this),
3478                 OperandTraits<CmpInst>::operands(this),
3479                 InsertAtEnd) {
3480   Op<0>() = LHS;
3481   Op<1>() = RHS;
3482   setPredicate((Predicate)predicate);
3483   setName(Name);
3484 }
3485 
3486 CmpInst *
3487 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3488                 const Twine &Name, Instruction *InsertBefore) {
3489   if (Op == Instruction::ICmp) {
3490     if (InsertBefore)
3491       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3492                           S1, S2, Name);
3493     else
3494       return new ICmpInst(CmpInst::Predicate(predicate),
3495                           S1, S2, Name);
3496   }
3497 
3498   if (InsertBefore)
3499     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3500                         S1, S2, Name);
3501   else
3502     return new FCmpInst(CmpInst::Predicate(predicate),
3503                         S1, S2, Name);
3504 }
3505 
3506 CmpInst *
3507 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3508                 const Twine &Name, BasicBlock *InsertAtEnd) {
3509   if (Op == Instruction::ICmp) {
3510     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3511                         S1, S2, Name);
3512   }
3513   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3514                       S1, S2, Name);
3515 }
3516 
3517 void CmpInst::swapOperands() {
3518   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3519     IC->swapOperands();
3520   else
3521     cast<FCmpInst>(this)->swapOperands();
3522 }
3523 
3524 bool CmpInst::isCommutative() const {
3525   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3526     return IC->isCommutative();
3527   return cast<FCmpInst>(this)->isCommutative();
3528 }
3529 
3530 bool CmpInst::isEquality() const {
3531   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3532     return IC->isEquality();
3533   return cast<FCmpInst>(this)->isEquality();
3534 }
3535 
3536 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3537   switch (pred) {
3538     default: llvm_unreachable("Unknown cmp predicate!");
3539     case ICMP_EQ: return ICMP_NE;
3540     case ICMP_NE: return ICMP_EQ;
3541     case ICMP_UGT: return ICMP_ULE;
3542     case ICMP_ULT: return ICMP_UGE;
3543     case ICMP_UGE: return ICMP_ULT;
3544     case ICMP_ULE: return ICMP_UGT;
3545     case ICMP_SGT: return ICMP_SLE;
3546     case ICMP_SLT: return ICMP_SGE;
3547     case ICMP_SGE: return ICMP_SLT;
3548     case ICMP_SLE: return ICMP_SGT;
3549 
3550     case FCMP_OEQ: return FCMP_UNE;
3551     case FCMP_ONE: return FCMP_UEQ;
3552     case FCMP_OGT: return FCMP_ULE;
3553     case FCMP_OLT: return FCMP_UGE;
3554     case FCMP_OGE: return FCMP_ULT;
3555     case FCMP_OLE: return FCMP_UGT;
3556     case FCMP_UEQ: return FCMP_ONE;
3557     case FCMP_UNE: return FCMP_OEQ;
3558     case FCMP_UGT: return FCMP_OLE;
3559     case FCMP_ULT: return FCMP_OGE;
3560     case FCMP_UGE: return FCMP_OLT;
3561     case FCMP_ULE: return FCMP_OGT;
3562     case FCMP_ORD: return FCMP_UNO;
3563     case FCMP_UNO: return FCMP_ORD;
3564     case FCMP_TRUE: return FCMP_FALSE;
3565     case FCMP_FALSE: return FCMP_TRUE;
3566   }
3567 }
3568 
3569 StringRef CmpInst::getPredicateName(Predicate Pred) {
3570   switch (Pred) {
3571   default:                   return "unknown";
3572   case FCmpInst::FCMP_FALSE: return "false";
3573   case FCmpInst::FCMP_OEQ:   return "oeq";
3574   case FCmpInst::FCMP_OGT:   return "ogt";
3575   case FCmpInst::FCMP_OGE:   return "oge";
3576   case FCmpInst::FCMP_OLT:   return "olt";
3577   case FCmpInst::FCMP_OLE:   return "ole";
3578   case FCmpInst::FCMP_ONE:   return "one";
3579   case FCmpInst::FCMP_ORD:   return "ord";
3580   case FCmpInst::FCMP_UNO:   return "uno";
3581   case FCmpInst::FCMP_UEQ:   return "ueq";
3582   case FCmpInst::FCMP_UGT:   return "ugt";
3583   case FCmpInst::FCMP_UGE:   return "uge";
3584   case FCmpInst::FCMP_ULT:   return "ult";
3585   case FCmpInst::FCMP_ULE:   return "ule";
3586   case FCmpInst::FCMP_UNE:   return "une";
3587   case FCmpInst::FCMP_TRUE:  return "true";
3588   case ICmpInst::ICMP_EQ:    return "eq";
3589   case ICmpInst::ICMP_NE:    return "ne";
3590   case ICmpInst::ICMP_SGT:   return "sgt";
3591   case ICmpInst::ICMP_SGE:   return "sge";
3592   case ICmpInst::ICMP_SLT:   return "slt";
3593   case ICmpInst::ICMP_SLE:   return "sle";
3594   case ICmpInst::ICMP_UGT:   return "ugt";
3595   case ICmpInst::ICMP_UGE:   return "uge";
3596   case ICmpInst::ICMP_ULT:   return "ult";
3597   case ICmpInst::ICMP_ULE:   return "ule";
3598   }
3599 }
3600 
3601 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3602   switch (pred) {
3603     default: llvm_unreachable("Unknown icmp predicate!");
3604     case ICMP_EQ: case ICMP_NE:
3605     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3606        return pred;
3607     case ICMP_UGT: return ICMP_SGT;
3608     case ICMP_ULT: return ICMP_SLT;
3609     case ICMP_UGE: return ICMP_SGE;
3610     case ICMP_ULE: return ICMP_SLE;
3611   }
3612 }
3613 
3614 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3615   switch (pred) {
3616     default: llvm_unreachable("Unknown icmp predicate!");
3617     case ICMP_EQ: case ICMP_NE:
3618     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3619        return pred;
3620     case ICMP_SGT: return ICMP_UGT;
3621     case ICMP_SLT: return ICMP_ULT;
3622     case ICMP_SGE: return ICMP_UGE;
3623     case ICMP_SLE: return ICMP_ULE;
3624   }
3625 }
3626 
3627 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
3628   switch (pred) {
3629     default: llvm_unreachable("Unknown or unsupported cmp predicate!");
3630     case ICMP_SGT: return ICMP_SGE;
3631     case ICMP_SLT: return ICMP_SLE;
3632     case ICMP_SGE: return ICMP_SGT;
3633     case ICMP_SLE: return ICMP_SLT;
3634     case ICMP_UGT: return ICMP_UGE;
3635     case ICMP_ULT: return ICMP_ULE;
3636     case ICMP_UGE: return ICMP_UGT;
3637     case ICMP_ULE: return ICMP_ULT;
3638 
3639     case FCMP_OGT: return FCMP_OGE;
3640     case FCMP_OLT: return FCMP_OLE;
3641     case FCMP_OGE: return FCMP_OGT;
3642     case FCMP_OLE: return FCMP_OLT;
3643     case FCMP_UGT: return FCMP_UGE;
3644     case FCMP_ULT: return FCMP_ULE;
3645     case FCMP_UGE: return FCMP_UGT;
3646     case FCMP_ULE: return FCMP_ULT;
3647   }
3648 }
3649 
3650 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3651   switch (pred) {
3652     default: llvm_unreachable("Unknown cmp predicate!");
3653     case ICMP_EQ: case ICMP_NE:
3654       return pred;
3655     case ICMP_SGT: return ICMP_SLT;
3656     case ICMP_SLT: return ICMP_SGT;
3657     case ICMP_SGE: return ICMP_SLE;
3658     case ICMP_SLE: return ICMP_SGE;
3659     case ICMP_UGT: return ICMP_ULT;
3660     case ICMP_ULT: return ICMP_UGT;
3661     case ICMP_UGE: return ICMP_ULE;
3662     case ICMP_ULE: return ICMP_UGE;
3663 
3664     case FCMP_FALSE: case FCMP_TRUE:
3665     case FCMP_OEQ: case FCMP_ONE:
3666     case FCMP_UEQ: case FCMP_UNE:
3667     case FCMP_ORD: case FCMP_UNO:
3668       return pred;
3669     case FCMP_OGT: return FCMP_OLT;
3670     case FCMP_OLT: return FCMP_OGT;
3671     case FCMP_OGE: return FCMP_OLE;
3672     case FCMP_OLE: return FCMP_OGE;
3673     case FCMP_UGT: return FCMP_ULT;
3674     case FCMP_ULT: return FCMP_UGT;
3675     case FCMP_UGE: return FCMP_ULE;
3676     case FCMP_ULE: return FCMP_UGE;
3677   }
3678 }
3679 
3680 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
3681   switch (pred) {
3682   case ICMP_SGT: return ICMP_SGE;
3683   case ICMP_SLT: return ICMP_SLE;
3684   case ICMP_UGT: return ICMP_UGE;
3685   case ICMP_ULT: return ICMP_ULE;
3686   case FCMP_OGT: return FCMP_OGE;
3687   case FCMP_OLT: return FCMP_OLE;
3688   case FCMP_UGT: return FCMP_UGE;
3689   case FCMP_ULT: return FCMP_ULE;
3690   default: return pred;
3691   }
3692 }
3693 
3694 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3695   assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!");
3696 
3697   switch (pred) {
3698   default:
3699     llvm_unreachable("Unknown predicate!");
3700   case CmpInst::ICMP_ULT:
3701     return CmpInst::ICMP_SLT;
3702   case CmpInst::ICMP_ULE:
3703     return CmpInst::ICMP_SLE;
3704   case CmpInst::ICMP_UGT:
3705     return CmpInst::ICMP_SGT;
3706   case CmpInst::ICMP_UGE:
3707     return CmpInst::ICMP_SGE;
3708   }
3709 }
3710 
3711 bool CmpInst::isUnsigned(Predicate predicate) {
3712   switch (predicate) {
3713     default: return false;
3714     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3715     case ICmpInst::ICMP_UGE: return true;
3716   }
3717 }
3718 
3719 bool CmpInst::isSigned(Predicate predicate) {
3720   switch (predicate) {
3721     default: return false;
3722     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3723     case ICmpInst::ICMP_SGE: return true;
3724   }
3725 }
3726 
3727 bool CmpInst::isOrdered(Predicate predicate) {
3728   switch (predicate) {
3729     default: return false;
3730     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3731     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3732     case FCmpInst::FCMP_ORD: return true;
3733   }
3734 }
3735 
3736 bool CmpInst::isUnordered(Predicate predicate) {
3737   switch (predicate) {
3738     default: return false;
3739     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3740     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3741     case FCmpInst::FCMP_UNO: return true;
3742   }
3743 }
3744 
3745 bool CmpInst::isTrueWhenEqual(Predicate predicate) {
3746   switch(predicate) {
3747     default: return false;
3748     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3749     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3750   }
3751 }
3752 
3753 bool CmpInst::isFalseWhenEqual(Predicate predicate) {
3754   switch(predicate) {
3755   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3756   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3757   default: return false;
3758   }
3759 }
3760 
3761 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3762   // If the predicates match, then we know the first condition implies the
3763   // second is true.
3764   if (Pred1 == Pred2)
3765     return true;
3766 
3767   switch (Pred1) {
3768   default:
3769     break;
3770   case ICMP_EQ:
3771     // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3772     return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
3773            Pred2 == ICMP_SLE;
3774   case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
3775     return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
3776   case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
3777     return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
3778   case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
3779     return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
3780   case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
3781     return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
3782   }
3783   return false;
3784 }
3785 
3786 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3787   return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
3788 }
3789 
3790 //===----------------------------------------------------------------------===//
3791 //                        SwitchInst Implementation
3792 //===----------------------------------------------------------------------===//
3793 
3794 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3795   assert(Value && Default && NumReserved);
3796   ReservedSpace = NumReserved;
3797   setNumHungOffUseOperands(2);
3798   allocHungoffUses(ReservedSpace);
3799 
3800   Op<0>() = Value;
3801   Op<1>() = Default;
3802 }
3803 
3804 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3805 /// switch on and a default destination.  The number of additional cases can
3806 /// be specified here to make memory allocation more efficient.  This
3807 /// constructor can also autoinsert before another instruction.
3808 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3809                        Instruction *InsertBefore)
3810     : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3811                   nullptr, 0, InsertBefore) {
3812   init(Value, Default, 2+NumCases*2);
3813 }
3814 
3815 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3816 /// switch on and a default destination.  The number of additional cases can
3817 /// be specified here to make memory allocation more efficient.  This
3818 /// constructor also autoinserts at the end of the specified BasicBlock.
3819 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3820                        BasicBlock *InsertAtEnd)
3821     : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3822                   nullptr, 0, InsertAtEnd) {
3823   init(Value, Default, 2+NumCases*2);
3824 }
3825 
3826 SwitchInst::SwitchInst(const SwitchInst &SI)
3827     : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
3828   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3829   setNumHungOffUseOperands(SI.getNumOperands());
3830   Use *OL = getOperandList();
3831   const Use *InOL = SI.getOperandList();
3832   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3833     OL[i] = InOL[i];
3834     OL[i+1] = InOL[i+1];
3835   }
3836   SubclassOptionalData = SI.SubclassOptionalData;
3837 }
3838 
3839 /// addCase - Add an entry to the switch instruction...
3840 ///
3841 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3842   unsigned NewCaseIdx = getNumCases();
3843   unsigned OpNo = getNumOperands();
3844   if (OpNo+2 > ReservedSpace)
3845     growOperands();  // Get more space!
3846   // Initialize some new operands.
3847   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3848   setNumHungOffUseOperands(OpNo+2);
3849   CaseHandle Case(this, NewCaseIdx);
3850   Case.setValue(OnVal);
3851   Case.setSuccessor(Dest);
3852 }
3853 
3854 /// removeCase - This method removes the specified case and its successor
3855 /// from the switch instruction.
3856 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
3857   unsigned idx = I->getCaseIndex();
3858 
3859   assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3860 
3861   unsigned NumOps = getNumOperands();
3862   Use *OL = getOperandList();
3863 
3864   // Overwrite this case with the end of the list.
3865   if (2 + (idx + 1) * 2 != NumOps) {
3866     OL[2 + idx * 2] = OL[NumOps - 2];
3867     OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3868   }
3869 
3870   // Nuke the last value.
3871   OL[NumOps-2].set(nullptr);
3872   OL[NumOps-2+1].set(nullptr);
3873   setNumHungOffUseOperands(NumOps-2);
3874 
3875   return CaseIt(this, idx);
3876 }
3877 
3878 /// growOperands - grow operands - This grows the operand list in response
3879 /// to a push_back style of operation.  This grows the number of ops by 3 times.
3880 ///
3881 void SwitchInst::growOperands() {
3882   unsigned e = getNumOperands();
3883   unsigned NumOps = e*3;
3884 
3885   ReservedSpace = NumOps;
3886   growHungoffUses(ReservedSpace);
3887 }
3888 
3889 MDNode *
3890 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
3891   if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
3892     if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
3893       if (MDName->getString() == "branch_weights")
3894         return ProfileData;
3895   return nullptr;
3896 }
3897 
3898 MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
3899   assert(Changed && "called only if metadata has changed");
3900 
3901   if (!Weights)
3902     return nullptr;
3903 
3904   assert(SI.getNumSuccessors() == Weights->size() &&
3905          "num of prof branch_weights must accord with num of successors");
3906 
3907   bool AllZeroes =
3908       all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
3909 
3910   if (AllZeroes || Weights.getValue().size() < 2)
3911     return nullptr;
3912 
3913   return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
3914 }
3915 
3916 void SwitchInstProfUpdateWrapper::init() {
3917   MDNode *ProfileData = getProfBranchWeightsMD(SI);
3918   if (!ProfileData)
3919     return;
3920 
3921   if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
3922     llvm_unreachable("number of prof branch_weights metadata operands does "
3923                      "not correspond to number of succesors");
3924   }
3925 
3926   SmallVector<uint32_t, 8> Weights;
3927   for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
3928     ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
3929     uint32_t CW = C->getValue().getZExtValue();
3930     Weights.push_back(CW);
3931   }
3932   this->Weights = std::move(Weights);
3933 }
3934 
3935 SwitchInst::CaseIt
3936 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
3937   if (Weights) {
3938     assert(SI.getNumSuccessors() == Weights->size() &&
3939            "num of prof branch_weights must accord with num of successors");
3940     Changed = true;
3941     // Copy the last case to the place of the removed one and shrink.
3942     // This is tightly coupled with the way SwitchInst::removeCase() removes
3943     // the cases in SwitchInst::removeCase(CaseIt).
3944     Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
3945     Weights.getValue().pop_back();
3946   }
3947   return SI.removeCase(I);
3948 }
3949 
3950 void SwitchInstProfUpdateWrapper::addCase(
3951     ConstantInt *OnVal, BasicBlock *Dest,
3952     SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
3953   SI.addCase(OnVal, Dest);
3954 
3955   if (!Weights && W && *W) {
3956     Changed = true;
3957     Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
3958     Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
3959   } else if (Weights) {
3960     Changed = true;
3961     Weights.getValue().push_back(W ? *W : 0);
3962   }
3963   if (Weights)
3964     assert(SI.getNumSuccessors() == Weights->size() &&
3965            "num of prof branch_weights must accord with num of successors");
3966 }
3967 
3968 SymbolTableList<Instruction>::iterator
3969 SwitchInstProfUpdateWrapper::eraseFromParent() {
3970   // Instruction is erased. Mark as unchanged to not touch it in the destructor.
3971   Changed = false;
3972   if (Weights)
3973     Weights->resize(0);
3974   return SI.eraseFromParent();
3975 }
3976 
3977 SwitchInstProfUpdateWrapper::CaseWeightOpt
3978 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
3979   if (!Weights)
3980     return None;
3981   return Weights.getValue()[idx];
3982 }
3983 
3984 void SwitchInstProfUpdateWrapper::setSuccessorWeight(
3985     unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
3986   if (!W)
3987     return;
3988 
3989   if (!Weights && *W)
3990     Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
3991 
3992   if (Weights) {
3993     auto &OldW = Weights.getValue()[idx];
3994     if (*W != OldW) {
3995       Changed = true;
3996       OldW = *W;
3997     }
3998   }
3999 }
4000 
4001 SwitchInstProfUpdateWrapper::CaseWeightOpt
4002 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
4003                                                 unsigned idx) {
4004   if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
4005     if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
4006       return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
4007           ->getValue()
4008           .getZExtValue();
4009 
4010   return None;
4011 }
4012 
4013 //===----------------------------------------------------------------------===//
4014 //                        IndirectBrInst Implementation
4015 //===----------------------------------------------------------------------===//
4016 
4017 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4018   assert(Address && Address->getType()->isPointerTy() &&
4019          "Address of indirectbr must be a pointer");
4020   ReservedSpace = 1+NumDests;
4021   setNumHungOffUseOperands(1);
4022   allocHungoffUses(ReservedSpace);
4023 
4024   Op<0>() = Address;
4025 }
4026 
4027 
4028 /// growOperands - grow operands - This grows the operand list in response
4029 /// to a push_back style of operation.  This grows the number of ops by 2 times.
4030 ///
4031 void IndirectBrInst::growOperands() {
4032   unsigned e = getNumOperands();
4033   unsigned NumOps = e*2;
4034 
4035   ReservedSpace = NumOps;
4036   growHungoffUses(ReservedSpace);
4037 }
4038 
4039 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4040                                Instruction *InsertBefore)
4041     : Instruction(Type::getVoidTy(Address->getContext()),
4042                   Instruction::IndirectBr, nullptr, 0, InsertBefore) {
4043   init(Address, NumCases);
4044 }
4045 
4046 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4047                                BasicBlock *InsertAtEnd)
4048     : Instruction(Type::getVoidTy(Address->getContext()),
4049                   Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
4050   init(Address, NumCases);
4051 }
4052 
4053 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4054     : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
4055                   nullptr, IBI.getNumOperands()) {
4056   allocHungoffUses(IBI.getNumOperands());
4057   Use *OL = getOperandList();
4058   const Use *InOL = IBI.getOperandList();
4059   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4060     OL[i] = InOL[i];
4061   SubclassOptionalData = IBI.SubclassOptionalData;
4062 }
4063 
4064 /// addDestination - Add a destination.
4065 ///
4066 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
4067   unsigned OpNo = getNumOperands();
4068   if (OpNo+1 > ReservedSpace)
4069     growOperands();  // Get more space!
4070   // Initialize some new operands.
4071   assert(OpNo < ReservedSpace && "Growing didn't work!");
4072   setNumHungOffUseOperands(OpNo+1);
4073   getOperandList()[OpNo] = DestBB;
4074 }
4075 
4076 /// removeDestination - This method removes the specified successor from the
4077 /// indirectbr instruction.
4078 void IndirectBrInst::removeDestination(unsigned idx) {
4079   assert(idx < getNumOperands()-1 && "Successor index out of range!");
4080 
4081   unsigned NumOps = getNumOperands();
4082   Use *OL = getOperandList();
4083 
4084   // Replace this value with the last one.
4085   OL[idx+1] = OL[NumOps-1];
4086 
4087   // Nuke the last value.
4088   OL[NumOps-1].set(nullptr);
4089   setNumHungOffUseOperands(NumOps-1);
4090 }
4091 
4092 //===----------------------------------------------------------------------===//
4093 //                            FreezeInst Implementation
4094 //===----------------------------------------------------------------------===//
4095 
4096 FreezeInst::FreezeInst(Value *S,
4097                        const Twine &Name, Instruction *InsertBefore)
4098     : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
4099   setName(Name);
4100 }
4101 
4102 FreezeInst::FreezeInst(Value *S,
4103                        const Twine &Name, BasicBlock *InsertAtEnd)
4104     : UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) {
4105   setName(Name);
4106 }
4107 
4108 //===----------------------------------------------------------------------===//
4109 //                           cloneImpl() implementations
4110 //===----------------------------------------------------------------------===//
4111 
4112 // Define these methods here so vtables don't get emitted into every translation
4113 // unit that uses these classes.
4114 
4115 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4116   return new (getNumOperands()) GetElementPtrInst(*this);
4117 }
4118 
4119 UnaryOperator *UnaryOperator::cloneImpl() const {
4120   return Create(getOpcode(), Op<0>());
4121 }
4122 
4123 BinaryOperator *BinaryOperator::cloneImpl() const {
4124   return Create(getOpcode(), Op<0>(), Op<1>());
4125 }
4126 
4127 FCmpInst *FCmpInst::cloneImpl() const {
4128   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4129 }
4130 
4131 ICmpInst *ICmpInst::cloneImpl() const {
4132   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4133 }
4134 
4135 ExtractValueInst *ExtractValueInst::cloneImpl() const {
4136   return new ExtractValueInst(*this);
4137 }
4138 
4139 InsertValueInst *InsertValueInst::cloneImpl() const {
4140   return new InsertValueInst(*this);
4141 }
4142 
4143 AllocaInst *AllocaInst::cloneImpl() const {
4144   AllocaInst *Result =
4145       new AllocaInst(getAllocatedType(), getType()->getAddressSpace(),
4146                      (Value *)getOperand(0), MaybeAlign(getAlignment()));
4147   Result->setUsedWithInAlloca(isUsedWithInAlloca());
4148   Result->setSwiftError(isSwiftError());
4149   return Result;
4150 }
4151 
4152 LoadInst *LoadInst::cloneImpl() const {
4153   return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4154                       MaybeAlign(getAlignment()), getOrdering(),
4155                       getSyncScopeID());
4156 }
4157 
4158 StoreInst *StoreInst::cloneImpl() const {
4159   return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
4160                        MaybeAlign(getAlignment()), getOrdering(),
4161                        getSyncScopeID());
4162 }
4163 
4164 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
4165   AtomicCmpXchgInst *Result =
4166     new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
4167                           getSuccessOrdering(), getFailureOrdering(),
4168                           getSyncScopeID());
4169   Result->setVolatile(isVolatile());
4170   Result->setWeak(isWeak());
4171   return Result;
4172 }
4173 
4174 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
4175   AtomicRMWInst *Result =
4176     new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4177                       getOrdering(), getSyncScopeID());
4178   Result->setVolatile(isVolatile());
4179   return Result;
4180 }
4181 
4182 FenceInst *FenceInst::cloneImpl() const {
4183   return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4184 }
4185 
4186 TruncInst *TruncInst::cloneImpl() const {
4187   return new TruncInst(getOperand(0), getType());
4188 }
4189 
4190 ZExtInst *ZExtInst::cloneImpl() const {
4191   return new ZExtInst(getOperand(0), getType());
4192 }
4193 
4194 SExtInst *SExtInst::cloneImpl() const {
4195   return new SExtInst(getOperand(0), getType());
4196 }
4197 
4198 FPTruncInst *FPTruncInst::cloneImpl() const {
4199   return new FPTruncInst(getOperand(0), getType());
4200 }
4201 
4202 FPExtInst *FPExtInst::cloneImpl() const {
4203   return new FPExtInst(getOperand(0), getType());
4204 }
4205 
4206 UIToFPInst *UIToFPInst::cloneImpl() const {
4207   return new UIToFPInst(getOperand(0), getType());
4208 }
4209 
4210 SIToFPInst *SIToFPInst::cloneImpl() const {
4211   return new SIToFPInst(getOperand(0), getType());
4212 }
4213 
4214 FPToUIInst *FPToUIInst::cloneImpl() const {
4215   return new FPToUIInst(getOperand(0), getType());
4216 }
4217 
4218 FPToSIInst *FPToSIInst::cloneImpl() const {
4219   return new FPToSIInst(getOperand(0), getType());
4220 }
4221 
4222 PtrToIntInst *PtrToIntInst::cloneImpl() const {
4223   return new PtrToIntInst(getOperand(0), getType());
4224 }
4225 
4226 IntToPtrInst *IntToPtrInst::cloneImpl() const {
4227   return new IntToPtrInst(getOperand(0), getType());
4228 }
4229 
4230 BitCastInst *BitCastInst::cloneImpl() const {
4231   return new BitCastInst(getOperand(0), getType());
4232 }
4233 
4234 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
4235   return new AddrSpaceCastInst(getOperand(0), getType());
4236 }
4237 
4238 CallInst *CallInst::cloneImpl() const {
4239   if (hasOperandBundles()) {
4240     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4241     return new(getNumOperands(), DescriptorBytes) CallInst(*this);
4242   }
4243   return  new(getNumOperands()) CallInst(*this);
4244 }
4245 
4246 SelectInst *SelectInst::cloneImpl() const {
4247   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4248 }
4249 
4250 VAArgInst *VAArgInst::cloneImpl() const {
4251   return new VAArgInst(getOperand(0), getType());
4252 }
4253 
4254 ExtractElementInst *ExtractElementInst::cloneImpl() const {
4255   return ExtractElementInst::Create(getOperand(0), getOperand(1));
4256 }
4257 
4258 InsertElementInst *InsertElementInst::cloneImpl() const {
4259   return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4260 }
4261 
4262 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
4263   return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4264 }
4265 
4266 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
4267 
4268 LandingPadInst *LandingPadInst::cloneImpl() const {
4269   return new LandingPadInst(*this);
4270 }
4271 
4272 ReturnInst *ReturnInst::cloneImpl() const {
4273   return new(getNumOperands()) ReturnInst(*this);
4274 }
4275 
4276 BranchInst *BranchInst::cloneImpl() const {
4277   return new(getNumOperands()) BranchInst(*this);
4278 }
4279 
4280 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4281 
4282 IndirectBrInst *IndirectBrInst::cloneImpl() const {
4283   return new IndirectBrInst(*this);
4284 }
4285 
4286 InvokeInst *InvokeInst::cloneImpl() const {
4287   if (hasOperandBundles()) {
4288     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4289     return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
4290   }
4291   return new(getNumOperands()) InvokeInst(*this);
4292 }
4293 
4294 CallBrInst *CallBrInst::cloneImpl() const {
4295   if (hasOperandBundles()) {
4296     unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4297     return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
4298   }
4299   return new (getNumOperands()) CallBrInst(*this);
4300 }
4301 
4302 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4303 
4304 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4305   return new (getNumOperands()) CleanupReturnInst(*this);
4306 }
4307 
4308 CatchReturnInst *CatchReturnInst::cloneImpl() const {
4309   return new (getNumOperands()) CatchReturnInst(*this);
4310 }
4311 
4312 CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4313   return new CatchSwitchInst(*this);
4314 }
4315 
4316 FuncletPadInst *FuncletPadInst::cloneImpl() const {
4317   return new (getNumOperands()) FuncletPadInst(*this);
4318 }
4319 
4320 UnreachableInst *UnreachableInst::cloneImpl() const {
4321   LLVMContext &Context = getContext();
4322   return new UnreachableInst(Context);
4323 }
4324 
4325 FreezeInst *FreezeInst::cloneImpl() const {
4326   return new FreezeInst(getOperand(0));
4327 }
4328