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