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