Enhance BinaryOperator::isNot to support vector not.
[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 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1047 /// constant integers.  If so, the result pointer and the first operand have
1048 /// a constant offset between them.
1049 bool GetElementPtrInst::hasAllConstantIndices() const {
1050   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1051     if (!isa<ConstantInt>(getOperand(i)))
1052       return false;
1053   }
1054   return true;
1055 }
1056
1057
1058 //===----------------------------------------------------------------------===//
1059 //                           ExtractElementInst Implementation
1060 //===----------------------------------------------------------------------===//
1061
1062 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1063                                        const std::string &Name,
1064                                        Instruction *InsertBef)
1065   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1066                 ExtractElement, Ops, 2, InsertBef) {
1067   assert(isValidOperands(Val, Index) &&
1068          "Invalid extractelement instruction operands!");
1069   Ops[0].init(Val, this);
1070   Ops[1].init(Index, this);
1071   setName(Name);
1072 }
1073
1074 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1075                                        const std::string &Name,
1076                                        Instruction *InsertBef)
1077   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1078                 ExtractElement, Ops, 2, InsertBef) {
1079   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1080   assert(isValidOperands(Val, Index) &&
1081          "Invalid extractelement instruction operands!");
1082   Ops[0].init(Val, this);
1083   Ops[1].init(Index, this);
1084   setName(Name);
1085 }
1086
1087
1088 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1089                                        const std::string &Name,
1090                                        BasicBlock *InsertAE)
1091   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1092                 ExtractElement, Ops, 2, InsertAE) {
1093   assert(isValidOperands(Val, Index) &&
1094          "Invalid extractelement instruction operands!");
1095
1096   Ops[0].init(Val, this);
1097   Ops[1].init(Index, this);
1098   setName(Name);
1099 }
1100
1101 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1102                                        const std::string &Name,
1103                                        BasicBlock *InsertAE)
1104   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1105                 ExtractElement, Ops, 2, InsertAE) {
1106   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1107   assert(isValidOperands(Val, Index) &&
1108          "Invalid extractelement instruction operands!");
1109   
1110   Ops[0].init(Val, this);
1111   Ops[1].init(Index, this);
1112   setName(Name);
1113 }
1114
1115
1116 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1117   if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1118     return false;
1119   return true;
1120 }
1121
1122
1123 //===----------------------------------------------------------------------===//
1124 //                           InsertElementInst Implementation
1125 //===----------------------------------------------------------------------===//
1126
1127 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1128     : Instruction(IE.getType(), InsertElement, Ops, 3) {
1129   Ops[0].init(IE.Ops[0], this);
1130   Ops[1].init(IE.Ops[1], this);
1131   Ops[2].init(IE.Ops[2], this);
1132 }
1133 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1134                                      const std::string &Name,
1135                                      Instruction *InsertBef)
1136   : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1137   assert(isValidOperands(Vec, Elt, Index) &&
1138          "Invalid insertelement instruction operands!");
1139   Ops[0].init(Vec, this);
1140   Ops[1].init(Elt, this);
1141   Ops[2].init(Index, this);
1142   setName(Name);
1143 }
1144
1145 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1146                                      const std::string &Name,
1147                                      Instruction *InsertBef)
1148   : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1149   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1150   assert(isValidOperands(Vec, Elt, Index) &&
1151          "Invalid insertelement instruction operands!");
1152   Ops[0].init(Vec, this);
1153   Ops[1].init(Elt, this);
1154   Ops[2].init(Index, this);
1155   setName(Name);
1156 }
1157
1158
1159 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1160                                      const std::string &Name,
1161                                      BasicBlock *InsertAE)
1162   : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1163   assert(isValidOperands(Vec, Elt, Index) &&
1164          "Invalid insertelement instruction operands!");
1165
1166   Ops[0].init(Vec, this);
1167   Ops[1].init(Elt, this);
1168   Ops[2].init(Index, this);
1169   setName(Name);
1170 }
1171
1172 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1173                                      const std::string &Name,
1174                                      BasicBlock *InsertAE)
1175 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1176   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1177   assert(isValidOperands(Vec, Elt, Index) &&
1178          "Invalid insertelement instruction operands!");
1179   
1180   Ops[0].init(Vec, this);
1181   Ops[1].init(Elt, this);
1182   Ops[2].init(Index, this);
1183   setName(Name);
1184 }
1185
1186 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
1187                                         const Value *Index) {
1188   if (!isa<VectorType>(Vec->getType()))
1189     return false;   // First operand of insertelement must be vector type.
1190   
1191   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1192     return false;// Second operand of insertelement must be vector element type.
1193     
1194   if (Index->getType() != Type::Int32Ty)
1195     return false;  // Third operand of insertelement must be uint.
1196   return true;
1197 }
1198
1199
1200 //===----------------------------------------------------------------------===//
1201 //                      ShuffleVectorInst Implementation
1202 //===----------------------------------------------------------------------===//
1203
1204 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV) 
1205     : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1206   Ops[0].init(SV.Ops[0], this);
1207   Ops[1].init(SV.Ops[1], this);
1208   Ops[2].init(SV.Ops[2], this);
1209 }
1210
1211 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1212                                      const std::string &Name,
1213                                      Instruction *InsertBefore)
1214   : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1215   assert(isValidOperands(V1, V2, Mask) &&
1216          "Invalid shuffle vector instruction operands!");
1217   Ops[0].init(V1, this);
1218   Ops[1].init(V2, this);
1219   Ops[2].init(Mask, this);
1220   setName(Name);
1221 }
1222
1223 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1224                                      const std::string &Name, 
1225                                      BasicBlock *InsertAtEnd)
1226   : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1227   assert(isValidOperands(V1, V2, Mask) &&
1228          "Invalid shuffle vector instruction operands!");
1229
1230   Ops[0].init(V1, this);
1231   Ops[1].init(V2, this);
1232   Ops[2].init(Mask, this);
1233   setName(Name);
1234 }
1235
1236 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 
1237                                         const Value *Mask) {
1238   if (!isa<VectorType>(V1->getType())) return false;
1239   if (V1->getType() != V2->getType()) return false;
1240   if (!isa<VectorType>(Mask->getType()) ||
1241          cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1242          cast<VectorType>(Mask->getType())->getNumElements() !=
1243          cast<VectorType>(V1->getType())->getNumElements())
1244     return false;
1245   return true;
1246 }
1247
1248
1249 //===----------------------------------------------------------------------===//
1250 //                             BinaryOperator Class
1251 //===----------------------------------------------------------------------===//
1252
1253 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1254                                const Type *Ty, const std::string &Name,
1255                                Instruction *InsertBefore)
1256   : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1257   Ops[0].init(S1, this);
1258   Ops[1].init(S2, this);
1259   init(iType);
1260   setName(Name);
1261 }
1262
1263 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
1264                                const Type *Ty, const std::string &Name,
1265                                BasicBlock *InsertAtEnd)
1266   : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1267   Ops[0].init(S1, this);
1268   Ops[1].init(S2, this);
1269   init(iType);
1270   setName(Name);
1271 }
1272
1273
1274 void BinaryOperator::init(BinaryOps iType) {
1275   Value *LHS = getOperand(0), *RHS = getOperand(1);
1276   LHS = LHS; RHS = RHS; // Silence warnings.
1277   assert(LHS->getType() == RHS->getType() &&
1278          "Binary operator operand types must match!");
1279 #ifndef NDEBUG
1280   switch (iType) {
1281   case Add: case Sub:
1282   case Mul: 
1283     assert(getType() == LHS->getType() &&
1284            "Arithmetic operation should return same type as operands!");
1285     assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1286             isa<VectorType>(getType())) &&
1287           "Tried to create an arithmetic operation on a non-arithmetic type!");
1288     break;
1289   case UDiv: 
1290   case SDiv: 
1291     assert(getType() == LHS->getType() &&
1292            "Arithmetic operation should return same type as operands!");
1293     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
1294             cast<VectorType>(getType())->getElementType()->isInteger())) &&
1295            "Incorrect operand type (not integer) for S/UDIV");
1296     break;
1297   case FDiv:
1298     assert(getType() == LHS->getType() &&
1299            "Arithmetic operation should return same type as operands!");
1300     assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1301             cast<VectorType>(getType())->getElementType()->isFloatingPoint())) 
1302             && "Incorrect operand type (not floating point) for FDIV");
1303     break;
1304   case URem: 
1305   case SRem: 
1306     assert(getType() == LHS->getType() &&
1307            "Arithmetic operation should return same type as operands!");
1308     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
1309             cast<VectorType>(getType())->getElementType()->isInteger())) &&
1310            "Incorrect operand type (not integer) for S/UREM");
1311     break;
1312   case FRem:
1313     assert(getType() == LHS->getType() &&
1314            "Arithmetic operation should return same type as operands!");
1315     assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1316             cast<VectorType>(getType())->getElementType()->isFloatingPoint())) 
1317             && "Incorrect operand type (not floating point) for FREM");
1318     break;
1319   case Shl:
1320   case LShr:
1321   case AShr:
1322     assert(getType() == LHS->getType() &&
1323            "Shift operation should return same type as operands!");
1324     assert(getType()->isInteger() && 
1325            "Shift operation requires integer operands");
1326     break;
1327   case And: case Or:
1328   case Xor:
1329     assert(getType() == LHS->getType() &&
1330            "Logical operation should return same type as operands!");
1331     assert((getType()->isInteger() ||
1332             (isa<VectorType>(getType()) && 
1333              cast<VectorType>(getType())->getElementType()->isInteger())) &&
1334            "Tried to create a logical operation on a non-integral type!");
1335     break;
1336   default:
1337     break;
1338   }
1339 #endif
1340 }
1341
1342 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1343                                        const std::string &Name,
1344                                        Instruction *InsertBefore) {
1345   assert(S1->getType() == S2->getType() &&
1346          "Cannot create binary operator with two operands of differing type!");
1347   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1348 }
1349
1350 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1351                                        const std::string &Name,
1352                                        BasicBlock *InsertAtEnd) {
1353   BinaryOperator *Res = create(Op, S1, S2, Name);
1354   InsertAtEnd->getInstList().push_back(Res);
1355   return Res;
1356 }
1357
1358 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1359                                           Instruction *InsertBefore) {
1360   Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1361   return new BinaryOperator(Instruction::Sub,
1362                             zero, Op,
1363                             Op->getType(), Name, InsertBefore);
1364 }
1365
1366 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1367                                           BasicBlock *InsertAtEnd) {
1368   Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1369   return new BinaryOperator(Instruction::Sub,
1370                             zero, Op,
1371                             Op->getType(), Name, InsertAtEnd);
1372 }
1373
1374 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1375                                           Instruction *InsertBefore) {
1376   Constant *C;
1377   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1378     C = ConstantInt::getAllOnesValue(PTy->getElementType());
1379     C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1380   } else {
1381     C = ConstantInt::getAllOnesValue(Op->getType());
1382   }
1383   
1384   return new BinaryOperator(Instruction::Xor, Op, C,
1385                             Op->getType(), Name, InsertBefore);
1386 }
1387
1388 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1389                                           BasicBlock *InsertAtEnd) {
1390   Constant *AllOnes;
1391   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1392     // Create a vector of all ones values.
1393     Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1394     AllOnes = 
1395       ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1396   } else {
1397     AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1398   }
1399   
1400   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1401                             Op->getType(), Name, InsertAtEnd);
1402 }
1403
1404
1405 // isConstantAllOnes - Helper function for several functions below
1406 static inline bool isConstantAllOnes(const Value *V) {
1407   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1408     return CI->isAllOnesValue();
1409   if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1410     return CV->isAllOnesValue();
1411   return false;
1412 }
1413
1414 bool BinaryOperator::isNeg(const Value *V) {
1415   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1416     if (Bop->getOpcode() == Instruction::Sub)
1417       return Bop->getOperand(0) ==
1418              ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1419   return false;
1420 }
1421
1422 bool BinaryOperator::isNot(const Value *V) {
1423   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1424     return (Bop->getOpcode() == Instruction::Xor &&
1425             (isConstantAllOnes(Bop->getOperand(1)) ||
1426              isConstantAllOnes(Bop->getOperand(0))));
1427   return false;
1428 }
1429
1430 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1431   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1432   return cast<BinaryOperator>(BinOp)->getOperand(1);
1433 }
1434
1435 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1436   return getNegArgument(const_cast<Value*>(BinOp));
1437 }
1438
1439 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1440   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1441   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1442   Value *Op0 = BO->getOperand(0);
1443   Value *Op1 = BO->getOperand(1);
1444   if (isConstantAllOnes(Op0)) return Op1;
1445
1446   assert(isConstantAllOnes(Op1));
1447   return Op0;
1448 }
1449
1450 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1451   return getNotArgument(const_cast<Value*>(BinOp));
1452 }
1453
1454
1455 // swapOperands - Exchange the two operands to this instruction.  This
1456 // instruction is safe to use on any binary instruction and does not
1457 // modify the semantics of the instruction.  If the instruction is
1458 // order dependent (SetLT f.e.) the opcode is changed.
1459 //
1460 bool BinaryOperator::swapOperands() {
1461   if (!isCommutative())
1462     return true; // Can't commute operands
1463   std::swap(Ops[0], Ops[1]);
1464   return false;
1465 }
1466
1467 //===----------------------------------------------------------------------===//
1468 //                                CastInst Class
1469 //===----------------------------------------------------------------------===//
1470
1471 // Just determine if this cast only deals with integral->integral conversion.
1472 bool CastInst::isIntegerCast() const {
1473   switch (getOpcode()) {
1474     default: return false;
1475     case Instruction::ZExt:
1476     case Instruction::SExt:
1477     case Instruction::Trunc:
1478       return true;
1479     case Instruction::BitCast:
1480       return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1481   }
1482 }
1483
1484 bool CastInst::isLosslessCast() const {
1485   // Only BitCast can be lossless, exit fast if we're not BitCast
1486   if (getOpcode() != Instruction::BitCast)
1487     return false;
1488
1489   // Identity cast is always lossless
1490   const Type* SrcTy = getOperand(0)->getType();
1491   const Type* DstTy = getType();
1492   if (SrcTy == DstTy)
1493     return true;
1494   
1495   // Pointer to pointer is always lossless.
1496   if (isa<PointerType>(SrcTy))
1497     return isa<PointerType>(DstTy);
1498   return false;  // Other types have no identity values
1499 }
1500
1501 /// This function determines if the CastInst does not require any bits to be
1502 /// changed in order to effect the cast. Essentially, it identifies cases where
1503 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
1504 /// example, the following are all no-op casts:
1505 /// # bitcast uint %X, int
1506 /// # bitcast uint* %x, sbyte*
1507 /// # bitcast vector< 2 x int > %x, vector< 4 x short> 
1508 /// # ptrtoint uint* %x, uint     ; on 32-bit plaforms only
1509 /// @brief Determine if a cast is a no-op.
1510 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1511   switch (getOpcode()) {
1512     default:
1513       assert(!"Invalid CastOp");
1514     case Instruction::Trunc:
1515     case Instruction::ZExt:
1516     case Instruction::SExt: 
1517     case Instruction::FPTrunc:
1518     case Instruction::FPExt:
1519     case Instruction::UIToFP:
1520     case Instruction::SIToFP:
1521     case Instruction::FPToUI:
1522     case Instruction::FPToSI:
1523       return false; // These always modify bits
1524     case Instruction::BitCast:
1525       return true;  // BitCast never modifies bits.
1526     case Instruction::PtrToInt:
1527       return IntPtrTy->getPrimitiveSizeInBits() ==
1528             getType()->getPrimitiveSizeInBits();
1529     case Instruction::IntToPtr:
1530       return IntPtrTy->getPrimitiveSizeInBits() ==
1531              getOperand(0)->getType()->getPrimitiveSizeInBits();
1532   }
1533 }
1534
1535 /// This function determines if a pair of casts can be eliminated and what 
1536 /// opcode should be used in the elimination. This assumes that there are two 
1537 /// instructions like this:
1538 /// *  %F = firstOpcode SrcTy %x to MidTy
1539 /// *  %S = secondOpcode MidTy %F to DstTy
1540 /// The function returns a resultOpcode so these two casts can be replaced with:
1541 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
1542 /// If no such cast is permited, the function returns 0.
1543 unsigned CastInst::isEliminableCastPair(
1544   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1545   const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1546 {
1547   // Define the 144 possibilities for these two cast instructions. The values
1548   // in this matrix determine what to do in a given situation and select the
1549   // case in the switch below.  The rows correspond to firstOp, the columns 
1550   // correspond to secondOp.  In looking at the table below, keep in  mind
1551   // the following cast properties:
1552   //
1553   //          Size Compare       Source               Destination
1554   // Operator  Src ? Size   Type       Sign         Type       Sign
1555   // -------- ------------ -------------------   ---------------------
1556   // TRUNC         >       Integer      Any        Integral     Any
1557   // ZEXT          <       Integral   Unsigned     Integer      Any
1558   // SEXT          <       Integral    Signed      Integer      Any
1559   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
1560   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
1561   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
1562   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
1563   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
1564   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
1565   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
1566   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
1567   // BITCONVERT    =       FirstClass   n/a       FirstClass    n/a   
1568   //
1569   // NOTE: some transforms are safe, but we consider them to be non-profitable.
1570   // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1571   // into "fptoui double to ulong", but this loses information about the range
1572   // of the produced value (we no longer know the top-part is all zeros). 
1573   // Further this conversion is often much more expensive for typical hardware,
1574   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
1575   // same reason.
1576   const unsigned numCastOps = 
1577     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1578   static const uint8_t CastResults[numCastOps][numCastOps] = {
1579     // T        F  F  U  S  F  F  P  I  B   -+
1580     // R  Z  S  P  P  I  I  T  P  2  N  T    |
1581     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
1582     // N  X  X  U  S  F  F  N  X  N  2  V    |
1583     // C  T  T  I  I  P  P  C  T  T  P  T   -+
1584     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
1585     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
1586     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
1587     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
1588     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
1589     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
1590     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
1591     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
1592     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
1593     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
1594     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
1595     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
1596   };
1597
1598   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1599                             [secondOp-Instruction::CastOpsBegin];
1600   switch (ElimCase) {
1601     case 0: 
1602       // categorically disallowed
1603       return 0;
1604     case 1: 
1605       // allowed, use first cast's opcode
1606       return firstOp;
1607     case 2: 
1608       // allowed, use second cast's opcode
1609       return secondOp;
1610     case 3: 
1611       // no-op cast in second op implies firstOp as long as the DestTy 
1612       // is integer
1613       if (DstTy->isInteger())
1614         return firstOp;
1615       return 0;
1616     case 4:
1617       // no-op cast in second op implies firstOp as long as the DestTy
1618       // is floating point
1619       if (DstTy->isFloatingPoint())
1620         return firstOp;
1621       return 0;
1622     case 5: 
1623       // no-op cast in first op implies secondOp as long as the SrcTy
1624       // is an integer
1625       if (SrcTy->isInteger())
1626         return secondOp;
1627       return 0;
1628     case 6:
1629       // no-op cast in first op implies secondOp as long as the SrcTy
1630       // is a floating point
1631       if (SrcTy->isFloatingPoint())
1632         return secondOp;
1633       return 0;
1634     case 7: { 
1635       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1636       unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1637       unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1638       if (MidSize >= PtrSize)
1639         return Instruction::BitCast;
1640       return 0;
1641     }
1642     case 8: {
1643       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
1644       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
1645       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
1646       unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1647       unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1648       if (SrcSize == DstSize)
1649         return Instruction::BitCast;
1650       else if (SrcSize < DstSize)
1651         return firstOp;
1652       return secondOp;
1653     }
1654     case 9: // zext, sext -> zext, because sext can't sign extend after zext
1655       return Instruction::ZExt;
1656     case 10:
1657       // fpext followed by ftrunc is allowed if the bit size returned to is
1658       // the same as the original, in which case its just a bitcast
1659       if (SrcTy == DstTy)
1660         return Instruction::BitCast;
1661       return 0; // If the types are not the same we can't eliminate it.
1662     case 11:
1663       // bitcast followed by ptrtoint is allowed as long as the bitcast
1664       // is a pointer to pointer cast.
1665       if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1666         return secondOp;
1667       return 0;
1668     case 12:
1669       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
1670       if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1671         return firstOp;
1672       return 0;
1673     case 13: {
1674       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1675       unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1676       unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1677       unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1678       if (SrcSize <= PtrSize && SrcSize == DstSize)
1679         return Instruction::BitCast;
1680       return 0;
1681     }
1682     case 99: 
1683       // cast combination can't happen (error in input). This is for all cases
1684       // where the MidTy is not the same for the two cast instructions.
1685       assert(!"Invalid Cast Combination");
1686       return 0;
1687     default:
1688       assert(!"Error in CastResults table!!!");
1689       return 0;
1690   }
1691   return 0;
1692 }
1693
1694 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty, 
1695   const std::string &Name, Instruction *InsertBefore) {
1696   // Construct and return the appropriate CastInst subclass
1697   switch (op) {
1698     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
1699     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
1700     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
1701     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
1702     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
1703     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
1704     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
1705     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
1706     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
1707     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1708     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1709     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
1710     default:
1711       assert(!"Invalid opcode provided");
1712   }
1713   return 0;
1714 }
1715
1716 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1717   const std::string &Name, BasicBlock *InsertAtEnd) {
1718   // Construct and return the appropriate CastInst subclass
1719   switch (op) {
1720     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
1721     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
1722     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
1723     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
1724     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
1725     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
1726     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
1727     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
1728     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
1729     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1730     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1731     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
1732     default:
1733       assert(!"Invalid opcode provided");
1734   }
1735   return 0;
1736 }
1737
1738 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty, 
1739                                         const std::string &Name,
1740                                         Instruction *InsertBefore) {
1741   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1742     return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1743   return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1744 }
1745
1746 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty, 
1747                                         const std::string &Name,
1748                                         BasicBlock *InsertAtEnd) {
1749   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1750     return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1751   return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1752 }
1753
1754 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty, 
1755                                         const std::string &Name,
1756                                         Instruction *InsertBefore) {
1757   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1758     return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1759   return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1760 }
1761
1762 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty, 
1763                                         const std::string &Name,
1764                                         BasicBlock *InsertAtEnd) {
1765   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1766     return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1767   return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1768 }
1769
1770 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1771                                          const std::string &Name,
1772                                          Instruction *InsertBefore) {
1773   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1774     return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1775   return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1776 }
1777
1778 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1779                                          const std::string &Name, 
1780                                          BasicBlock *InsertAtEnd) {
1781   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1782     return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1783   return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1784 }
1785
1786 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1787                                       const std::string &Name,
1788                                       BasicBlock *InsertAtEnd) {
1789   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1790   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1791          "Invalid cast");
1792
1793   if (Ty->isInteger())
1794     return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1795   return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1796 }
1797
1798 /// @brief Create a BitCast or a PtrToInt cast instruction
1799 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty, 
1800                                       const std::string &Name, 
1801                                       Instruction *InsertBefore) {
1802   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1803   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1804          "Invalid cast");
1805
1806   if (Ty->isInteger())
1807     return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1808   return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1809 }
1810
1811 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty, 
1812                                       bool isSigned, const std::string &Name,
1813                                       Instruction *InsertBefore) {
1814   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1815   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1816   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1817   Instruction::CastOps opcode =
1818     (SrcBits == DstBits ? Instruction::BitCast :
1819      (SrcBits > DstBits ? Instruction::Trunc :
1820       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1821   return create(opcode, C, Ty, Name, InsertBefore);
1822 }
1823
1824 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty, 
1825                                       bool isSigned, const std::string &Name,
1826                                       BasicBlock *InsertAtEnd) {
1827   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1828   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1829   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1830   Instruction::CastOps opcode =
1831     (SrcBits == DstBits ? Instruction::BitCast :
1832      (SrcBits > DstBits ? Instruction::Trunc :
1833       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1834   return create(opcode, C, Ty, Name, InsertAtEnd);
1835 }
1836
1837 CastInst *CastInst::createFPCast(Value *C, const Type *Ty, 
1838                                  const std::string &Name, 
1839                                  Instruction *InsertBefore) {
1840   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
1841          "Invalid cast");
1842   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1843   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1844   Instruction::CastOps opcode =
1845     (SrcBits == DstBits ? Instruction::BitCast :
1846      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1847   return create(opcode, C, Ty, Name, InsertBefore);
1848 }
1849
1850 CastInst *CastInst::createFPCast(Value *C, const Type *Ty, 
1851                                  const std::string &Name, 
1852                                  BasicBlock *InsertAtEnd) {
1853   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
1854          "Invalid cast");
1855   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1856   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1857   Instruction::CastOps opcode =
1858     (SrcBits == DstBits ? Instruction::BitCast :
1859      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1860   return create(opcode, C, Ty, Name, InsertAtEnd);
1861 }
1862
1863 // Provide a way to get a "cast" where the cast opcode is inferred from the 
1864 // types and size of the operand. This, basically, is a parallel of the 
1865 // logic in the castIsValid function below.  This axiom should hold:
1866 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1867 // should not assert in castIsValid. In other words, this produces a "correct"
1868 // casting opcode for the arguments passed to it.
1869 Instruction::CastOps
1870 CastInst::getCastOpcode(
1871   const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1872   // Get the bit sizes, we'll need these
1873   const Type *SrcTy = Src->getType();
1874   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr/vector
1875   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1876
1877   // Run through the possibilities ...
1878   if (DestTy->isInteger()) {                       // Casting to integral
1879     if (SrcTy->isInteger()) {                      // Casting from integral
1880       if (DestBits < SrcBits)
1881         return Trunc;                               // int -> smaller int
1882       else if (DestBits > SrcBits) {                // its an extension
1883         if (SrcIsSigned)
1884           return SExt;                              // signed -> SEXT
1885         else
1886           return ZExt;                              // unsigned -> ZEXT
1887       } else {
1888         return BitCast;                             // Same size, No-op cast
1889       }
1890     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
1891       if (DestIsSigned) 
1892         return FPToSI;                              // FP -> sint
1893       else
1894         return FPToUI;                              // FP -> uint 
1895     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1896       assert(DestBits == PTy->getBitWidth() &&
1897                "Casting vector to integer of different width");
1898       return BitCast;                             // Same size, no-op cast
1899     } else {
1900       assert(isa<PointerType>(SrcTy) &&
1901              "Casting from a value that is not first-class type");
1902       return PtrToInt;                              // ptr -> int
1903     }
1904   } else if (DestTy->isFloatingPoint()) {           // Casting to floating pt
1905     if (SrcTy->isInteger()) {                      // Casting from integral
1906       if (SrcIsSigned)
1907         return SIToFP;                              // sint -> FP
1908       else
1909         return UIToFP;                              // uint -> FP
1910     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
1911       if (DestBits < SrcBits) {
1912         return FPTrunc;                             // FP -> smaller FP
1913       } else if (DestBits > SrcBits) {
1914         return FPExt;                               // FP -> larger FP
1915       } else  {
1916         return BitCast;                             // same size, no-op cast
1917       }
1918     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1919       assert(DestBits == PTy->getBitWidth() &&
1920              "Casting vector to floating point of different width");
1921         return BitCast;                             // same size, no-op cast
1922     } else {
1923       assert(0 && "Casting pointer or non-first class to float");
1924     }
1925   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1926     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1927       assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1928              "Casting vector to vector of different widths");
1929       return BitCast;                             // vector -> vector
1930     } else if (DestPTy->getBitWidth() == SrcBits) {
1931       return BitCast;                               // float/int -> vector
1932     } else {
1933       assert(!"Illegal cast to vector (wrong type or size)");
1934     }
1935   } else if (isa<PointerType>(DestTy)) {
1936     if (isa<PointerType>(SrcTy)) {
1937       return BitCast;                               // ptr -> ptr
1938     } else if (SrcTy->isInteger()) {
1939       return IntToPtr;                              // int -> ptr
1940     } else {
1941       assert(!"Casting pointer to other than pointer or int");
1942     }
1943   } else {
1944     assert(!"Casting to type that is not first-class");
1945   }
1946
1947   // If we fall through to here we probably hit an assertion cast above
1948   // and assertions are not turned on. Anything we return is an error, so
1949   // BitCast is as good a choice as any.
1950   return BitCast;
1951 }
1952
1953 //===----------------------------------------------------------------------===//
1954 //                    CastInst SubClass Constructors
1955 //===----------------------------------------------------------------------===//
1956
1957 /// Check that the construction parameters for a CastInst are correct. This
1958 /// could be broken out into the separate constructors but it is useful to have
1959 /// it in one place and to eliminate the redundant code for getting the sizes
1960 /// of the types involved.
1961 bool 
1962 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1963
1964   // Check for type sanity on the arguments
1965   const Type *SrcTy = S->getType();
1966   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1967     return false;
1968
1969   // Get the size of the types in bits, we'll need this later
1970   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1971   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1972
1973   // Switch on the opcode provided
1974   switch (op) {
1975   default: return false; // This is an input error
1976   case Instruction::Trunc:
1977     return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1978   case Instruction::ZExt:
1979     return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1980   case Instruction::SExt: 
1981     return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1982   case Instruction::FPTrunc:
1983     return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() && 
1984       SrcBitSize > DstBitSize;
1985   case Instruction::FPExt:
1986     return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() && 
1987       SrcBitSize < DstBitSize;
1988   case Instruction::UIToFP:
1989     return SrcTy->isInteger() && DstTy->isFloatingPoint();
1990   case Instruction::SIToFP:
1991     return SrcTy->isInteger() && DstTy->isFloatingPoint();
1992   case Instruction::FPToUI:
1993     return SrcTy->isFloatingPoint() && DstTy->isInteger();
1994   case Instruction::FPToSI:
1995     return SrcTy->isFloatingPoint() && DstTy->isInteger();
1996   case Instruction::PtrToInt:
1997     return isa<PointerType>(SrcTy) && DstTy->isInteger();
1998   case Instruction::IntToPtr:
1999     return SrcTy->isInteger() && isa<PointerType>(DstTy);
2000   case Instruction::BitCast:
2001     // BitCast implies a no-op cast of type only. No bits change.
2002     // However, you can't cast pointers to anything but pointers.
2003     if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2004       return false;
2005
2006     // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
2007     // these cases, the cast is okay if the source and destination bit widths
2008     // are identical.
2009     return SrcBitSize == DstBitSize;
2010   }
2011 }
2012
2013 TruncInst::TruncInst(
2014   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2015 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2016   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2017 }
2018
2019 TruncInst::TruncInst(
2020   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2021 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
2022   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2023 }
2024
2025 ZExtInst::ZExtInst(
2026   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2027 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
2028   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2029 }
2030
2031 ZExtInst::ZExtInst(
2032   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2033 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
2034   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2035 }
2036 SExtInst::SExtInst(
2037   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2038 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
2039   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2040 }
2041
2042 SExtInst::SExtInst(
2043   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2044 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
2045   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2046 }
2047
2048 FPTruncInst::FPTruncInst(
2049   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2050 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
2051   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2052 }
2053
2054 FPTruncInst::FPTruncInst(
2055   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2056 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
2057   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2058 }
2059
2060 FPExtInst::FPExtInst(
2061   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2062 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
2063   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2064 }
2065
2066 FPExtInst::FPExtInst(
2067   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2068 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
2069   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2070 }
2071
2072 UIToFPInst::UIToFPInst(
2073   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2074 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
2075   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2076 }
2077
2078 UIToFPInst::UIToFPInst(
2079   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2080 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
2081   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2082 }
2083
2084 SIToFPInst::SIToFPInst(
2085   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2086 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
2087   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2088 }
2089
2090 SIToFPInst::SIToFPInst(
2091   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2092 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
2093   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2094 }
2095
2096 FPToUIInst::FPToUIInst(
2097   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2098 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
2099   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2100 }
2101
2102 FPToUIInst::FPToUIInst(
2103   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2104 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
2105   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2106 }
2107
2108 FPToSIInst::FPToSIInst(
2109   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2110 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
2111   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2112 }
2113
2114 FPToSIInst::FPToSIInst(
2115   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2116 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
2117   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2118 }
2119
2120 PtrToIntInst::PtrToIntInst(
2121   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2122 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
2123   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2124 }
2125
2126 PtrToIntInst::PtrToIntInst(
2127   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2128 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
2129   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2130 }
2131
2132 IntToPtrInst::IntToPtrInst(
2133   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2134 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
2135   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2136 }
2137
2138 IntToPtrInst::IntToPtrInst(
2139   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2140 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
2141   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2142 }
2143
2144 BitCastInst::BitCastInst(
2145   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2146 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
2147   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2148 }
2149
2150 BitCastInst::BitCastInst(
2151   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2152 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
2153   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2154 }
2155
2156 //===----------------------------------------------------------------------===//
2157 //                               CmpInst Classes
2158 //===----------------------------------------------------------------------===//
2159
2160 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2161                  const std::string &Name, Instruction *InsertBefore)
2162   : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2163     Ops[0].init(LHS, this);
2164     Ops[1].init(RHS, this);
2165   SubclassData = predicate;
2166   setName(Name);
2167   if (op == Instruction::ICmp) {
2168     assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2169            predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2170            "Invalid ICmp predicate value");
2171     const Type* Op0Ty = getOperand(0)->getType();
2172     const Type* Op1Ty = getOperand(1)->getType();
2173     assert(Op0Ty == Op1Ty &&
2174            "Both operands to ICmp instruction are not of the same type!");
2175     // Check that the operands are the right type
2176     assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2177            "Invalid operand types for ICmp instruction");
2178     return;
2179   }
2180   assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2181   assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2182          "Invalid FCmp predicate value");
2183   const Type* Op0Ty = getOperand(0)->getType();
2184   const Type* Op1Ty = getOperand(1)->getType();
2185   assert(Op0Ty == Op1Ty &&
2186          "Both operands to FCmp instruction are not of the same type!");
2187   // Check that the operands are the right type
2188   assert(Op0Ty->isFloatingPoint() &&
2189          "Invalid operand types for FCmp instruction");
2190 }
2191   
2192 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2193                  const std::string &Name, BasicBlock *InsertAtEnd)
2194   : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2195   Ops[0].init(LHS, this);
2196   Ops[1].init(RHS, this);
2197   SubclassData = predicate;
2198   setName(Name);
2199   if (op == Instruction::ICmp) {
2200     assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2201            predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2202            "Invalid ICmp predicate value");
2203
2204     const Type* Op0Ty = getOperand(0)->getType();
2205     const Type* Op1Ty = getOperand(1)->getType();
2206     assert(Op0Ty == Op1Ty &&
2207           "Both operands to ICmp instruction are not of the same type!");
2208     // Check that the operands are the right type
2209     assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2210            "Invalid operand types for ICmp instruction");
2211     return;
2212   }
2213   assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2214   assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2215          "Invalid FCmp predicate value");
2216   const Type* Op0Ty = getOperand(0)->getType();
2217   const Type* Op1Ty = getOperand(1)->getType();
2218   assert(Op0Ty == Op1Ty &&
2219           "Both operands to FCmp instruction are not of the same type!");
2220   // Check that the operands are the right type
2221   assert(Op0Ty->isFloatingPoint() &&
2222         "Invalid operand types for FCmp instruction");
2223 }
2224
2225 CmpInst *
2226 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2227                 const std::string &Name, Instruction *InsertBefore) {
2228   if (Op == Instruction::ICmp) {
2229     return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name, 
2230                         InsertBefore);
2231   }
2232   return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name, 
2233                       InsertBefore);
2234 }
2235
2236 CmpInst *
2237 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2238                 const std::string &Name, BasicBlock *InsertAtEnd) {
2239   if (Op == Instruction::ICmp) {
2240     return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name, 
2241                         InsertAtEnd);
2242   }
2243   return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name, 
2244                       InsertAtEnd);
2245 }
2246
2247 void CmpInst::swapOperands() {
2248   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2249     IC->swapOperands();
2250   else
2251     cast<FCmpInst>(this)->swapOperands();
2252 }
2253
2254 bool CmpInst::isCommutative() {
2255   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2256     return IC->isCommutative();
2257   return cast<FCmpInst>(this)->isCommutative();
2258 }
2259
2260 bool CmpInst::isEquality() {
2261   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2262     return IC->isEquality();
2263   return cast<FCmpInst>(this)->isEquality();
2264 }
2265
2266
2267 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2268   switch (pred) {
2269     default:
2270       assert(!"Unknown icmp predicate!");
2271     case ICMP_EQ: return ICMP_NE;
2272     case ICMP_NE: return ICMP_EQ;
2273     case ICMP_UGT: return ICMP_ULE;
2274     case ICMP_ULT: return ICMP_UGE;
2275     case ICMP_UGE: return ICMP_ULT;
2276     case ICMP_ULE: return ICMP_UGT;
2277     case ICMP_SGT: return ICMP_SLE;
2278     case ICMP_SLT: return ICMP_SGE;
2279     case ICMP_SGE: return ICMP_SLT;
2280     case ICMP_SLE: return ICMP_SGT;
2281   }
2282 }
2283
2284 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2285   switch (pred) {
2286     default: assert(! "Unknown icmp predicate!");
2287     case ICMP_EQ: case ICMP_NE:
2288       return pred;
2289     case ICMP_SGT: return ICMP_SLT;
2290     case ICMP_SLT: return ICMP_SGT;
2291     case ICMP_SGE: return ICMP_SLE;
2292     case ICMP_SLE: return ICMP_SGE;
2293     case ICMP_UGT: return ICMP_ULT;
2294     case ICMP_ULT: return ICMP_UGT;
2295     case ICMP_UGE: return ICMP_ULE;
2296     case ICMP_ULE: return ICMP_UGE;
2297   }
2298 }
2299
2300 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2301   switch (pred) {
2302     default: assert(! "Unknown icmp predicate!");
2303     case ICMP_EQ: case ICMP_NE: 
2304     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2305        return pred;
2306     case ICMP_UGT: return ICMP_SGT;
2307     case ICMP_ULT: return ICMP_SLT;
2308     case ICMP_UGE: return ICMP_SGE;
2309     case ICMP_ULE: return ICMP_SLE;
2310   }
2311 }
2312
2313 bool ICmpInst::isSignedPredicate(Predicate pred) {
2314   switch (pred) {
2315     default: assert(! "Unknown icmp predicate!");
2316     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2317       return true;
2318     case ICMP_EQ:  case ICMP_NE: case ICMP_UGT: case ICMP_ULT: 
2319     case ICMP_UGE: case ICMP_ULE:
2320       return false;
2321   }
2322 }
2323
2324 /// Initialize a set of values that all satisfy the condition with C.
2325 ///
2326 ConstantRange 
2327 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2328   APInt Lower(C);
2329   APInt Upper(C);
2330   uint32_t BitWidth = C.getBitWidth();
2331   switch (pred) {
2332   default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2333   case ICmpInst::ICMP_EQ: Upper++; break;
2334   case ICmpInst::ICMP_NE: Lower++; break;
2335   case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2336   case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2337   case ICmpInst::ICMP_UGT: 
2338     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2339     break;
2340   case ICmpInst::ICMP_SGT:
2341     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2342     break;
2343   case ICmpInst::ICMP_ULE: 
2344     Lower = APInt::getMinValue(BitWidth); Upper++; 
2345     break;
2346   case ICmpInst::ICMP_SLE: 
2347     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
2348     break;
2349   case ICmpInst::ICMP_UGE:
2350     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2351     break;
2352   case ICmpInst::ICMP_SGE:
2353     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2354     break;
2355   }
2356   return ConstantRange(Lower, Upper);
2357 }
2358
2359 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2360   switch (pred) {
2361     default:
2362       assert(!"Unknown icmp predicate!");
2363     case FCMP_OEQ: return FCMP_UNE;
2364     case FCMP_ONE: return FCMP_UEQ;
2365     case FCMP_OGT: return FCMP_ULE;
2366     case FCMP_OLT: return FCMP_UGE;
2367     case FCMP_OGE: return FCMP_ULT;
2368     case FCMP_OLE: return FCMP_UGT;
2369     case FCMP_UEQ: return FCMP_ONE;
2370     case FCMP_UNE: return FCMP_OEQ;
2371     case FCMP_UGT: return FCMP_OLE;
2372     case FCMP_ULT: return FCMP_OGE;
2373     case FCMP_UGE: return FCMP_OLT;
2374     case FCMP_ULE: return FCMP_OGT;
2375     case FCMP_ORD: return FCMP_UNO;
2376     case FCMP_UNO: return FCMP_ORD;
2377     case FCMP_TRUE: return FCMP_FALSE;
2378     case FCMP_FALSE: return FCMP_TRUE;
2379   }
2380 }
2381
2382 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2383   switch (pred) {
2384     default: assert(!"Unknown fcmp predicate!");
2385     case FCMP_FALSE: case FCMP_TRUE:
2386     case FCMP_OEQ: case FCMP_ONE:
2387     case FCMP_UEQ: case FCMP_UNE:
2388     case FCMP_ORD: case FCMP_UNO:
2389       return pred;
2390     case FCMP_OGT: return FCMP_OLT;
2391     case FCMP_OLT: return FCMP_OGT;
2392     case FCMP_OGE: return FCMP_OLE;
2393     case FCMP_OLE: return FCMP_OGE;
2394     case FCMP_UGT: return FCMP_ULT;
2395     case FCMP_ULT: return FCMP_UGT;
2396     case FCMP_UGE: return FCMP_ULE;
2397     case FCMP_ULE: return FCMP_UGE;
2398   }
2399 }
2400
2401 bool CmpInst::isUnsigned(unsigned short predicate) {
2402   switch (predicate) {
2403     default: return false;
2404     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
2405     case ICmpInst::ICMP_UGE: return true;
2406   }
2407 }
2408
2409 bool CmpInst::isSigned(unsigned short predicate){
2410   switch (predicate) {
2411     default: return false;
2412     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
2413     case ICmpInst::ICMP_SGE: return true;
2414   }
2415 }
2416
2417 bool CmpInst::isOrdered(unsigned short predicate) {
2418   switch (predicate) {
2419     default: return false;
2420     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
2421     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
2422     case FCmpInst::FCMP_ORD: return true;
2423   }
2424 }
2425       
2426 bool CmpInst::isUnordered(unsigned short predicate) {
2427   switch (predicate) {
2428     default: return false;
2429     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
2430     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
2431     case FCmpInst::FCMP_UNO: return true;
2432   }
2433 }
2434
2435 //===----------------------------------------------------------------------===//
2436 //                        SwitchInst Implementation
2437 //===----------------------------------------------------------------------===//
2438
2439 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2440   assert(Value && Default);
2441   ReservedSpace = 2+NumCases*2;
2442   NumOperands = 2;
2443   OperandList = new Use[ReservedSpace];
2444
2445   OperandList[0].init(Value, this);
2446   OperandList[1].init(Default, this);
2447 }
2448
2449 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2450 /// switch on and a default destination.  The number of additional cases can
2451 /// be specified here to make memory allocation more efficient.  This
2452 /// constructor can also autoinsert before another instruction.
2453 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2454                        Instruction *InsertBefore)
2455   : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2456   init(Value, Default, NumCases);
2457 }
2458
2459 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2460 /// switch on and a default destination.  The number of additional cases can
2461 /// be specified here to make memory allocation more efficient.  This
2462 /// constructor also autoinserts at the end of the specified BasicBlock.
2463 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2464                        BasicBlock *InsertAtEnd)
2465   : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2466   init(Value, Default, NumCases);
2467 }
2468
2469 SwitchInst::SwitchInst(const SwitchInst &SI)
2470   : TerminatorInst(Type::VoidTy, Instruction::Switch,
2471                    new Use[SI.getNumOperands()], SI.getNumOperands()) {
2472   Use *OL = OperandList, *InOL = SI.OperandList;
2473   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2474     OL[i].init(InOL[i], this);
2475     OL[i+1].init(InOL[i+1], this);
2476   }
2477 }
2478
2479 SwitchInst::~SwitchInst() {
2480   delete [] OperandList;
2481 }
2482
2483
2484 /// addCase - Add an entry to the switch instruction...
2485 ///
2486 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2487   unsigned OpNo = NumOperands;
2488   if (OpNo+2 > ReservedSpace)
2489     resizeOperands(0);  // Get more space!
2490   // Initialize some new operands.
2491   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2492   NumOperands = OpNo+2;
2493   OperandList[OpNo].init(OnVal, this);
2494   OperandList[OpNo+1].init(Dest, this);
2495 }
2496
2497 /// removeCase - This method removes the specified successor from the switch
2498 /// instruction.  Note that this cannot be used to remove the default
2499 /// destination (successor #0).
2500 ///
2501 void SwitchInst::removeCase(unsigned idx) {
2502   assert(idx != 0 && "Cannot remove the default case!");
2503   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2504
2505   unsigned NumOps = getNumOperands();
2506   Use *OL = OperandList;
2507
2508   // Move everything after this operand down.
2509   //
2510   // FIXME: we could just swap with the end of the list, then erase.  However,
2511   // client might not expect this to happen.  The code as it is thrashes the
2512   // use/def lists, which is kinda lame.
2513   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2514     OL[i-2] = OL[i];
2515     OL[i-2+1] = OL[i+1];
2516   }
2517
2518   // Nuke the last value.
2519   OL[NumOps-2].set(0);
2520   OL[NumOps-2+1].set(0);
2521   NumOperands = NumOps-2;
2522 }
2523
2524 /// resizeOperands - resize operands - This adjusts the length of the operands
2525 /// list according to the following behavior:
2526 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
2527 ///      of operation.  This grows the number of ops by 1.5 times.
2528 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
2529 ///   3. If NumOps == NumOperands, trim the reserved space.
2530 ///
2531 void SwitchInst::resizeOperands(unsigned NumOps) {
2532   if (NumOps == 0) {
2533     NumOps = getNumOperands()/2*6;
2534   } else if (NumOps*2 > NumOperands) {
2535     // No resize needed.
2536     if (ReservedSpace >= NumOps) return;
2537   } else if (NumOps == NumOperands) {
2538     if (ReservedSpace == NumOps) return;
2539   } else {
2540     return;
2541   }
2542
2543   ReservedSpace = NumOps;
2544   Use *NewOps = new Use[NumOps];
2545   Use *OldOps = OperandList;
2546   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2547       NewOps[i].init(OldOps[i], this);
2548       OldOps[i].set(0);
2549   }
2550   delete [] OldOps;
2551   OperandList = NewOps;
2552 }
2553
2554
2555 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2556   return getSuccessor(idx);
2557 }
2558 unsigned SwitchInst::getNumSuccessorsV() const {
2559   return getNumSuccessors();
2560 }
2561 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2562   setSuccessor(idx, B);
2563 }
2564
2565
2566 // Define these methods here so vtables don't get emitted into every translation
2567 // unit that uses these classes.
2568
2569 GetElementPtrInst *GetElementPtrInst::clone() const {
2570   return new GetElementPtrInst(*this);
2571 }
2572
2573 BinaryOperator *BinaryOperator::clone() const {
2574   return create(getOpcode(), Ops[0], Ops[1]);
2575 }
2576
2577 CmpInst* CmpInst::clone() const {
2578   return create(getOpcode(), getPredicate(), Ops[0], Ops[1]);
2579 }
2580
2581 MallocInst *MallocInst::clone()   const { return new MallocInst(*this); }
2582 AllocaInst *AllocaInst::clone()   const { return new AllocaInst(*this); }
2583 FreeInst   *FreeInst::clone()     const { return new FreeInst(getOperand(0)); }
2584 LoadInst   *LoadInst::clone()     const { return new LoadInst(*this); }
2585 StoreInst  *StoreInst::clone()    const { return new StoreInst(*this); }
2586 CastInst   *TruncInst::clone()    const { return new TruncInst(*this); }
2587 CastInst   *ZExtInst::clone()     const { return new ZExtInst(*this); }
2588 CastInst   *SExtInst::clone()     const { return new SExtInst(*this); }
2589 CastInst   *FPTruncInst::clone()  const { return new FPTruncInst(*this); }
2590 CastInst   *FPExtInst::clone()    const { return new FPExtInst(*this); }
2591 CastInst   *UIToFPInst::clone()   const { return new UIToFPInst(*this); }
2592 CastInst   *SIToFPInst::clone()   const { return new SIToFPInst(*this); }
2593 CastInst   *FPToUIInst::clone()   const { return new FPToUIInst(*this); }
2594 CastInst   *FPToSIInst::clone()   const { return new FPToSIInst(*this); }
2595 CastInst   *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2596 CastInst   *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2597 CastInst   *BitCastInst::clone()  const { return new BitCastInst(*this); }
2598 CallInst   *CallInst::clone()     const { return new CallInst(*this); }
2599 SelectInst *SelectInst::clone()   const { return new SelectInst(*this); }
2600 VAArgInst  *VAArgInst::clone()    const { return new VAArgInst(*this); }
2601
2602 ExtractElementInst *ExtractElementInst::clone() const {
2603   return new ExtractElementInst(*this);
2604 }
2605 InsertElementInst *InsertElementInst::clone() const {
2606   return new InsertElementInst(*this);
2607 }
2608 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2609   return new ShuffleVectorInst(*this);
2610 }
2611 PHINode    *PHINode::clone()    const { return new PHINode(*this); }
2612 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2613 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2614 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2615 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2616 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2617 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}