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