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