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