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