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