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