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