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