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