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