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