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