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