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