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