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