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