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