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