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