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