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