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