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