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