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