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