LLVM API Documentation

Instructions.cpp

Go to the documentation of this file.
00001 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements all of the non-inline methods for the LLVM instruction
00011 // classes.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Constants.h"
00016 #include "llvm/DerivedTypes.h"
00017 #include "llvm/Function.h"
00018 #include "llvm/Instructions.h"
00019 #include "llvm/Operator.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 #include "llvm/Support/CallSite.h"
00022 #include "llvm/Support/ConstantRange.h"
00023 #include "llvm/Support/MathExtras.h"
00024 using namespace llvm;
00025 
00026 //===----------------------------------------------------------------------===//
00027 //                            CallSite Class
00028 //===----------------------------------------------------------------------===//
00029 
00030 #define CALLSITE_DELEGATE_GETTER(METHOD) \
00031   Instruction *II(getInstruction());     \
00032   return isCall()                        \
00033     ? cast<CallInst>(II)->METHOD         \
00034     : cast<InvokeInst>(II)->METHOD
00035 
00036 #define CALLSITE_DELEGATE_SETTER(METHOD) \
00037   Instruction *II(getInstruction());     \
00038   if (isCall())                          \
00039     cast<CallInst>(II)->METHOD;          \
00040   else                                   \
00041     cast<InvokeInst>(II)->METHOD
00042 
00043 CallSite::CallSite(Instruction *C) {
00044   assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
00045   I.setPointer(C);
00046   I.setInt(isa<CallInst>(C));
00047 }
00048 unsigned CallSite::getCallingConv() const {
00049   CALLSITE_DELEGATE_GETTER(getCallingConv());
00050 }
00051 void CallSite::setCallingConv(unsigned CC) {
00052   CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
00053 }
00054 const AttrListPtr &CallSite::getAttributes() const {
00055   CALLSITE_DELEGATE_GETTER(getAttributes());
00056 }
00057 void CallSite::setAttributes(const AttrListPtr &PAL) {
00058   CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
00059 }
00060 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
00061   CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
00062 }
00063 uint16_t CallSite::getParamAlignment(uint16_t i) const {
00064   CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
00065 }
00066 bool CallSite::doesNotAccessMemory() const {
00067   CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
00068 }
00069 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
00070   CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
00071 }
00072 bool CallSite::onlyReadsMemory() const {
00073   CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
00074 }
00075 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
00076   CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
00077 }
00078 bool CallSite::doesNotReturn() const {
00079  CALLSITE_DELEGATE_GETTER(doesNotReturn());
00080 }
00081 void CallSite::setDoesNotReturn(bool doesNotReturn) {
00082   CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
00083 }
00084 bool CallSite::doesNotThrow() const {
00085   CALLSITE_DELEGATE_GETTER(doesNotThrow());
00086 }
00087 void CallSite::setDoesNotThrow(bool doesNotThrow) {
00088   CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
00089 }
00090 
00091 bool CallSite::hasArgument(const Value *Arg) const {
00092   for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
00093     if (AI->get() == Arg)
00094       return true;
00095   return false;
00096 }
00097 
00098 #undef CALLSITE_DELEGATE_GETTER
00099 #undef CALLSITE_DELEGATE_SETTER
00100 
00101 //===----------------------------------------------------------------------===//
00102 //                            TerminatorInst Class
00103 //===----------------------------------------------------------------------===//
00104 
00105 // Out of line virtual method, so the vtable, etc has a home.
00106 TerminatorInst::~TerminatorInst() {
00107 }
00108 
00109 //===----------------------------------------------------------------------===//
00110 //                           UnaryInstruction Class
00111 //===----------------------------------------------------------------------===//
00112 
00113 // Out of line virtual method, so the vtable, etc has a home.
00114 UnaryInstruction::~UnaryInstruction() {
00115 }
00116 
00117 //===----------------------------------------------------------------------===//
00118 //                              SelectInst Class
00119 //===----------------------------------------------------------------------===//
00120 
00121 /// areInvalidOperands - Return a string if the specified operands are invalid
00122 /// for a select operation, otherwise return null.
00123 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
00124   if (Op1->getType() != Op2->getType())
00125     return "both values to select must have same type";
00126   
00127   if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
00128     // Vector select.
00129     if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
00130       return "vector select condition element type must be i1";
00131     const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
00132     if (ET == 0)
00133       return "selected values for vector select must be vectors";
00134     if (ET->getNumElements() != VT->getNumElements())
00135       return "vector select requires selected vectors to have "
00136                    "the same vector length as select condition";
00137   } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
00138     return "select condition must be i1 or <n x i1>";
00139   }
00140   return 0;
00141 }
00142 
00143 
00144 //===----------------------------------------------------------------------===//
00145 //                               PHINode Class
00146 //===----------------------------------------------------------------------===//
00147 
00148 PHINode::PHINode(const PHINode &PN)
00149   : Instruction(PN.getType(), Instruction::PHI,
00150                 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
00151     ReservedSpace(PN.getNumOperands()) {
00152   Use *OL = OperandList;
00153   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
00154     OL[i] = PN.getOperand(i);
00155     OL[i+1] = PN.getOperand(i+1);
00156   }
00157   SubclassOptionalData = PN.SubclassOptionalData;
00158 }
00159 
00160 PHINode::~PHINode() {
00161   if (OperandList)
00162     dropHungoffUses(OperandList);
00163 }
00164 
00165 // removeIncomingValue - Remove an incoming value.  This is useful if a
00166 // predecessor basic block is deleted.
00167 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
00168   unsigned NumOps = getNumOperands();
00169   Use *OL = OperandList;
00170   assert(Idx*2 < NumOps && "BB not in PHI node!");
00171   Value *Removed = OL[Idx*2];
00172 
00173   // Move everything after this operand down.
00174   //
00175   // FIXME: we could just swap with the end of the list, then erase.  However,
00176   // client might not expect this to happen.  The code as it is thrashes the
00177   // use/def lists, which is kinda lame.
00178   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
00179     OL[i-2] = OL[i];
00180     OL[i-2+1] = OL[i+1];
00181   }
00182 
00183   // Nuke the last value.
00184   OL[NumOps-2].set(0);
00185   OL[NumOps-2+1].set(0);
00186   NumOperands = NumOps-2;
00187 
00188   // If the PHI node is dead, because it has zero entries, nuke it now.
00189   if (NumOps == 2 && DeletePHIIfEmpty) {
00190     // If anyone is using this PHI, make them use a dummy value instead...
00191     replaceAllUsesWith(UndefValue::get(getType()));
00192     eraseFromParent();
00193   }
00194   return Removed;
00195 }
00196 
00197 /// resizeOperands - resize operands - This adjusts the length of the operands
00198 /// list according to the following behavior:
00199 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
00200 ///      of operation.  This grows the number of ops by 1.5 times.
00201 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
00202 ///   3. If NumOps == NumOperands, trim the reserved space.
00203 ///
00204 void PHINode::resizeOperands(unsigned NumOps) {
00205   unsigned e = getNumOperands();
00206   if (NumOps == 0) {
00207     NumOps = e*3/2;
00208     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
00209   } else if (NumOps*2 > NumOperands) {
00210     // No resize needed.
00211     if (ReservedSpace >= NumOps) return;
00212   } else if (NumOps == NumOperands) {
00213     if (ReservedSpace == NumOps) return;
00214   } else {
00215     return;
00216   }
00217 
00218   ReservedSpace = NumOps;
00219   Use *OldOps = OperandList;
00220   Use *NewOps = allocHungoffUses(NumOps);
00221   std::copy(OldOps, OldOps + e, NewOps);
00222   OperandList = NewOps;
00223   if (OldOps) Use::zap(OldOps, OldOps + e, true);
00224 }
00225 
00226 /// hasConstantValue - If the specified PHI node always merges together the same
00227 /// value, return the value, otherwise return null.
00228 ///
00229 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
00230   // If the PHI node only has one incoming value, eliminate the PHI node...
00231   if (getNumIncomingValues() == 1) {
00232     if (getIncomingValue(0) != this)   // not  X = phi X
00233       return getIncomingValue(0);
00234     else
00235       return UndefValue::get(getType());  // Self cycle is dead.
00236   }
00237       
00238   // Otherwise if all of the incoming values are the same for the PHI, replace
00239   // the PHI node with the incoming value.
00240   //
00241   Value *InVal = 0;
00242   bool HasUndefInput = false;
00243   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
00244     if (isa<UndefValue>(getIncomingValue(i))) {
00245       HasUndefInput = true;
00246     } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
00247       if (InVal && getIncomingValue(i) != InVal)
00248         return 0;  // Not the same, bail out.
00249       else
00250         InVal = getIncomingValue(i);
00251     }
00252   
00253   // The only case that could cause InVal to be null is if we have a PHI node
00254   // that only has entries for itself.  In this case, there is no entry into the
00255   // loop, so kill the PHI.
00256   //
00257   if (InVal == 0) InVal = UndefValue::get(getType());
00258   
00259   // If we have a PHI node like phi(X, undef, X), where X is defined by some
00260   // instruction, we cannot always return X as the result of the PHI node.  Only
00261   // do this if X is not an instruction (thus it must dominate the PHI block),
00262   // or if the client is prepared to deal with this possibility.
00263   if (HasUndefInput && !AllowNonDominatingInstruction)
00264     if (Instruction *IV = dyn_cast<Instruction>(InVal))
00265       // If it's in the entry block, it dominates everything.
00266       if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
00267           isa<InvokeInst>(IV))
00268         return 0;   // Cannot guarantee that InVal dominates this PHINode.
00269 
00270   // All of the incoming values are the same, return the value now.
00271   return InVal;
00272 }
00273 
00274 
00275 //===----------------------------------------------------------------------===//
00276 //                        CallInst Implementation
00277 //===----------------------------------------------------------------------===//
00278 
00279 CallInst::~CallInst() {
00280 }
00281 
00282 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
00283   assert(NumOperands == NumParams+1 && "NumOperands not set up?");
00284   Use *OL = OperandList;
00285   OL[0] = Func;
00286 
00287   const FunctionType *FTy =
00288     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00289   FTy = FTy;  // silence warning.
00290 
00291   assert((NumParams == FTy->getNumParams() ||
00292           (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
00293          "Calling a function with bad signature!");
00294   for (unsigned i = 0; i != NumParams; ++i) {
00295     assert((i >= FTy->getNumParams() || 
00296             FTy->getParamType(i) == Params[i]->getType()) &&
00297            "Calling a function with a bad signature!");
00298     OL[i+1] = Params[i];
00299   }
00300 }
00301 
00302 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
00303   assert(NumOperands == 3 && "NumOperands not set up?");
00304   Use *OL = OperandList;
00305   OL[0] = Func;
00306   OL[1] = Actual1;
00307   OL[2] = Actual2;
00308 
00309   const FunctionType *FTy =
00310     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00311   FTy = FTy;  // silence warning.
00312 
00313   assert((FTy->getNumParams() == 2 ||
00314           (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
00315          "Calling a function with bad signature");
00316   assert((0 >= FTy->getNumParams() || 
00317           FTy->getParamType(0) == Actual1->getType()) &&
00318          "Calling a function with a bad signature!");
00319   assert((1 >= FTy->getNumParams() || 
00320           FTy->getParamType(1) == Actual2->getType()) &&
00321          "Calling a function with a bad signature!");
00322 }
00323 
00324 void CallInst::init(Value *Func, Value *Actual) {
00325   assert(NumOperands == 2 && "NumOperands not set up?");
00326   Use *OL = OperandList;
00327   OL[0] = Func;
00328   OL[1] = Actual;
00329 
00330   const FunctionType *FTy =
00331     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00332   FTy = FTy;  // silence warning.
00333 
00334   assert((FTy->getNumParams() == 1 ||
00335           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
00336          "Calling a function with bad signature");
00337   assert((0 == FTy->getNumParams() || 
00338           FTy->getParamType(0) == Actual->getType()) &&
00339          "Calling a function with a bad signature!");
00340 }
00341 
00342 void CallInst::init(Value *Func) {
00343   assert(NumOperands == 1 && "NumOperands not set up?");
00344   Use *OL = OperandList;
00345   OL[0] = Func;
00346 
00347   const FunctionType *FTy =
00348     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00349   FTy = FTy;  // silence warning.
00350 
00351   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
00352 }
00353 
00354 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
00355                    Instruction *InsertBefore)
00356   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00357                                    ->getElementType())->getReturnType(),
00358                 Instruction::Call,
00359                 OperandTraits<CallInst>::op_end(this) - 2,
00360                 2, InsertBefore) {
00361   init(Func, Actual);
00362   setName(Name);
00363 }
00364 
00365 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
00366                    BasicBlock  *InsertAtEnd)
00367   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00368                                    ->getElementType())->getReturnType(),
00369                 Instruction::Call,
00370                 OperandTraits<CallInst>::op_end(this) - 2,
00371                 2, InsertAtEnd) {
00372   init(Func, Actual);
00373   setName(Name);
00374 }
00375 CallInst::CallInst(Value *Func, const Twine &Name,
00376                    Instruction *InsertBefore)
00377   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00378                                    ->getElementType())->getReturnType(),
00379                 Instruction::Call,
00380                 OperandTraits<CallInst>::op_end(this) - 1,
00381                 1, InsertBefore) {
00382   init(Func);
00383   setName(Name);
00384 }
00385 
00386 CallInst::CallInst(Value *Func, const Twine &Name,
00387                    BasicBlock *InsertAtEnd)
00388   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00389                                    ->getElementType())->getReturnType(),
00390                 Instruction::Call,
00391                 OperandTraits<CallInst>::op_end(this) - 1,
00392                 1, InsertAtEnd) {
00393   init(Func);
00394   setName(Name);
00395 }
00396 
00397 CallInst::CallInst(const CallInst &CI)
00398   : Instruction(CI.getType(), Instruction::Call,
00399                 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
00400                 CI.getNumOperands()) {
00401   setAttributes(CI.getAttributes());
00402   SubclassData = CI.SubclassData;
00403   Use *OL = OperandList;
00404   Use *InOL = CI.OperandList;
00405   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
00406     OL[i] = InOL[i];
00407   SubclassOptionalData = CI.SubclassOptionalData;
00408 }
00409 
00410 void CallInst::addAttribute(unsigned i, Attributes attr) {
00411   AttrListPtr PAL = getAttributes();
00412   PAL = PAL.addAttr(i, attr);
00413   setAttributes(PAL);
00414 }
00415 
00416 void CallInst::removeAttribute(unsigned i, Attributes attr) {
00417   AttrListPtr PAL = getAttributes();
00418   PAL = PAL.removeAttr(i, attr);
00419   setAttributes(PAL);
00420 }
00421 
00422 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
00423   if (AttributeList.paramHasAttr(i, attr))
00424     return true;
00425   if (const Function *F = getCalledFunction())
00426     return F->paramHasAttr(i, attr);
00427   return false;
00428 }
00429 
00430 
00431 //===----------------------------------------------------------------------===//
00432 //                        InvokeInst Implementation
00433 //===----------------------------------------------------------------------===//
00434 
00435 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
00436                       Value* const *Args, unsigned NumArgs) {
00437   assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
00438   Use *OL = OperandList;
00439   OL[0] = Fn;
00440   OL[1] = IfNormal;
00441   OL[2] = IfException;
00442   const FunctionType *FTy =
00443     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
00444   FTy = FTy;  // silence warning.
00445 
00446   assert(((NumArgs == FTy->getNumParams()) ||
00447           (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
00448          "Calling a function with bad signature");
00449 
00450   for (unsigned i = 0, e = NumArgs; i != e; i++) {
00451     assert((i >= FTy->getNumParams() || 
00452             FTy->getParamType(i) == Args[i]->getType()) &&
00453            "Invoking a function with a bad signature!");
00454     
00455     OL[i+3] = Args[i];
00456   }
00457 }
00458 
00459 InvokeInst::InvokeInst(const InvokeInst &II)
00460   : TerminatorInst(II.getType(), Instruction::Invoke,
00461                    OperandTraits<InvokeInst>::op_end(this)
00462                    - II.getNumOperands(),
00463                    II.getNumOperands()) {
00464   setAttributes(II.getAttributes());
00465   SubclassData = II.SubclassData;
00466   Use *OL = OperandList, *InOL = II.OperandList;
00467   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
00468     OL[i] = InOL[i];
00469   SubclassOptionalData = II.SubclassOptionalData;
00470 }
00471 
00472 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
00473   return getSuccessor(idx);
00474 }
00475 unsigned InvokeInst::getNumSuccessorsV() const {
00476   return getNumSuccessors();
00477 }
00478 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
00479   return setSuccessor(idx, B);
00480 }
00481 
00482 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
00483   if (AttributeList.paramHasAttr(i, attr))
00484     return true;
00485   if (const Function *F = getCalledFunction())
00486     return F->paramHasAttr(i, attr);
00487   return false;
00488 }
00489 
00490 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
00491   AttrListPtr PAL = getAttributes();
00492   PAL = PAL.addAttr(i, attr);
00493   setAttributes(PAL);
00494 }
00495 
00496 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
00497   AttrListPtr PAL = getAttributes();
00498   PAL = PAL.removeAttr(i, attr);
00499   setAttributes(PAL);
00500 }
00501 
00502 
00503 //===----------------------------------------------------------------------===//
00504 //                        ReturnInst Implementation
00505 //===----------------------------------------------------------------------===//
00506 
00507 ReturnInst::ReturnInst(const ReturnInst &RI)
00508   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
00509                    OperandTraits<ReturnInst>::op_end(this) -
00510                      RI.getNumOperands(),
00511                    RI.getNumOperands()) {
00512   if (RI.getNumOperands())
00513     Op<0>() = RI.Op<0>();
00514   SubclassOptionalData = RI.SubclassOptionalData;
00515 }
00516 
00517 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
00518   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
00519                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
00520                    InsertBefore) {
00521   if (retVal)
00522     Op<0>() = retVal;
00523 }
00524 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
00525   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
00526                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
00527                    InsertAtEnd) {
00528   if (retVal)
00529     Op<0>() = retVal;
00530 }
00531 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
00532   : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
00533                    OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
00534 }
00535 
00536 unsigned ReturnInst::getNumSuccessorsV() const {
00537   return getNumSuccessors();
00538 }
00539 
00540 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
00541 /// emit the vtable for the class in this translation unit.
00542 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00543   llvm_unreachable("ReturnInst has no successors!");
00544 }
00545 
00546 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
00547   llvm_unreachable("ReturnInst has no successors!");
00548   return 0;
00549 }
00550 
00551 ReturnInst::~ReturnInst() {
00552 }
00553 
00554 //===----------------------------------------------------------------------===//
00555 //                        UnwindInst Implementation
00556 //===----------------------------------------------------------------------===//
00557 
00558 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
00559   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
00560                    0, 0, InsertBefore) {
00561 }
00562 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
00563   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
00564                    0, 0, InsertAtEnd) {
00565 }
00566 
00567 
00568 unsigned UnwindInst::getNumSuccessorsV() const {
00569   return getNumSuccessors();
00570 }
00571 
00572 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00573   llvm_unreachable("UnwindInst has no successors!");
00574 }
00575 
00576 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
00577   llvm_unreachable("UnwindInst has no successors!");
00578   return 0;
00579 }
00580 
00581 //===----------------------------------------------------------------------===//
00582 //                      UnreachableInst Implementation
00583 //===----------------------------------------------------------------------===//
00584 
00585 UnreachableInst::UnreachableInst(LLVMContext &Context, 
00586                                  Instruction *InsertBefore)
00587   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
00588                    0, 0, InsertBefore) {
00589 }
00590 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
00591   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
00592                    0, 0, InsertAtEnd) {
00593 }
00594 
00595 unsigned UnreachableInst::getNumSuccessorsV() const {
00596   return getNumSuccessors();
00597 }
00598 
00599 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00600   llvm_unreachable("UnwindInst has no successors!");
00601 }
00602 
00603 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
00604   llvm_unreachable("UnwindInst has no successors!");
00605   return 0;
00606 }
00607 
00608 //===----------------------------------------------------------------------===//
00609 //                        BranchInst Implementation
00610 //===----------------------------------------------------------------------===//
00611 
00612 void BranchInst::AssertOK() {
00613   if (isConditional())
00614     assert(getCondition()->getType() == Type::getInt1Ty(getContext()) &&
00615            "May only branch on boolean predicates!");
00616 }
00617 
00618 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
00619   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
00620                    OperandTraits<BranchInst>::op_end(this) - 1,
00621                    1, InsertBefore) {
00622   assert(IfTrue != 0 && "Branch destination may not be null!");
00623   Op<-1>() = IfTrue;
00624 }
00625 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
00626                        Instruction *InsertBefore)
00627   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
00628                    OperandTraits<BranchInst>::op_end(this) - 3,
00629                    3, InsertBefore) {
00630   Op<-1>() = IfTrue;
00631   Op<-2>() = IfFalse;
00632   Op<-3>() = Cond;
00633 #ifndef NDEBUG
00634   AssertOK();
00635 #endif
00636 }
00637 
00638 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
00639   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
00640                    OperandTraits<BranchInst>::op_end(this) - 1,
00641                    1, InsertAtEnd) {
00642   assert(IfTrue != 0 && "Branch destination may not be null!");
00643   Op<-1>() = IfTrue;
00644 }
00645 
00646 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
00647            BasicBlock *InsertAtEnd)
00648   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
00649                    OperandTraits<BranchInst>::op_end(this) - 3,
00650                    3, InsertAtEnd) {
00651   Op<-1>() = IfTrue;
00652   Op<-2>() = IfFalse;
00653   Op<-3>() = Cond;
00654 #ifndef NDEBUG
00655   AssertOK();
00656 #endif
00657 }
00658 
00659 
00660 BranchInst::BranchInst(const BranchInst &BI) :
00661   TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
00662                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
00663                  BI.getNumOperands()) {
00664   Op<-1>() = BI.Op<-1>();
00665   if (BI.getNumOperands() != 1) {
00666     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
00667     Op<-3>() = BI.Op<-3>();
00668     Op<-2>() = BI.Op<-2>();
00669   }
00670   SubclassOptionalData = BI.SubclassOptionalData;
00671 }
00672 
00673 
00674 Use* Use::getPrefix() {
00675   PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
00676   if (PotentialPrefix.getOpaqueValue())
00677     return 0;
00678 
00679   return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
00680 }
00681 
00682 BranchInst::~BranchInst() {
00683   if (NumOperands == 1) {
00684     if (Use *Prefix = OperandList->getPrefix()) {
00685       Op<-1>() = 0;
00686       //
00687       // mark OperandList to have a special value for scrutiny
00688       // by baseclass destructors and operator delete
00689       OperandList = Prefix;
00690     } else {
00691       NumOperands = 3;
00692       OperandList = op_begin();
00693     }
00694   }
00695 }
00696 
00697 
00698 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
00699   return getSuccessor(idx);
00700 }
00701 unsigned BranchInst::getNumSuccessorsV() const {
00702   return getNumSuccessors();
00703 }
00704 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
00705   setSuccessor(idx, B);
00706 }
00707 
00708 
00709 //===----------------------------------------------------------------------===//
00710 //                        AllocationInst Implementation
00711 //===----------------------------------------------------------------------===//
00712 
00713 static Value *getAISize(LLVMContext &Context, Value *Amt) {
00714   if (!Amt)
00715     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
00716   else {
00717     assert(!isa<BasicBlock>(Amt) &&
00718            "Passed basic block into allocation size parameter! Use other ctor");
00719     assert(Amt->getType() == Type::getInt32Ty(Context) &&
00720            "Malloc/Allocation array size is not a 32-bit integer!");
00721   }
00722   return Amt;
00723 }
00724 
00725 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
00726                                unsigned Align, const Twine &Name,
00727                                Instruction *InsertBefore)
00728   : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
00729                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
00730   setAlignment(Align);
00731   assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
00732   setName(Name);
00733 }
00734 
00735 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
00736                                unsigned Align, const Twine &Name,
00737                                BasicBlock *InsertAtEnd)
00738   : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
00739                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
00740   setAlignment(Align);
00741   assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
00742   setName(Name);
00743 }
00744 
00745 // Out of line virtual method, so the vtable, etc has a home.
00746 AllocationInst::~AllocationInst() {
00747 }
00748 
00749 void AllocationInst::setAlignment(unsigned Align) {
00750   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00751   SubclassData = Log2_32(Align) + 1;
00752   assert(getAlignment() == Align && "Alignment representation error!");
00753 }
00754 
00755 bool AllocationInst::isArrayAllocation() const {
00756   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
00757     return CI->getZExtValue() != 1;
00758   return true;
00759 }
00760 
00761 const Type *AllocationInst::getAllocatedType() const {
00762   return getType()->getElementType();
00763 }
00764 
00765 /// isStaticAlloca - Return true if this alloca is in the entry block of the
00766 /// function and is a constant size.  If so, the code generator will fold it
00767 /// into the prolog/epilog code, so it is basically free.
00768 bool AllocaInst::isStaticAlloca() const {
00769   // Must be constant size.
00770   if (!isa<ConstantInt>(getArraySize())) return false;
00771   
00772   // Must be in the entry block.
00773   const BasicBlock *Parent = getParent();
00774   return Parent == &Parent->getParent()->front();
00775 }
00776 
00777 //===----------------------------------------------------------------------===//
00778 //                             FreeInst Implementation
00779 //===----------------------------------------------------------------------===//
00780 
00781 void FreeInst::AssertOK() {
00782   assert(isa<PointerType>(getOperand(0)->getType()) &&
00783          "Can not free something of nonpointer type!");
00784 }
00785 
00786 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
00787   : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
00788                      Free, Ptr, InsertBefore) {
00789   AssertOK();
00790 }
00791 
00792 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
00793   : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
00794                      Free, Ptr, InsertAtEnd) {
00795   AssertOK();
00796 }
00797 
00798 
00799 //===----------------------------------------------------------------------===//
00800 //                           LoadInst Implementation
00801 //===----------------------------------------------------------------------===//
00802 
00803 void LoadInst::AssertOK() {
00804   assert(isa<PointerType>(getOperand(0)->getType()) &&
00805          "Ptr must have pointer type.");
00806 }
00807 
00808 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
00809   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00810                      Load, Ptr, InsertBef) {
00811   setVolatile(false);
00812   setAlignment(0);
00813   AssertOK();
00814   setName(Name);
00815 }
00816 
00817 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
00818   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00819                      Load, Ptr, InsertAE) {
00820   setVolatile(false);
00821   setAlignment(0);
00822   AssertOK();
00823   setName(Name);
00824 }
00825 
00826 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
00827                    Instruction *InsertBef)
00828   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00829                      Load, Ptr, InsertBef) {
00830   setVolatile(isVolatile);
00831   setAlignment(0);
00832   AssertOK();
00833   setName(Name);
00834 }
00835 
00836 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
00837                    unsigned Align, Instruction *InsertBef)
00838   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00839                      Load, Ptr, InsertBef) {
00840   setVolatile(isVolatile);
00841   setAlignment(Align);
00842   AssertOK();
00843   setName(Name);
00844 }
00845 
00846 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
00847                    unsigned Align, BasicBlock *InsertAE)
00848   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00849                      Load, Ptr, InsertAE) {
00850   setVolatile(isVolatile);
00851   setAlignment(Align);
00852   AssertOK();
00853   setName(Name);
00854 }
00855 
00856 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
00857                    BasicBlock *InsertAE)
00858   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00859                      Load, Ptr, InsertAE) {
00860   setVolatile(isVolatile);
00861   setAlignment(0);
00862   AssertOK();
00863   setName(Name);
00864 }
00865 
00866 
00867 
00868 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
00869   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00870                      Load, Ptr, InsertBef) {
00871   setVolatile(false);
00872   setAlignment(0);
00873   AssertOK();
00874   if (Name && Name[0]) setName(Name);
00875 }
00876 
00877 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
00878   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00879                      Load, Ptr, InsertAE) {
00880   setVolatile(false);
00881   setAlignment(0);
00882   AssertOK();
00883   if (Name && Name[0]) setName(Name);
00884 }
00885 
00886 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
00887                    Instruction *InsertBef)
00888 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00889                    Load, Ptr, InsertBef) {
00890   setVolatile(isVolatile);
00891   setAlignment(0);
00892   AssertOK();
00893   if (Name && Name[0]) setName(Name);
00894 }
00895 
00896 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
00897                    BasicBlock *InsertAE)
00898   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00899                      Load, Ptr, InsertAE) {
00900   setVolatile(isVolatile);
00901   setAlignment(0);
00902   AssertOK();
00903   if (Name && Name[0]) setName(Name);
00904 }
00905 
00906 void LoadInst::setAlignment(unsigned Align) {
00907   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00908   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
00909 }
00910 
00911 //===----------------------------------------------------------------------===//
00912 //                           StoreInst Implementation
00913 //===----------------------------------------------------------------------===//
00914 
00915 void StoreInst::AssertOK() {
00916   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
00917   assert(isa<PointerType>(getOperand(1)->getType()) &&
00918          "Ptr must have pointer type!");
00919   assert(getOperand(0)->getType() ==
00920                  cast<PointerType>(getOperand(1)->getType())->getElementType()
00921          && "Ptr must be a pointer to Val type!");
00922 }
00923 
00924 
00925 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
00926   : Instruction(Type::getVoidTy(val->getContext()), Store,
00927                 OperandTraits<StoreInst>::op_begin(this),
00928                 OperandTraits<StoreInst>::operands(this),
00929                 InsertBefore) {
00930   Op<0>() = val;
00931   Op<1>() = addr;
00932   setVolatile(false);
00933   setAlignment(0);
00934   AssertOK();
00935 }
00936 
00937 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
00938   : Instruction(Type::getVoidTy(val->getContext()), Store,
00939                 OperandTraits<StoreInst>::op_begin(this),
00940                 OperandTraits<StoreInst>::operands(this),
00941                 InsertAtEnd) {
00942   Op<0>() = val;
00943   Op<1>() = addr;
00944   setVolatile(false);
00945   setAlignment(0);
00946   AssertOK();
00947 }
00948 
00949 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00950                      Instruction *InsertBefore)
00951   : Instruction(Type::getVoidTy(val->getContext()), Store,
00952                 OperandTraits<StoreInst>::op_begin(this),
00953                 OperandTraits<StoreInst>::operands(this),
00954                 InsertBefore) {
00955   Op<0>() = val;
00956   Op<1>() = addr;
00957   setVolatile(isVolatile);
00958   setAlignment(0);
00959   AssertOK();
00960 }
00961 
00962 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00963                      unsigned Align, Instruction *InsertBefore)
00964   : Instruction(Type::getVoidTy(val->getContext()), Store,
00965                 OperandTraits<StoreInst>::op_begin(this),
00966                 OperandTraits<StoreInst>::operands(this),
00967                 InsertBefore) {
00968   Op<0>() = val;
00969   Op<1>() = addr;
00970   setVolatile(isVolatile);
00971   setAlignment(Align);
00972   AssertOK();
00973 }
00974 
00975 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00976                      unsigned Align, BasicBlock *InsertAtEnd)
00977   : Instruction(Type::getVoidTy(val->getContext()), Store,
00978                 OperandTraits<StoreInst>::op_begin(this),
00979                 OperandTraits<StoreInst>::operands(this),
00980                 InsertAtEnd) {
00981   Op<0>() = val;
00982   Op<1>() = addr;
00983   setVolatile(isVolatile);
00984   setAlignment(Align);
00985   AssertOK();
00986 }
00987 
00988 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00989                      BasicBlock *InsertAtEnd)
00990   : Instruction(Type::getVoidTy(val->getContext()), Store,
00991                 OperandTraits<StoreInst>::op_begin(this),
00992                 OperandTraits<StoreInst>::operands(this),
00993                 InsertAtEnd) {
00994   Op<0>() = val;
00995   Op<1>() = addr;
00996   setVolatile(isVolatile);
00997   setAlignment(0);
00998   AssertOK();
00999 }
01000 
01001 void StoreInst::setAlignment(unsigned Align) {
01002   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
01003   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
01004 }
01005 
01006 //===----------------------------------------------------------------------===//
01007 //                       GetElementPtrInst Implementation
01008 //===----------------------------------------------------------------------===//
01009 
01010 static unsigned retrieveAddrSpace(const Value *Val) {
01011   return cast<PointerType>(Val->getType())->getAddressSpace();
01012 }
01013 
01014 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
01015                              const Twine &Name) {
01016   assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
01017   Use *OL = OperandList;
01018   OL[0] = Ptr;
01019 
01020   for (unsigned i = 0; i != NumIdx; ++i)
01021     OL[i+1] = Idx[i];
01022 
01023   setName(Name);
01024 }
01025 
01026 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
01027   assert(NumOperands == 2 && "NumOperands not initialized?");
01028   Use *OL = OperandList;
01029   OL[0] = Ptr;
01030   OL[1] = Idx;
01031 
01032   setName(Name);
01033 }
01034 
01035 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
01036   : Instruction(GEPI.getType(), GetElementPtr,
01037                 OperandTraits<GetElementPtrInst>::op_end(this)
01038                 - GEPI.getNumOperands(),
01039                 GEPI.getNumOperands()) {
01040   Use *OL = OperandList;
01041   Use *GEPIOL = GEPI.OperandList;
01042   for (unsigned i = 0, E = NumOperands; i != E; ++i)
01043     OL[i] = GEPIOL[i];
01044   SubclassOptionalData = GEPI.SubclassOptionalData;
01045 }
01046 
01047 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
01048                                      const Twine &Name, Instruction *InBe)
01049   : Instruction(PointerType::get(
01050       checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
01051                 GetElementPtr,
01052                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
01053                 2, InBe) {
01054   init(Ptr, Idx, Name);
01055 }
01056 
01057 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
01058                                      const Twine &Name, BasicBlock *IAE)
01059   : Instruction(PointerType::get(
01060             checkType(getIndexedType(Ptr->getType(),Idx)),  
01061                 retrieveAddrSpace(Ptr)),
01062                 GetElementPtr,
01063                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
01064                 2, IAE) {
01065   init(Ptr, Idx, Name);
01066 }
01067 
01068 /// getIndexedType - Returns the type of the element that would be accessed with
01069 /// a gep instruction with the specified parameters.
01070 ///
01071 /// The Idxs pointer should point to a continuous piece of memory containing the
01072 /// indices, either as Value* or uint64_t.
01073 ///
01074 /// A null type is returned if the indices are invalid for the specified
01075 /// pointer type.
01076 ///
01077 template <typename IndexTy>
01078 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
01079                                           unsigned NumIdx) {
01080   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
01081   if (!PTy) return 0;   // Type isn't a pointer type!
01082   const Type *Agg = PTy->getElementType();
01083 
01084   // Handle the special case of the empty set index set, which is always valid.
01085   if (NumIdx == 0)
01086     return Agg;
01087   
01088   // If there is at least one index, the top level type must be sized, otherwise
01089   // it cannot be 'stepped over'.  We explicitly allow abstract types (those
01090   // that contain opaque types) under the assumption that it will be resolved to
01091   // a sane type later.
01092   if (!Agg->isSized() && !Agg->isAbstract())
01093     return 0;
01094 
01095   unsigned CurIdx = 1;
01096   for (; CurIdx != NumIdx; ++CurIdx) {
01097     const CompositeType *CT = dyn_cast<CompositeType>(Agg);
01098     if (!CT || isa<PointerType>(CT)) return 0;
01099     IndexTy Index = Idxs[CurIdx];
01100     if (!CT->indexValid(Index)) return 0;
01101     Agg = CT->getTypeAtIndex(Index);
01102 
01103     // If the new type forwards to another type, then it is in the middle
01104     // of being refined to another type (and hence, may have dropped all
01105     // references to what it was using before).  So, use the new forwarded
01106     // type.
01107     if (const Type *Ty = Agg->getForwardedType())
01108       Agg = Ty;
01109   }
01110   return CurIdx == NumIdx ? Agg : 0;
01111 }
01112 
01113 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
01114                                               Value* const *Idxs,
01115                                               unsigned NumIdx) {
01116   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
01117 }
01118 
01119 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
01120                                               uint64_t const *Idxs,
01121                                               unsigned NumIdx) {
01122   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
01123 }
01124 
01125 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
01126   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
01127   if (!PTy) return 0;   // Type isn't a pointer type!
01128 
01129   // Check the pointer index.
01130   if (!PTy->indexValid(Idx)) return 0;
01131 
01132   return PTy->getElementType();
01133 }
01134 
01135 
01136 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
01137 /// zeros.  If so, the result pointer and the first operand have the same
01138 /// value, just potentially different types.
01139 bool GetElementPtrInst::hasAllZeroIndices() const {
01140   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01141     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
01142       if (!CI->isZero()) return false;
01143     } else {
01144       return false;
01145     }
01146   }
01147   return true;
01148 }
01149 
01150 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
01151 /// constant integers.  If so, the result pointer and the first operand have
01152 /// a constant offset between them.
01153 bool GetElementPtrInst::hasAllConstantIndices() const {
01154   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01155     if (!isa<ConstantInt>(getOperand(i)))
01156       return false;
01157   }
01158   return true;
01159 }
01160 
01161 
01162 //===----------------------------------------------------------------------===//
01163 //                           ExtractElementInst Implementation
01164 //===----------------------------------------------------------------------===//
01165 
01166 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
01167                                        const Twine &Name,
01168                                        Instruction *InsertBef)
01169   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01170                 ExtractElement,
01171                 OperandTraits<ExtractElementInst>::op_begin(this),
01172                 2, InsertBef) {
01173   assert(isValidOperands(Val, Index) &&
01174          "Invalid extractelement instruction operands!");
01175   Op<0>() = Val;
01176   Op<1>() = Index;
01177   setName(Name);
01178 }
01179 
01180 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
01181                                        const Twine &Name,
01182                                        BasicBlock *InsertAE)
01183   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01184                 ExtractElement,
01185                 OperandTraits<ExtractElementInst>::op_begin(this),
01186                 2, InsertAE) {
01187   assert(isValidOperands(Val, Index) &&
01188          "Invalid extractelement instruction operands!");
01189 
01190   Op<0>() = Val;
01191   Op<1>() = Index;
01192   setName(Name);
01193 }
01194 
01195 
01196 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
01197   if (!isa<VectorType>(Val->getType()) ||
01198       Index->getType() != Type::getInt32Ty(Val->getContext()))
01199     return false;
01200   return true;
01201 }
01202 
01203 
01204 //===----------------------------------------------------------------------===//
01205 //                           InsertElementInst Implementation
01206 //===----------------------------------------------------------------------===//
01207 
01208 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
01209                                      const Twine &Name,
01210                                      Instruction *InsertBef)
01211   : Instruction(Vec->getType(), InsertElement,
01212                 OperandTraits<InsertElementInst>::op_begin(this),
01213                 3, InsertBef) {
01214   assert(isValidOperands(Vec, Elt, Index) &&
01215          "Invalid insertelement instruction operands!");
01216   Op<0>() = Vec;
01217   Op<1>() = Elt;
01218   Op<2>() = Index;
01219   setName(Name);
01220 }
01221 
01222 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
01223                                      const Twine &Name,
01224                                      BasicBlock *InsertAE)
01225   : Instruction(Vec->getType(), InsertElement,
01226                 OperandTraits<InsertElementInst>::op_begin(this),
01227                 3, InsertAE) {
01228   assert(isValidOperands(Vec, Elt, Index) &&
01229          "Invalid insertelement instruction operands!");
01230 
01231   Op<0>() = Vec;
01232   Op<1>() = Elt;
01233   Op<2>() = Index;
01234   setName(Name);
01235 }
01236 
01237 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
01238                                         const Value *Index) {
01239   if (!isa<VectorType>(Vec->getType()))
01240     return false;   // First operand of insertelement must be vector type.
01241   
01242   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
01243     return false;// Second operand of insertelement must be vector element type.
01244     
01245   if (Index->getType() != Type::getInt32Ty(Vec->getContext()))
01246     return false;  // Third operand of insertelement must be i32.
01247   return true;
01248 }
01249 
01250 
01251 //===----------------------------------------------------------------------===//
01252 //                      ShuffleVectorInst Implementation
01253 //===----------------------------------------------------------------------===//
01254 
01255 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
01256                                      const Twine &Name,
01257                                      Instruction *InsertBefore)
01258 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
01259                 cast<VectorType>(Mask->getType())->getNumElements()),
01260               ShuffleVector,
01261               OperandTraits<ShuffleVectorInst>::op_begin(this),
01262               OperandTraits<ShuffleVectorInst>::operands(this),
01263               InsertBefore) {
01264   assert(isValidOperands(V1, V2, Mask) &&
01265          "Invalid shuffle vector instruction operands!");
01266   Op<0>() = V1;
01267   Op<1>() = V2;
01268   Op<2>() = Mask;
01269   setName(Name);
01270 }
01271 
01272 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
01273                                      const Twine &Name,
01274                                      BasicBlock *InsertAtEnd)
01275   : Instruction(V1->getType(), ShuffleVector,
01276                 OperandTraits<ShuffleVectorInst>::op_begin(this),
01277                 OperandTraits<ShuffleVectorInst>::operands(this),
01278                 InsertAtEnd) {
01279   assert(isValidOperands(V1, V2, Mask) &&
01280          "Invalid shuffle vector instruction operands!");
01281 
01282   Op<0>() = V1;
01283   Op<1>() = V2;
01284   Op<2>() = Mask;
01285   setName(Name);
01286 }
01287 
01288 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
01289                                         const Value *Mask) {
01290   if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
01291     return false;
01292   
01293   const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
01294   if (!isa<Constant>(Mask) || MaskTy == 0 ||
01295       MaskTy->getElementType() != Type::getInt32Ty(V1->getContext()))
01296     return false;
01297   return true;
01298 }
01299 
01300 /// getMaskValue - Return the index from the shuffle mask for the specified
01301 /// output result.  This is either -1 if the element is undef or a number less
01302 /// than 2*numelements.
01303 int ShuffleVectorInst::getMaskValue(unsigned i) const {
01304   const Constant *Mask = cast<Constant>(getOperand(2));
01305   if (isa<UndefValue>(Mask)) return -1;
01306   if (isa<ConstantAggregateZero>(Mask)) return 0;
01307   const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
01308   assert(i < MaskCV->getNumOperands() && "Index out of range");
01309 
01310   if (isa<UndefValue>(MaskCV->getOperand(i)))
01311     return -1;
01312   return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
01313 }
01314 
01315 //===----------------------------------------------------------------------===//
01316 //                             InsertValueInst Class
01317 //===----------------------------------------------------------------------===//
01318 
01319 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx, 
01320                            unsigned NumIdx, const Twine &Name) {
01321   assert(NumOperands == 2 && "NumOperands not initialized?");
01322   Op<0>() = Agg;
01323   Op<1>() = Val;
01324 
01325   Indices.insert(Indices.end(), Idx, Idx + NumIdx);
01326   setName(Name);
01327 }
01328 
01329 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx, 
01330                            const Twine &Name) {
01331   assert(NumOperands == 2 && "NumOperands not initialized?");
01332   Op<0>() = Agg;
01333   Op<1>() = Val;
01334 
01335   Indices.push_back(Idx);
01336   setName(Name);
01337 }
01338 
01339 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
01340   : Instruction(IVI.getType(), InsertValue,
01341                 OperandTraits<InsertValueInst>::op_begin(this), 2),
01342     Indices(IVI.Indices) {
01343   Op<0>() = IVI.getOperand(0);
01344   Op<1>() = IVI.getOperand(1);
01345   SubclassOptionalData = IVI.SubclassOptionalData;
01346 }
01347 
01348 InsertValueInst::InsertValueInst(Value *Agg,
01349                                  Value *Val,
01350                                  unsigned Idx, 
01351                                  const Twine &Name,
01352                                  Instruction *InsertBefore)
01353   : Instruction(Agg->getType(), InsertValue,
01354                 OperandTraits<InsertValueInst>::op_begin(this),
01355                 2, InsertBefore) {
01356   init(Agg, Val, Idx, Name);
01357 }
01358 
01359 InsertValueInst::InsertValueInst(Value *Agg,
01360                                  Value *Val,
01361                                  unsigned Idx, 
01362                                  const Twine &Name,
01363                                  BasicBlock *InsertAtEnd)
01364   : Instruction(Agg->getType(), InsertValue,
01365                 OperandTraits<InsertValueInst>::op_begin(this),
01366                 2, InsertAtEnd) {
01367   init(Agg, Val, Idx, Name);
01368 }
01369 
01370 //===----------------------------------------------------------------------===//
01371 //                             ExtractValueInst Class
01372 //===----------------------------------------------------------------------===//
01373 
01374 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
01375                             const Twine &Name) {
01376   assert(NumOperands == 1 && "NumOperands not initialized?");
01377 
01378   Indices.insert(Indices.end(), Idx, Idx + NumIdx);
01379   setName(Name);
01380 }
01381 
01382 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
01383   assert(NumOperands == 1 && "NumOperands not initialized?");
01384 
01385   Indices.push_back(Idx);
01386   setName(Name);
01387 }
01388 
01389 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
01390   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
01391     Indices(EVI.Indices) {
01392   SubclassOptionalData = EVI.SubclassOptionalData;
01393 }
01394 
01395 // getIndexedType - Returns the type of the element that would be extracted
01396 // with an extractvalue instruction with the specified parameters.
01397 //
01398 // A null type is returned if the indices are invalid for the specified
01399 // pointer type.
01400 //
01401 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
01402                                              const unsigned *Idxs,
01403                                              unsigned NumIdx) {
01404   unsigned CurIdx = 0;
01405   for (; CurIdx != NumIdx; ++CurIdx) {
01406     const CompositeType *CT = dyn_cast<CompositeType>(Agg);
01407     if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
01408     unsigned Index = Idxs[CurIdx];
01409     if (!CT->indexValid(Index)) return 0;
01410     Agg = CT->getTypeAtIndex(Index);
01411 
01412     // If the new type forwards to another type, then it is in the middle
01413     // of being refined to another type (and hence, may have dropped all
01414     // references to what it was using before).  So, use the new forwarded
01415     // type.
01416     if (const Type *Ty = Agg->getForwardedType())
01417       Agg = Ty;
01418   }
01419   return CurIdx == NumIdx ? Agg : 0;
01420 }
01421 
01422 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
01423                                              unsigned Idx) {
01424   return getIndexedType(Agg, &Idx, 1);
01425 }
01426 
01427 //===----------------------------------------------------------------------===//
01428 //                             BinaryOperator Class
01429 //===----------------------------------------------------------------------===//
01430 
01431 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
01432 /// type is floating-point, to help provide compatibility with an older API.
01433 ///
01434 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
01435                                              const Type *Ty) {
01436   // API compatibility: Adjust integer opcodes to floating-point opcodes.
01437   if (Ty->isFPOrFPVector()) {
01438     if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
01439     else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
01440     else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
01441   }
01442   return iType;
01443 }
01444 
01445 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
01446                                const Type *Ty, const Twine &Name,
01447                                Instruction *InsertBefore)
01448   : Instruction(Ty, AdjustIType(iType, Ty),
01449                 OperandTraits<BinaryOperator>::op_begin(this),
01450                 OperandTraits<BinaryOperator>::operands(this),
01451                 InsertBefore) {
01452   Op<0>() = S1;
01453   Op<1>() = S2;
01454   init(AdjustIType(iType, Ty));
01455   setName(Name);
01456 }
01457 
01458 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
01459                                const Type *Ty, const Twine &Name,
01460                                BasicBlock *InsertAtEnd)
01461   : Instruction(Ty, AdjustIType(iType, Ty),
01462                 OperandTraits<BinaryOperator>::op_begin(this),
01463                 OperandTraits<BinaryOperator>::operands(this),
01464                 InsertAtEnd) {
01465   Op<0>() = S1;
01466   Op<1>() = S2;
01467   init(AdjustIType(iType, Ty));
01468   setName(Name);
01469 }
01470 
01471 
01472 void BinaryOperator::init(BinaryOps iType) {
01473   Value *LHS = getOperand(0), *RHS = getOperand(1);
01474   LHS = LHS; RHS = RHS; // Silence warnings.
01475   assert(LHS->getType() == RHS->getType() &&
01476          "Binary operator operand types must match!");
01477 #ifndef NDEBUG
01478   switch (iType) {
01479   case Add: case Sub:
01480   case Mul:
01481     assert(getType() == LHS->getType() &&
01482            "Arithmetic operation should return same type as operands!");
01483     assert(getType()->isIntOrIntVector() &&
01484            "Tried to create an integer operation on a non-integer type!");
01485     break;
01486   case FAdd: case FSub:
01487   case FMul:
01488     assert(getType() == LHS->getType() &&
01489            "Arithmetic operation should return same type as operands!");
01490     assert(getType()->isFPOrFPVector() &&
01491            "Tried to create a floating-point operation on a "
01492            "non-floating-point type!");
01493     break;
01494   case UDiv: 
01495   case SDiv: 
01496     assert(getType() == LHS->getType() &&
01497            "Arithmetic operation should return same type as operands!");
01498     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
01499             cast<VectorType>(getType())->getElementType()->isInteger())) &&
01500            "Incorrect operand type (not integer) for S/UDIV");
01501     break;
01502   case FDiv:
01503     assert(getType() == LHS->getType() &&
01504            "Arithmetic operation should return same type as operands!");
01505     assert(getType()->isFPOrFPVector() &&
01506            "Incorrect operand type (not floating point) for FDIV");
01507     break;
01508   case URem: 
01509   case SRem: 
01510     assert(getType() == LHS->getType() &&
01511            "Arithmetic operation should return same type as operands!");
01512     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
01513             cast<VectorType>(getType())->getElementType()->isInteger())) &&
01514            "Incorrect operand type (not integer) for S/UREM");
01515     break;
01516   case FRem:
01517     assert(getType() == LHS->getType() &&
01518            "Arithmetic operation should return same type as operands!");
01519     assert(getType()->isFPOrFPVector() &&
01520            "Incorrect operand type (not floating point) for FREM");
01521     break;
01522   case Shl:
01523   case LShr:
01524   case AShr:
01525     assert(getType() == LHS->getType() &&
01526            "Shift operation should return same type as operands!");
01527     assert((getType()->isInteger() ||
01528             (isa<VectorType>(getType()) && 
01529              cast<VectorType>(getType())->getElementType()->isInteger())) &&
01530            "Tried to create a shift operation on a non-integral type!");
01531     break;
01532   case And: case Or:
01533   case Xor:
01534     assert(getType() == LHS->getType() &&
01535            "Logical operation should return same type as operands!");
01536     assert((getType()->isInteger() ||
01537             (isa<VectorType>(getType()) && 
01538              cast<VectorType>(getType())->getElementType()->isInteger())) &&
01539            "Tried to create a logical operation on a non-integral type!");
01540     break;
01541   default:
01542     break;
01543   }
01544 #endif
01545 }
01546 
01547 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
01548                                        const Twine &Name,
01549                                        Instruction *InsertBefore) {
01550   assert(S1->getType() == S2->getType() &&
01551          "Cannot create binary operator with two operands of differing type!");
01552   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
01553 }
01554 
01555 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
01556                                        const Twine &Name,
01557                                        BasicBlock *InsertAtEnd) {
01558   BinaryOperator *Res = Create(Op, S1, S2, Name);
01559   InsertAtEnd->getInstList().push_back(Res);
01560   return Res;
01561 }
01562 
01563 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
01564                                           Instruction *InsertBefore) {
01565   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01566   return new BinaryOperator(Instruction::Sub,
01567                             zero, Op,
01568                             Op->getType(), Name, InsertBefore);
01569 }
01570 
01571 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
01572                                           BasicBlock *InsertAtEnd) {
01573   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01574   return new BinaryOperator(Instruction::Sub,
01575                             zero, Op,
01576                             Op->getType(), Name, InsertAtEnd);
01577 }
01578 
01579 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
01580                                            Instruction *InsertBefore) {
01581   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01582   return new BinaryOperator(Instruction::FSub,
01583                             zero, Op,
01584                             Op->getType(), Name, InsertBefore);
01585 }
01586 
01587 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
01588                                            BasicBlock *InsertAtEnd) {
01589   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01590   return new BinaryOperator(Instruction::FSub,
01591                             zero, Op,
01592                             Op->getType(), Name, InsertAtEnd);
01593 }
01594 
01595 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
01596                                           Instruction *InsertBefore) {
01597   Constant *C;
01598   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
01599     C = Constant::getAllOnesValue(PTy->getElementType());
01600     C = ConstantVector::get(
01601                               std::vector<Constant*>(PTy->getNumElements(), C));
01602   } else {
01603     C = Constant::getAllOnesValue(Op->getType());
01604   }
01605   
01606   return new BinaryOperator(Instruction::Xor, Op, C,
01607                             Op->getType(), Name, InsertBefore);
01608 }
01609 
01610 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
01611                                           BasicBlock *InsertAtEnd) {
01612   Constant *AllOnes;
01613   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
01614     // Create a vector of all ones values.
01615     Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
01616     AllOnes = ConstantVector::get(
01617                             std::vector<Constant*>(PTy->getNumElements(), Elt));
01618   } else {
01619     AllOnes = Constant::getAllOnesValue(Op->getType());
01620   }
01621   
01622   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
01623                             Op->getType(), Name, InsertAtEnd);
01624 }
01625 
01626 
01627 // isConstantAllOnes - Helper function for several functions below
01628 static inline bool isConstantAllOnes(const Value *V) {
01629   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
01630     return CI->isAllOnesValue();
01631   if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
01632     return CV->isAllOnesValue();
01633   return false;
01634 }
01635 
01636 bool BinaryOperator::isNeg(const Value *V) {
01637   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01638     if (Bop->getOpcode() == Instruction::Sub)
01639       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
01640         return C->isNegativeZeroValue();
01641   return false;
01642 }
01643 
01644 bool BinaryOperator::isFNeg(const Value *V) {
01645   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01646     if (Bop->getOpcode() == Instruction::FSub)
01647       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
01648       return C->isNegativeZeroValue();
01649   return false;
01650 }
01651 
01652 bool BinaryOperator::isNot(const Value *V) {
01653   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01654     return (Bop->getOpcode() == Instruction::Xor &&
01655             (isConstantAllOnes(Bop->getOperand(1)) ||
01656              isConstantAllOnes(Bop->getOperand(0))));
01657   return false;
01658 }
01659 
01660 Value *BinaryOperator::getNegArgument(Value *BinOp) {
01661   return cast<BinaryOperator>(BinOp)->getOperand(1);
01662 }
01663 
01664 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
01665   return getNegArgument(const_cast<Value*>(BinOp));
01666 }
01667 
01668 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
01669   return cast<BinaryOperator>(BinOp)->getOperand(1);
01670 }
01671 
01672 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
01673   return getFNegArgument(const_cast<Value*>(BinOp));
01674 }
01675 
01676 Value *BinaryOperator::getNotArgument(Value *BinOp) {
01677   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
01678   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
01679   Value *Op0 = BO->getOperand(0);
01680   Value *Op1 = BO->getOperand(1);
01681   if (isConstantAllOnes(Op0)) return Op1;
01682 
01683   assert(isConstantAllOnes(Op1));
01684   return Op0;
01685 }
01686 
01687 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
01688   return getNotArgument(const_cast<Value*>(BinOp));
01689 }
01690 
01691 
01692 // swapOperands - Exchange the two operands to this instruction.  This
01693 // instruction is safe to use on any binary instruction and does not
01694 // modify the semantics of the instruction.  If the instruction is
01695 // order dependent (SetLT f.e.) the opcode is changed.
01696 //
01697 bool BinaryOperator::swapOperands() {
01698   if (!isCommutative())
01699     return true; // Can't commute operands
01700   Op<0>().swap(Op<1>());
01701   return false;
01702 }
01703 
01704 //===----------------------------------------------------------------------===//
01705 //                                CastInst Class
01706 //===----------------------------------------------------------------------===//
01707 
01708 // Just determine if this cast only deals with integral->integral conversion.
01709 bool CastInst::isIntegerCast() const {
01710   switch (getOpcode()) {
01711     default: return false;
01712     case Instruction::ZExt:
01713     case Instruction::SExt:
01714     case Instruction::Trunc:
01715       return true;
01716     case Instruction::BitCast:
01717       return getOperand(0)->getType()->isInteger() && getType()->isInteger();
01718   }
01719 }
01720 
01721 bool CastInst::isLosslessCast() const {
01722   // Only BitCast can be lossless, exit fast if we're not BitCast
01723   if (getOpcode() != Instruction::BitCast)
01724     return false;
01725 
01726   // Identity cast is always lossless
01727   const Type* SrcTy = getOperand(0)->getType();
01728   const Type* DstTy = getType();
01729   if (SrcTy == DstTy)
01730     return true;
01731   
01732   // Pointer to pointer is always lossless.
01733   if (isa<PointerType>(SrcTy))
01734     return isa<PointerType>(DstTy);
01735   return false;  // Other types have no identity values
01736 }
01737 
01738 /// This function determines if the CastInst does not require any bits to be
01739 /// changed in order to effect the cast. Essentially, it identifies cases where
01740 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
01741 /// example, the following are all no-op casts:
01742 /// # bitcast i32* %x to i8*
01743 /// # bitcast <2 x i32> %x to <4 x i16> 
01744 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
01745 /// @brief Determine if a cast is a no-op.
01746 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
01747   switch (getOpcode()) {
01748     default:
01749       assert(!"Invalid CastOp");
01750     case Instruction::Trunc:
01751     case Instruction::ZExt:
01752     case Instruction::SExt: 
01753     case Instruction::FPTrunc:
01754     case Instruction::FPExt:
01755     case Instruction::UIToFP:
01756     case Instruction::SIToFP:
01757     case Instruction::FPToUI:
01758     case Instruction::FPToSI:
01759       return false; // These always modify bits
01760     case Instruction::BitCast:
01761       return true;  // BitCast never modifies bits.
01762     case Instruction::PtrToInt:
01763       return IntPtrTy->getScalarSizeInBits() ==
01764              getType()->getScalarSizeInBits();
01765     case Instruction::IntToPtr:
01766       return IntPtrTy->getScalarSizeInBits() ==
01767              getOperand(0)->getType()->getScalarSizeInBits();
01768   }
01769 }
01770 
01771 /// This function determines if a pair of casts can be eliminated and what 
01772 /// opcode should be used in the elimination. This assumes that there are two 
01773 /// instructions like this:
01774 /// *  %F = firstOpcode SrcTy %x to MidTy
01775 /// *  %S = secondOpcode MidTy %F to DstTy
01776 /// The function returns a resultOpcode so these two casts can be replaced with:
01777 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
01778 /// If no such cast is permited, the function returns 0.
01779 unsigned CastInst::isEliminableCastPair(
01780   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
01781   const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
01782 {
01783   // Define the 144 possibilities for these two cast instructions. The values
01784   // in this matrix determine what to do in a given situation and select the
01785   // case in the switch below.  The rows correspond to firstOp, the columns 
01786   // correspond to secondOp.  In looking at the table below, keep in  mind
01787   // the following cast properties:
01788   //
01789   //          Size Compare       Source               Destination
01790   // Operator  Src ? Size   Type       Sign         Type       Sign
01791   // -------- ------------ -------------------   ---------------------
01792   // TRUNC         >       Integer      Any        Integral     Any
01793   // ZEXT          <       Integral   Unsigned     Integer      Any
01794   // SEXT          <       Integral    Signed      Integer      Any
01795   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
01796   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
01797   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
01798   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
01799   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
01800   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
01801   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
01802   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
01803   // BITCONVERT    =       FirstClass   n/a       FirstClass    n/a   
01804   //
01805   // NOTE: some transforms are safe, but we consider them to be non-profitable.
01806   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
01807   // into "fptoui double to i64", but this loses information about the range
01808   // of the produced value (we no longer know the top-part is all zeros). 
01809   // Further this conversion is often much more expensive for typical hardware,
01810   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
01811   // same reason.
01812   const unsigned numCastOps = 
01813     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
01814   static const uint8_t CastResults[numCastOps][numCastOps] = {
01815     // T        F  F  U  S  F  F  P  I  B   -+
01816     // R  Z  S  P  P  I  I  T  P  2  N  T    |
01817     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
01818     // N  X  X  U  S  F  F  N  X  N  2  V    |
01819     // C  T  T  I  I  P  P  C  T  T  P  T   -+
01820     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
01821     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
01822     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
01823     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
01824     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
01825     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
01826     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
01827     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
01828     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
01829     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
01830     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
01831     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
01832   };
01833 
01834   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
01835                             [secondOp-Instruction::CastOpsBegin];
01836   switch (ElimCase) {
01837     case 0: 
01838       // categorically disallowed
01839       return 0;
01840     case 1: 
01841       // allowed, use first cast's opcode
01842       return firstOp;
01843     case 2: 
01844       // allowed, use second cast's opcode
01845       return secondOp;
01846     case 3: 
01847       // no-op cast in second op implies firstOp as long as the DestTy 
01848       // is integer
01849       if (DstTy->isInteger())
01850         return firstOp;
01851       return 0;
01852     case 4:
01853       // no-op cast in second op implies firstOp as long as the DestTy
01854       // is floating point
01855       if (DstTy->isFloatingPoint())
01856         return firstOp;
01857       return 0;
01858     case 5: 
01859       // no-op cast in first op implies secondOp as long as the SrcTy
01860       // is an integer
01861       if (SrcTy->isInteger())
01862         return secondOp;
01863       return 0;
01864     case 6:
01865       // no-op cast in first op implies secondOp as long as the SrcTy
01866       // is a floating point
01867       if (SrcTy->isFloatingPoint())
01868         return secondOp;
01869       return 0;
01870     case 7: { 
01871       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
01872       if (!IntPtrTy)
01873         return 0;
01874       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
01875       unsigned MidSize = MidTy->getScalarSizeInBits();
01876       if (MidSize >= PtrSize)
01877         return Instruction::BitCast;
01878       return 0;
01879     }
01880     case 8: {
01881       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
01882       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
01883       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
01884       unsigned SrcSize = SrcTy->getScalarSizeInBits();
01885       unsigned DstSize = DstTy->getScalarSizeInBits();
01886       if (SrcSize == DstSize)
01887         return Instruction::BitCast;
01888       else if (SrcSize < DstSize)
01889         return firstOp;
01890       return secondOp;
01891     }
01892     case 9: // zext, sext -> zext, because sext can't sign extend after zext
01893       return Instruction::ZExt;
01894     case 10:
01895       // fpext followed by ftrunc is allowed if the bit size returned to is
01896       // the same as the original, in which case its just a bitcast
01897       if (SrcTy == DstTy)
01898         return Instruction::BitCast;
01899       return 0; // If the types are not the same we can't eliminate it.
01900     case 11:
01901       // bitcast followed by ptrtoint is allowed as long as the bitcast
01902       // is a pointer to pointer cast.
01903       if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
01904         return secondOp;
01905       return 0;
01906     case 12:
01907       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
01908       if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
01909         return firstOp;
01910       return 0;
01911     case 13: {
01912       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
01913       if (!IntPtrTy)
01914         return 0;
01915       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
01916       unsigned SrcSize = SrcTy->getScalarSizeInBits();
01917       unsigned DstSize = DstTy->getScalarSizeInBits();
01918       if (SrcSize <= PtrSize && SrcSize == DstSize)
01919         return Instruction::BitCast;
01920       return 0;
01921     }
01922     case 99: 
01923       // cast combination can't happen (error in input). This is for all cases
01924       // where the MidTy is not the same for the two cast instructions.
01925       assert(!"Invalid Cast Combination");
01926       return 0;
01927     default:
01928       assert(!"Error in CastResults table!!!");
01929       return 0;
01930   }
01931   return 0;
01932 }
01933 
01934 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty, 
01935   const Twine &Name, Instruction *InsertBefore) {
01936   // Construct and return the appropriate CastInst subclass
01937   switch (op) {
01938     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
01939     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
01940     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
01941     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
01942     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
01943     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
01944     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
01945     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
01946     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
01947     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
01948     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
01949     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
01950     default:
01951       assert(!"Invalid opcode provided");
01952   }
01953   return 0;
01954 }
01955 
01956 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
01957   const Twine &Name, BasicBlock *InsertAtEnd) {
01958   // Construct and return the appropriate CastInst subclass
01959   switch (op) {
01960     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
01961     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
01962     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
01963     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
01964     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
01965     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
01966     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
01967     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
01968     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
01969     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
01970     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
01971     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
01972     default:
01973       assert(!"Invalid opcode provided");
01974   }
01975   return 0;
01976 }
01977 
01978 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 
01979                                         const Twine &Name,
01980                                         Instruction *InsertBefore) {
01981   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01982     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
01983   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
01984 }
01985 
01986 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 
01987                                         const Twine &Name,
01988                                         BasicBlock *InsertAtEnd) {
01989   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01990     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
01991   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
01992 }
01993 
01994 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 
01995                                         const Twine &Name,
01996                                         Instruction *InsertBefore) {
01997   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01998     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
01999   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
02000 }
02001 
02002 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 
02003                                         const Twine &Name,
02004                                         BasicBlock *InsertAtEnd) {
02005   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02006     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02007   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
02008 }
02009 
02010 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
02011                                          const Twine &Name,
02012                                          Instruction *InsertBefore) {
02013   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02014     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02015   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
02016 }
02017 
02018 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
02019                                          const Twine &Name, 
02020                                          BasicBlock *InsertAtEnd) {
02021   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02022     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02023   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
02024 }
02025 
02026 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
02027                                       const Twine &Name,
02028                                       BasicBlock *InsertAtEnd) {
02029   assert(isa<PointerType>(S->getType()) && "Invalid cast");
02030   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
02031          "Invalid cast");
02032 
02033   if (Ty->isInteger())
02034     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
02035   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02036 }
02037 
02038 /// @brief Create a BitCast or a PtrToInt cast instruction
02039 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty, 
02040                                       const Twine &Name, 
02041                                       Instruction *InsertBefore) {
02042   assert(isa<PointerType>(S->getType()) && "Invalid cast");
02043   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
02044          "Invalid cast");
02045 
02046   if (Ty->isInteger())
02047     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
02048   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02049 }
02050 
02051 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 
02052                                       bool isSigned, const Twine &Name,
02053                                       Instruction *InsertBefore) {
02054   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
02055   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02056   unsigned DstBits = Ty->getScalarSizeInBits();
02057   Instruction::CastOps opcode =
02058     (SrcBits == DstBits ? Instruction::BitCast :
02059      (SrcBits > DstBits ? Instruction::Trunc :
02060       (isSigned ? Instruction::SExt : Instruction::ZExt)));
02061   return Create(opcode, C, Ty, Name, InsertBefore);
02062 }
02063 
02064 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 
02065                                       bool isSigned, const Twine &Name,
02066                                       BasicBlock *InsertAtEnd) {
02067   assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
02068          "Invalid cast");
02069   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02070   unsigned DstBits = Ty->getScalarSizeInBits();
02071   Instruction::CastOps opcode =
02072     (SrcBits == DstBits ? Instruction::BitCast :
02073      (SrcBits > DstBits ? Instruction::Trunc :
02074       (isSigned ? Instruction::SExt : Instruction::ZExt)));
02075   return Create(opcode, C, Ty, Name, InsertAtEnd);
02076 }
02077 
02078 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 
02079                                  const Twine &Name, 
02080                                  Instruction *InsertBefore) {
02081   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
02082          "Invalid cast");
02083   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02084   unsigned DstBits = Ty->getScalarSizeInBits();
02085   Instruction::CastOps opcode =
02086     (SrcBits == DstBits ? Instruction::BitCast :
02087      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
02088   return Create(opcode, C, Ty, Name, InsertBefore);
02089 }
02090 
02091 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 
02092                                  const Twine &Name, 
02093                                  BasicBlock *InsertAtEnd) {
02094   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
02095          "Invalid cast");
02096   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02097   unsigned DstBits = Ty->getScalarSizeInBits();
02098   Instruction::CastOps opcode =
02099     (SrcBits == DstBits ? Instruction::BitCast :
02100      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
02101   return Create(opcode, C, Ty, Name, InsertAtEnd);
02102 }
02103 
02104 // Check whether it is valid to call getCastOpcode for these types.
02105 // This routine must be kept in sync with getCastOpcode.
02106 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
02107   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
02108     return false;
02109 
02110   if (SrcTy == DestTy)
02111     return true;
02112 
02113   // Get the bit sizes, we'll need these
02114   unsigned SrcBits = SrcTy->getScalarSizeInBits();   // 0 for ptr
02115   unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
02116 
02117   // Run through the possibilities ...
02118   if (DestTy->isInteger()) {                   // Casting to integral
02119     if (SrcTy->isInteger()) {                  // Casting from integral
02120         return true;
02121     } else if (SrcTy->isFloatingPoint()) {     // Casting from floating pt
02122       return true;
02123     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
02124                                                // Casting from vector
02125       return DestBits == PTy->getBitWidth();
02126     } else {                                   // Casting from something else
02127       return isa<PointerType>(SrcTy);
02128     }
02129   } else if (DestTy->isFloatingPoint()) {      // Casting to floating pt
02130     if (SrcTy->isInteger()) {                  // Casting from integral
02131       return true;
02132     } else if (SrcTy->isFloatingPoint()) {     // Casting from floating pt
02133       return true;
02134     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
02135                                                // Casting from vector
02136       return DestBits == PTy->getBitWidth();
02137     } else {                                   // Casting from something else
02138       return false;
02139     }
02140   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
02141                                                 // Casting to vector
02142     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
02143                                                 // Casting from vector
02144       return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
02145     } else {                                    // Casting from something else
02146       return DestPTy->getBitWidth() == SrcBits;
02147     }
02148   } else if (isa<PointerType>(DestTy)) {        // Casting to pointer
02149     if (isa<PointerType>(SrcTy)) {              // Casting from pointer
02150       return true;
02151     } else if (SrcTy->isInteger()) {            // Casting from integral
02152       return true;
02153     } else {                                    // Casting from something else
02154       return false;
02155     }
02156   } else {                                      // Casting to something else
02157     return false;
02158   }
02159 }
02160 
02161 // Provide a way to get a "cast" where the cast opcode is inferred from the 
02162 // types and size of the operand. This, basically, is a parallel of the 
02163 // logic in the castIsValid function below.  This axiom should hold:
02164 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
02165 // should not assert in castIsValid. In other words, this produces a "correct"
02166 // casting opcode for the arguments passed to it.
02167 // This routine must be kept in sync with isCastable.
02168 Instruction::CastOps
02169 CastInst::getCastOpcode(
02170   const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
02171   // Get the bit sizes, we'll need these
02172   const Type *SrcTy = Src->getType();
02173   unsigned SrcBits = SrcTy->getScalarSizeInBits();   // 0 for ptr
02174   unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
02175 
02176   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
02177          "Only first class types are castable!");
02178 
02179   // Run through the possibilities ...
02180   if (DestTy->isInteger()) {                       // Casting to integral
02181     if (SrcTy->isInteger()) {                      // Casting from integral
02182       if (DestBits < SrcBits)
02183         return Trunc;                               // int -> smaller int
02184       else if (DestBits > SrcBits) {                // its an extension
02185         if (SrcIsSigned)
02186           return SExt;                              // signed -> SEXT
02187         else
02188           return ZExt;                              // unsigned -> ZEXT
02189       } else {
02190         return BitCast;                             // Same size, No-op cast
02191       }
02192     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
02193       if (DestIsSigned) 
02194         return FPToSI;                              // FP -> sint
02195       else
02196         return FPToUI;                              // FP -> uint 
02197     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
02198       assert(DestBits == PTy->getBitWidth() &&
02199                "Casting vector to integer of different width");
02200       PTy = NULL;
02201       return BitCast;                             // Same size, no-op cast
02202     } else {
02203       assert(isa<PointerType>(SrcTy) &&
02204              "Casting from a value that is not first-class type");
02205       return PtrToInt;                              // ptr -> int
02206     }
02207   } else if (DestTy->isFloatingPoint()) {           // Casting to floating pt
02208     if (SrcTy->isInteger()) {                      // Casting from integral
02209       if (SrcIsSigned)
02210         return SIToFP;                              // sint -> FP
02211       else
02212         return UIToFP;                              // uint -> FP
02213     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
02214       if (DestBits < SrcBits) {
02215         return FPTrunc;                             // FP -> smaller FP
02216       } else if (DestBits > SrcBits) {
02217         return FPExt;                               // FP -> larger FP
02218       } else  {
02219         return BitCast;                             // same size, no-op cast
02220       }
02221     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
02222       assert(DestBits == PTy->getBitWidth() &&
02223              "Casting vector to floating point of different width");
02224       PTy = NULL;
02225       return BitCast;                             // same size, no-op cast
02226     } else {
02227       llvm_unreachable("Casting pointer or non-first class to float");
02228     }
02229   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
02230     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
02231       assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
02232              "Casting vector to vector of different widths");
02233       SrcPTy = NULL;
02234       return BitCast;                             // vector -> vector
02235     } else if (DestPTy->getBitWidth() == SrcBits) {
02236       return BitCast;                               // float/int -> vector
02237     } else {
02238       assert(!"Illegal cast to vector (wrong type or size)");
02239     }
02240   } else if (isa<PointerType>(DestTy)) {
02241     if (isa<PointerType>(SrcTy)) {
02242       return BitCast;                               // ptr -> ptr
02243     } else if (SrcTy->isInteger()) {
02244       return IntToPtr;                              // int -> ptr
02245     } else {
02246       assert(!"Casting pointer to other than pointer or int");
02247     }
02248   } else {
02249     assert(!"Casting to type that is not first-class");
02250   }
02251 
02252   // If we fall through to here we probably hit an assertion cast above
02253   // and assertions are not turned on. Anything we return is an error, so
02254   // BitCast is as good a choice as any.
02255   return BitCast;
02256 }
02257 
02258 //===----------------------------------------------------------------------===//
02259 //                    CastInst SubClass Constructors
02260 //===----------------------------------------------------------------------===//
02261 
02262 /// Check that the construction parameters for a CastInst are correct. This
02263 /// could be broken out into the separate constructors but it is useful to have
02264 /// it in one place and to eliminate the redundant code for getting the sizes
02265 /// of the types involved.
02266 bool 
02267 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
02268 
02269   // Check for type sanity on the arguments
02270   const Type *SrcTy = S->getType();
02271   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
02272     return false;
02273 
02274   // Get the size of the types in bits, we'll need this later
02275   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
02276   unsigned DstBitSize = DstTy->getScalarSizeInBits();
02277 
02278   // Switch on the opcode provided
02279   switch (op) {
02280   default: return false; // This is an input error
02281   case Instruction::Trunc:
02282     return SrcTy->isIntOrIntVector() &&
02283            DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
02284   case Instruction::ZExt:
02285     return SrcTy->isIntOrIntVector() &&
02286            DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
02287   case Instruction::SExt: 
02288     return SrcTy->isIntOrIntVector() &&
02289            DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
02290   case Instruction::FPTrunc:
02291     return SrcTy->isFPOrFPVector() &&
02292            DstTy->isFPOrFPVector() && 
02293            SrcBitSize > DstBitSize;
02294   case Instruction::FPExt:
02295     return SrcTy->isFPOrFPVector() &&
02296            DstTy->isFPOrFPVector() && 
02297            SrcBitSize < DstBitSize;
02298   case Instruction::UIToFP:
02299   case Instruction::SIToFP:
02300     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
02301       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
02302         return SVTy->getElementType()->isIntOrIntVector() &&
02303                DVTy->getElementType()->isFPOrFPVector() &&
02304                SVTy->getNumElements() == DVTy->getNumElements();
02305       }
02306     }
02307     return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
02308   case Instruction::FPToUI:
02309   case Instruction::FPToSI:
02310     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
02311       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
02312         return SVTy->getElementType()->isFPOrFPVector() &&
02313                DVTy->getElementType()->isIntOrIntVector() &&
02314                SVTy->getNumElements() == DVTy->getNumElements();
02315       }
02316     }
02317     return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
02318   case Instruction::PtrToInt:
02319     return isa<PointerType>(SrcTy) && DstTy->isInteger();
02320   case Instruction::IntToPtr:
02321     return SrcTy->isInteger() && isa<PointerType>(DstTy);
02322   case Instruction::BitCast:
02323     // BitCast implies a no-op cast of type only. No bits change.
02324     // However, you can't cast pointers to anything but pointers.
02325     if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
02326       return false;
02327 
02328     // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
02329     // these cases, the cast is okay if the source and destination bit widths
02330     // are identical.
02331     return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
02332   }
02333 }
02334 
02335 TruncInst::TruncInst(
02336   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02337 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
02338   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
02339 }
02340 
02341 TruncInst::TruncInst(
02342   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02343 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
02344   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
02345 }
02346 
02347 ZExtInst::ZExtInst(
02348   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02349 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
02350   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
02351 }
02352 
02353 ZExtInst::ZExtInst(
02354   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02355 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
02356   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
02357 }
02358 SExtInst::SExtInst(
02359   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02360 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
02361   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
02362 }
02363 
02364 SExtInst::SExtInst(
02365   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02366 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
02367   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
02368 }
02369 
02370 FPTruncInst::FPTruncInst(
02371   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02372 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
02373   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
02374 }
02375 
02376 FPTruncInst::FPTruncInst(
02377   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02378 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
02379   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
02380 }
02381 
02382 FPExtInst::FPExtInst(
02383   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02384 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
02385   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
02386 }
02387 
02388 FPExtInst::FPExtInst(
02389   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02390 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
02391   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
02392 }
02393 
02394 UIToFPInst::UIToFPInst(
02395   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02396 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
02397   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
02398 }
02399 
02400 UIToFPInst::UIToFPInst(
02401   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02402 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
02403   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
02404 }
02405 
02406 SIToFPInst::SIToFPInst(
02407   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02408 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
02409   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
02410 }
02411 
02412 SIToFPInst::SIToFPInst(
02413   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02414 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
02415   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
02416 }
02417 
02418 FPToUIInst::FPToUIInst(
02419   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02420 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
02421   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
02422 }
02423 
02424 FPToUIInst::FPToUIInst(
02425   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02426 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
02427   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
02428 }
02429 
02430 FPToSIInst::FPToSIInst(
02431   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02432 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
02433   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
02434 }
02435 
02436 FPToSIInst::FPToSIInst(
02437   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02438 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
02439   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
02440 }
02441 
02442 PtrToIntInst::PtrToIntInst(
02443   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02444 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
02445   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
02446 }
02447 
02448 PtrToIntInst::PtrToIntInst(
02449   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02450 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
02451   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
02452 }
02453 
02454 IntToPtrInst::IntToPtrInst(
02455   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02456 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
02457   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
02458 }
02459 
02460 IntToPtrInst::IntToPtrInst(
02461   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02462 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
02463   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
02464 }
02465 
02466 BitCastInst::BitCastInst(
02467   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
02468 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
02469   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
02470 }
02471 
02472 BitCastInst::BitCastInst(
02473   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02474 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
02475   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
02476 }
02477 
02478 //===----------------------------------------------------------------------===//
02479 //                               CmpInst Classes
02480 //===----------------------------------------------------------------------===//
02481 
02482 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
02483                  Value *LHS, Value *RHS, const Twine &Name,
02484                  Instruction *InsertBefore)
02485   : Instruction(ty, op,
02486                 OperandTraits<CmpInst>::op_begin(this),
02487                 OperandTraits<CmpInst>::operands(this),
02488                 InsertBefore) {
02489     Op<0>() = LHS;
02490     Op<1>() = RHS;
02491   SubclassData = predicate;
02492   setName(Name);
02493 }
02494 
02495 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
02496                  Value *LHS, Value *RHS, const Twine &Name,
02497                  BasicBlock *InsertAtEnd)
02498   : Instruction(ty, op,
02499                 OperandTraits<CmpInst>::op_begin(this),
02500                 OperandTraits<CmpInst>::operands(this),
02501                 InsertAtEnd) {
02502   Op<0>() = LHS;
02503   Op<1>() = RHS;
02504   SubclassData = predicate;
02505   setName(Name);
02506 }
02507 
02508 CmpInst *
02509 CmpInst::Create(LLVMContext &Context, OtherOps Op, unsigned short predicate,
02510                 Value *S1, Value *S2, 
02511                 const Twine &Name, Instruction *InsertBefore) {
02512   if (Op == Instruction::ICmp) {
02513     if (InsertBefore)
02514       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
02515                           S1, S2, Name);
02516     else
02517       return new ICmpInst(Context, CmpInst::Predicate(predicate),
02518                           S1, S2, Name);
02519   }
02520   
02521   if (InsertBefore)
02522     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
02523                         S1, S2, Name);
02524   else
02525     return new FCmpInst(Context, CmpInst::Predicate(predicate),
02526                         S1, S2, Name);
02527 }
02528 
02529 CmpInst *
02530 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
02531                 const Twine &Name, BasicBlock *InsertAtEnd) {
02532   if (Op == Instruction::ICmp) {
02533     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
02534                         S1, S2, Name);
02535   }
02536   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
02537                       S1, S2, Name);
02538 }
02539 
02540 void CmpInst::swapOperands() {
02541   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
02542     IC->swapOperands();
02543   else
02544     cast<FCmpInst>(this)->swapOperands();
02545 }
02546 
02547 bool CmpInst::isCommutative() {
02548   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
02549     return IC->isCommutative();
02550   return cast<FCmpInst>(this)->isCommutative();
02551 }
02552 
02553 bool CmpInst::isEquality() {
02554   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
02555     return IC->isEquality();
02556   return cast<FCmpInst>(this)->isEquality();
02557 }
02558 
02559 
02560 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
02561   switch (pred) {
02562     default: assert(!"Unknown cmp predicate!");
02563     case ICMP_EQ: return ICMP_NE;
02564     case ICMP_NE: return ICMP_EQ;
02565     case ICMP_UGT: return ICMP_ULE;
02566     case ICMP_ULT: return ICMP_UGE;
02567     case ICMP_UGE: return ICMP_ULT;
02568     case ICMP_ULE: return ICMP_UGT;
02569     case ICMP_SGT: return ICMP_SLE;
02570     case ICMP_SLT: return ICMP_SGE;
02571     case ICMP_SGE: return ICMP_SLT;
02572     case ICMP_SLE: return ICMP_SGT;
02573 
02574     case FCMP_OEQ: return FCMP_UNE;
02575     case FCMP_ONE: return FCMP_UEQ;
02576     case FCMP_OGT: return FCMP_ULE;
02577     case FCMP_OLT: return FCMP_UGE;
02578     case FCMP_OGE: return FCMP_ULT;
02579     case FCMP_OLE: return FCMP_UGT;
02580     case FCMP_UEQ: return FCMP_ONE;
02581     case FCMP_UNE: return FCMP_OEQ;
02582     case FCMP_UGT: return FCMP_OLE;
02583     case FCMP_ULT: return FCMP_OGE;
02584     case FCMP_UGE: return FCMP_OLT;
02585     case FCMP_ULE: return FCMP_OGT;
02586     case FCMP_ORD: return FCMP_UNO;
02587     case FCMP_UNO: return FCMP_ORD;
02588     case FCMP_TRUE: return FCMP_FALSE;
02589     case FCMP_FALSE: return FCMP_TRUE;
02590   }
02591 }
02592 
02593 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
02594   switch (pred) {
02595     default: assert(! "Unknown icmp predicate!");
02596     case ICMP_EQ: case ICMP_NE: 
02597     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
02598        return pred;
02599     case ICMP_UGT: return ICMP_SGT;
02600     case ICMP_ULT: return ICMP_SLT;
02601     case ICMP_UGE: return ICMP_SGE;
02602     case ICMP_ULE: return ICMP_SLE;
02603   }
02604 }
02605 
02606 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
02607   switch (pred) {
02608     default: assert(! "Unknown icmp predicate!");
02609     case ICMP_EQ: case ICMP_NE: 
02610     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
02611        return pred;
02612     case ICMP_SGT: return ICMP_UGT;
02613     case ICMP_SLT: return ICMP_ULT;
02614     case ICMP_SGE: return ICMP_UGE;
02615     case ICMP_SLE: return ICMP_ULE;
02616   }
02617 }
02618 
02619 bool ICmpInst::isSignedPredicate(Predicate pred) {
02620   switch (pred) {
02621     default: assert(! "Unknown icmp predicate!");
02622     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
02623       return true;
02624     case ICMP_EQ:  case ICMP_NE: case ICMP_UGT: case ICMP_ULT: 
02625     case ICMP_UGE: case ICMP_ULE:
02626       return false;
02627   }
02628 }
02629 
02630 /// Initialize a set of values that all satisfy the condition with C.
02631 ///
02632 ConstantRange 
02633 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
02634   APInt Lower(C);
02635   APInt Upper(C);
02636   uint32_t BitWidth = C.getBitWidth();
02637   switch (pred) {
02638   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
02639   case ICmpInst::ICMP_EQ: Upper++; break;
02640   case ICmpInst::ICMP_NE: Lower++; break;
02641   case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
02642   case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
02643   case ICmpInst::ICMP_UGT: 
02644     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
02645     break;
02646   case ICmpInst::ICMP_SGT:
02647     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
02648     break;
02649   case ICmpInst::ICMP_ULE: 
02650     Lower = APInt::getMinValue(BitWidth); Upper++; 
02651     break;
02652   case ICmpInst::ICMP_SLE: 
02653     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
02654     break;
02655   case ICmpInst::ICMP_UGE:
02656     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
02657     break;
02658   case ICmpInst::ICMP_SGE:
02659     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
02660     break;
02661   }
02662   return ConstantRange(Lower, Upper);
02663 }
02664 
02665 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
02666   switch (pred) {
02667     default: assert(!"Unknown cmp predicate!");
02668     case ICMP_EQ: case ICMP_NE:
02669       return pred;
02670     case ICMP_SGT: return ICMP_SLT;
02671     case ICMP_SLT: return ICMP_SGT;
02672     case ICMP_SGE: return ICMP_SLE;
02673     case ICMP_SLE: return ICMP_SGE;
02674     case ICMP_UGT: return ICMP_ULT;
02675     case ICMP_ULT: return ICMP_UGT;
02676     case ICMP_UGE: return ICMP_ULE;
02677     case ICMP_ULE: return ICMP_UGE;
02678   
02679     case FCMP_FALSE: case FCMP_TRUE:
02680     case FCMP_OEQ: case FCMP_ONE:
02681     case FCMP_UEQ: case FCMP_UNE:
02682     case FCMP_ORD: case FCMP_UNO:
02683       return pred;
02684     case FCMP_OGT: return FCMP_OLT;
02685     case FCMP_OLT: return FCMP_OGT;
02686     case FCMP_OGE: return FCMP_OLE;
02687     case FCMP_OLE: return FCMP_OGE;
02688     case FCMP_UGT: return FCMP_ULT;
02689     case FCMP_ULT: return FCMP_UGT;
02690     case FCMP_UGE: return FCMP_ULE;
02691     case FCMP_ULE: return FCMP_UGE;
02692   }
02693 }
02694 
02695 bool CmpInst::isUnsigned(unsigned short predicate) {
02696   switch (predicate) {
02697     default: return false;
02698     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
02699     case ICmpInst::ICMP_UGE: return true;
02700   }
02701 }
02702 
02703 bool CmpInst::isSigned(unsigned short predicate){
02704   switch (predicate) {
02705     default: return false;
02706     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
02707     case ICmpInst::ICMP_SGE: return true;
02708   }
02709 }
02710 
02711 bool CmpInst::isOrdered(unsigned short predicate) {
02712   switch (predicate) {
02713     default: return false;
02714     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
02715     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
02716     case FCmpInst::FCMP_ORD: return true;
02717   }
02718 }
02719       
02720 bool CmpInst::isUnordered(unsigned short predicate) {
02721   switch (predicate) {
02722     default: return false;
02723     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
02724     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
02725     case FCmpInst::FCMP_UNO: return true;
02726   }
02727 }
02728 
02729 //===----------------------------------------------------------------------===//
02730 //                        SwitchInst Implementation
02731 //===----------------------------------------------------------------------===//
02732 
02733 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
02734   assert(Value && Default);
02735   ReservedSpace = 2+NumCases*2;
02736   NumOperands = 2;
02737   OperandList = allocHungoffUses(ReservedSpace);
02738 
02739   OperandList[0] = Value;
02740   OperandList[1] = Default;
02741 }
02742 
02743 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
02744 /// switch on and a default destination.  The number of additional cases can
02745 /// be specified here to make memory allocation more efficient.  This
02746 /// constructor can also autoinsert before another instruction.
02747 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
02748                        Instruction *InsertBefore)
02749   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
02750                    0, 0, InsertBefore) {
02751   init(Value, Default, NumCases);
02752 }
02753 
02754 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
02755 /// switch on and a default destination.  The number of additional cases can
02756 /// be specified here to make memory allocation more efficient.  This
02757 /// constructor also autoinserts at the end of the specified BasicBlock.
02758 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
02759                        BasicBlock *InsertAtEnd)
02760   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
02761                    0, 0, InsertAtEnd) {
02762   init(Value, Default, NumCases);
02763 }
02764 
02765 SwitchInst::SwitchInst(const SwitchInst &SI)
02766   : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
02767                    allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
02768   Use *OL = OperandList, *InOL = SI.OperandList;
02769   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
02770     OL[i] = InOL[i];
02771     OL[i+1] = InOL[i+1];
02772   }
02773   SubclassOptionalData = SI.SubclassOptionalData;
02774 }
02775 
02776 SwitchInst::~SwitchInst() {
02777   dropHungoffUses(OperandList);
02778 }
02779 
02780 
02781 /// addCase - Add an entry to the switch instruction...
02782 ///
02783 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
02784   unsigned OpNo = NumOperands;
02785   if (OpNo+2 > ReservedSpace)
02786     resizeOperands(0);  // Get more space!
02787   // Initialize some new operands.
02788   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
02789   NumOperands = OpNo+2;
02790   OperandList[OpNo] = OnVal;
02791   OperandList[OpNo+1] = Dest;
02792 }
02793 
02794 /// removeCase - This method removes the specified successor from the switch
02795 /// instruction.  Note that this cannot be used to remove the default
02796 /// destination (successor #0).
02797 ///
02798 void SwitchInst::removeCase(unsigned idx) {
02799   assert(idx != 0 && "Cannot remove the default case!");
02800   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
02801 
02802   unsigned NumOps = getNumOperands();
02803   Use *OL = OperandList;
02804 
02805   // Move everything after this operand down.
02806   //
02807   // FIXME: we could just swap with the end of the list, then erase.  However,
02808   // client might not expect this to happen.  The code as it is thrashes the
02809   // use/def lists, which is kinda lame.
02810   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
02811     OL[i-2] = OL[i];
02812     OL[i-2+1] = OL[i+1];
02813   }
02814 
02815   // Nuke the last value.
02816   OL[NumOps-2].set(0);
02817   OL[NumOps-2+1].set(0);
02818   NumOperands = NumOps-2;
02819 }
02820 
02821 /// resizeOperands - resize operands - This adjusts the length of the operands
02822 /// list according to the following behavior:
02823 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
02824 ///      of operation.  This grows the number of ops by 3 times.
02825 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
02826 ///   3. If NumOps == NumOperands, trim the reserved space.
02827 ///
02828 void SwitchInst::resizeOperands(unsigned NumOps) {
02829   unsigned e = getNumOperands();
02830   if (NumOps == 0) {
02831     NumOps = e*3;
02832   } else if (NumOps*2 > NumOperands) {
02833     // No resize needed.
02834     if (ReservedSpace >= NumOps) return;
02835   } else if (NumOps == NumOperands) {
02836     if (ReservedSpace == NumOps) return;
02837   } else {
02838     return;
02839   }
02840 
02841   ReservedSpace = NumOps;
02842   Use *NewOps = allocHungoffUses(NumOps);
02843   Use *OldOps = OperandList;
02844   for (unsigned i = 0; i != e; ++i) {
02845       NewOps[i] = OldOps[i];
02846   }
02847   OperandList = NewOps;
02848   if (OldOps) Use::zap(OldOps, OldOps + e, true);
02849 }
02850 
02851 
02852 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
02853   return getSuccessor(idx);
02854 }
02855 unsigned SwitchInst::getNumSuccessorsV() const {
02856   return getNumSuccessors();
02857 }
02858 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
02859   setSuccessor(idx, B);
02860 }
02861 
02862 // Define these methods here so vtables don't get emitted into every translation
02863 // unit that uses these classes.
02864 
02865 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
02866   GetElementPtrInst *New = new(getNumOperands()) GetElementPtrInst(*this);
02867   New->SubclassOptionalData = SubclassOptionalData;
02868   return New;
02869 }
02870 
02871 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
02872   BinaryOperator *New = Create(getOpcode(), Op<0>(), Op<1>());
02873   New->SubclassOptionalData = SubclassOptionalData;
02874   return New;
02875 }
02876 
02877 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
02878   FCmpInst *New = new FCmpInst(Context, getPredicate(), Op<0>(), Op<1>());
02879   New->SubclassOptionalData = SubclassOptionalData;
02880   return New;
02881 }
02882 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
02883   ICmpInst *New = new ICmpInst(Context, getPredicate(), Op<0>(), Op<1>());
02884   New->SubclassOptionalData = SubclassOptionalData;
02885   return New;
02886 }
02887 
02888 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
02889   ExtractValueInst *New = new ExtractValueInst(*this);
02890   New->SubclassOptionalData = SubclassOptionalData;
02891   return New;
02892 }
02893 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
02894   InsertValueInst *New = new InsertValueInst(*this);
02895   New->SubclassOptionalData = SubclassOptionalData;
02896   return New;
02897 }
02898 
02899 MallocInst *MallocInst::clone(LLVMContext&) const {
02900   MallocInst *New = new MallocInst(getAllocatedType(),
02901                                    (Value*)getOperand(0),
02902                                    getAlignment());
02903   New->SubclassOptionalData = SubclassOptionalData;
02904   return New;
02905 }
02906 
02907 AllocaInst *AllocaInst::clone(LLVMContext&) const {
02908   AllocaInst *New = new AllocaInst(getAllocatedType(),
02909                                    (Value*)getOperand(0),
02910                                    getAlignment());
02911   New->SubclassOptionalData = SubclassOptionalData;
02912   return New;
02913 }
02914 
02915 FreeInst *FreeInst::clone(LLVMContext&) const {
02916   FreeInst *New = new FreeInst(getOperand(0));
02917   New->SubclassOptionalData = SubclassOptionalData;
02918   return New;
02919 }
02920 
02921 LoadInst *LoadInst::clone(LLVMContext&) const {
02922   LoadInst *New = new LoadInst(getOperand(0),
02923                                Twine(), isVolatile(),
02924                                getAlignment());
02925   New->SubclassOptionalData = SubclassOptionalData;
02926   return New;
02927 }
02928 
02929 StoreInst *StoreInst::clone(LLVMContext&) const {
02930   StoreInst *New = new StoreInst(getOperand(0), getOperand(1),
02931                                  isVolatile(), getAlignment());
02932   New->SubclassOptionalData = SubclassOptionalData;
02933   return New;
02934 }
02935 
02936 CastInst *TruncInst::clone(LLVMContext&) const {
02937   TruncInst *New = new TruncInst(getOperand(0), getType());
02938   New->SubclassOptionalData = SubclassOptionalData;
02939   return New;
02940 }
02941 
02942 CastInst *ZExtInst::clone(LLVMContext&) const {
02943   ZExtInst *New = new ZExtInst(getOperand(0), getType());
02944   New->SubclassOptionalData = SubclassOptionalData;
02945   return New;
02946 }
02947 
02948 CastInst *SExtInst::clone(LLVMContext&) const {
02949   SExtInst *New = new SExtInst(getOperand(0), getType());
02950   New->SubclassOptionalData = SubclassOptionalData;
02951   return New;
02952 }
02953 
02954 CastInst *FPTruncInst::clone(LLVMContext&) const {
02955   FPTruncInst *New = new FPTruncInst(getOperand(0), getType());
02956   New->SubclassOptionalData = SubclassOptionalData;
02957   return New;
02958 }
02959 
02960 CastInst *FPExtInst::clone(LLVMContext&) const {
02961   FPExtInst *New = new FPExtInst(getOperand(0), getType());
02962   New->SubclassOptionalData = SubclassOptionalData;
02963   return New;
02964 }
02965 
02966 CastInst *UIToFPInst::clone(LLVMContext&) const {
02967   UIToFPInst *New = new UIToFPInst(getOperand(0), getType());
02968   New->SubclassOptionalData = SubclassOptionalData;
02969   return New;
02970 }
02971 
02972 CastInst *SIToFPInst::clone(LLVMContext&) const {
02973   SIToFPInst *New = new SIToFPInst(getOperand(0), getType());
02974   New->SubclassOptionalData = SubclassOptionalData;
02975   return New;
02976 }
02977 
02978 CastInst *FPToUIInst::clone(LLVMContext&) const {
02979   FPToUIInst *New = new FPToUIInst(getOperand(0), getType());
02980   New->SubclassOptionalData = SubclassOptionalData;
02981   return New;
02982 }
02983 
02984 CastInst *FPToSIInst::clone(LLVMContext&) const {
02985   FPToSIInst *New = new FPToSIInst(getOperand(0), getType());
02986   New->SubclassOptionalData = SubclassOptionalData;
02987   return New;
02988 }
02989 
02990 CastInst *PtrToIntInst::clone(LLVMContext&) const {
02991   PtrToIntInst *New = new PtrToIntInst(getOperand(0), getType());
02992   New->SubclassOptionalData = SubclassOptionalData;
02993   return New;
02994 }
02995 
02996 CastInst *IntToPtrInst::clone(LLVMContext&) const {
02997   IntToPtrInst *New = new IntToPtrInst(getOperand(0), getType());
02998   New->SubclassOptionalData = SubclassOptionalData;
02999   return New;
03000 }
03001 
03002 CastInst *BitCastInst::clone(LLVMContext&) const {
03003   BitCastInst *New = new BitCastInst(getOperand(0), getType());
03004   New->SubclassOptionalData = SubclassOptionalData;
03005   return New;
03006 }
03007 
03008 CallInst *CallInst::clone(LLVMContext&) const {
03009   CallInst *New = new(getNumOperands()) CallInst(*this);
03010   New->SubclassOptionalData = SubclassOptionalData;
03011   return New;
03012 }
03013 
03014 SelectInst *SelectInst::clone(LLVMContext&) const {
03015   SelectInst *New = SelectInst::Create(getOperand(0),
03016                                        getOperand(1),
03017                                        getOperand(2));
03018   New->SubclassOptionalData = SubclassOptionalData;
03019   return New;
03020 }
03021 
03022 VAArgInst *VAArgInst::clone(LLVMContext&) const {
03023   VAArgInst *New = new VAArgInst(getOperand(0), getType());
03024   New->SubclassOptionalData = SubclassOptionalData;
03025   return New;
03026 }
03027 
03028 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
03029   ExtractElementInst *New = ExtractElementInst::Create(getOperand(0),
03030                                                        getOperand(1));
03031   New->SubclassOptionalData = SubclassOptionalData;
03032   return New;
03033 }
03034 
03035 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
03036   InsertElementInst *New = InsertElementInst::Create(getOperand(0),
03037                                                      getOperand(1),
03038                                                      getOperand(2));
03039   New->SubclassOptionalData = SubclassOptionalData;
03040   return New;
03041 }
03042 
03043 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
03044   ShuffleVectorInst *New = new ShuffleVectorInst(getOperand(0),
03045                                                  getOperand(1),
03046                                                  getOperand(2));
03047   New->SubclassOptionalData = SubclassOptionalData;
03048   return New;
03049 }
03050 
03051 PHINode *PHINode::clone(LLVMContext&) const {
03052   PHINode *New = new PHINode(*this);
03053   New->SubclassOptionalData = SubclassOptionalData;
03054   return New;
03055 }
03056 
03057 ReturnInst *ReturnInst::clone(LLVMContext&) const {
03058   ReturnInst *New = new(getNumOperands()) ReturnInst(*this);
03059   New->SubclassOptionalData = SubclassOptionalData;
03060   return New;
03061 }
03062 
03063 BranchInst *BranchInst::clone(LLVMContext&) const {
03064   unsigned Ops(getNumOperands());
03065   BranchInst *New = new(Ops, Ops == 1) BranchInst(*this);
03066   New->SubclassOptionalData = SubclassOptionalData;
03067   return New;
03068 }
03069 
03070 SwitchInst *SwitchInst::clone(LLVMContext&) const {
03071   SwitchInst *New = new SwitchInst(*this);
03072   New->SubclassOptionalData = SubclassOptionalData;
03073   return New;
03074 }
03075 
03076 InvokeInst *InvokeInst::clone(LLVMContext&) const {
03077   InvokeInst *New = new(getNumOperands()) InvokeInst(*this);
03078   New->SubclassOptionalData = SubclassOptionalData;
03079   return New;
03080 }
03081 
03082 UnwindInst *UnwindInst::clone(LLVMContext &C) const {
03083   UnwindInst *New = new UnwindInst(C);
03084   New->SubclassOptionalData = SubclassOptionalData;
03085   return New;
03086 }
03087 
03088 UnreachableInst *UnreachableInst::clone(LLVMContext &C) const {
03089   UnreachableInst *New = new UnreachableInst(C);
03090   New->SubclassOptionalData = SubclassOptionalData;
03091   return New;
03092 }