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