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