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