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