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