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