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