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