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