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