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