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