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