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