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