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