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