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