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