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