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/CallSite.h"
00018 #include "llvm/IR/ConstantRange.h"
00019 #include "llvm/IR/Constants.h"
00020 #include "llvm/IR/DataLayout.h"
00021 #include "llvm/IR/DerivedTypes.h"
00022 #include "llvm/IR/Function.h"
00023 #include "llvm/IR/Module.h"
00024 #include "llvm/IR/Operator.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)
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 nullptr;
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(nullptr);
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 nullptr; // 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, nullptr, 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, nullptr, 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(Constant *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   setTailCallKind(CI.getTailCallKind());
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::hasFnAttrImpl(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 = nullptr;
00424   Instruction *Result = nullptr;
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, nullptr, 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(nullptr, 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 = nullptr;
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, nullptr);
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, nullptr, 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::hasFnAttrImpl(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                    nullptr, 0, InsertBefore) {
00703 }
00704 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
00705   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
00706                    nullptr, 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 && "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 && "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(), nullptr), 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(), nullptr), 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((getSubclassDataFromInstruction() & ~31) |
00897                              (Log2_32(Align) + 1));
00898   assert(getAlignment() == Align && "Alignment representation error!");
00899 }
00900 
00901 bool AllocaInst::isArrayAllocation() const {
00902   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
00903     return !CI->isOne();
00904   return true;
00905 }
00906 
00907 Type *AllocaInst::getAllocatedType() const {
00908   return getType()->getElementType();
00909 }
00910 
00911 /// isStaticAlloca - Return true if this alloca is in the entry block of the
00912 /// function and is a constant size.  If so, the code generator will fold it
00913 /// into the prolog/epilog code, so it is basically free.
00914 bool AllocaInst::isStaticAlloca() const {
00915   // Must be constant size.
00916   if (!isa<ConstantInt>(getArraySize())) return false;
00917   
00918   // Must be in the entry block.
00919   const BasicBlock *Parent = getParent();
00920   return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
00921 }
00922 
00923 //===----------------------------------------------------------------------===//
00924 //                           LoadInst Implementation
00925 //===----------------------------------------------------------------------===//
00926 
00927 void LoadInst::AssertOK() {
00928   assert(getOperand(0)->getType()->isPointerTy() &&
00929          "Ptr must have pointer type.");
00930   assert(!(isAtomic() && getAlignment() == 0) &&
00931          "Alignment required for atomic load");
00932 }
00933 
00934 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
00935   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00936                      Load, Ptr, InsertBef) {
00937   setVolatile(false);
00938   setAlignment(0);
00939   setAtomic(NotAtomic);
00940   AssertOK();
00941   setName(Name);
00942 }
00943 
00944 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
00945   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00946                      Load, Ptr, InsertAE) {
00947   setVolatile(false);
00948   setAlignment(0);
00949   setAtomic(NotAtomic);
00950   AssertOK();
00951   setName(Name);
00952 }
00953 
00954 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
00955                    Instruction *InsertBef)
00956   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00957                      Load, Ptr, InsertBef) {
00958   setVolatile(isVolatile);
00959   setAlignment(0);
00960   setAtomic(NotAtomic);
00961   AssertOK();
00962   setName(Name);
00963 }
00964 
00965 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
00966                    BasicBlock *InsertAE)
00967   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00968                      Load, Ptr, InsertAE) {
00969   setVolatile(isVolatile);
00970   setAlignment(0);
00971   setAtomic(NotAtomic);
00972   AssertOK();
00973   setName(Name);
00974 }
00975 
00976 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
00977                    unsigned Align, Instruction *InsertBef)
00978   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00979                      Load, Ptr, InsertBef) {
00980   setVolatile(isVolatile);
00981   setAlignment(Align);
00982   setAtomic(NotAtomic);
00983   AssertOK();
00984   setName(Name);
00985 }
00986 
00987 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
00988                    unsigned Align, BasicBlock *InsertAE)
00989   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00990                      Load, Ptr, InsertAE) {
00991   setVolatile(isVolatile);
00992   setAlignment(Align);
00993   setAtomic(NotAtomic);
00994   AssertOK();
00995   setName(Name);
00996 }
00997 
00998 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
00999                    unsigned Align, AtomicOrdering Order,
01000                    SynchronizationScope SynchScope,
01001                    Instruction *InsertBef)
01002   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01003                      Load, Ptr, InsertBef) {
01004   setVolatile(isVolatile);
01005   setAlignment(Align);
01006   setAtomic(Order, SynchScope);
01007   AssertOK();
01008   setName(Name);
01009 }
01010 
01011 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
01012                    unsigned Align, AtomicOrdering Order,
01013                    SynchronizationScope SynchScope,
01014                    BasicBlock *InsertAE)
01015   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01016                      Load, Ptr, InsertAE) {
01017   setVolatile(isVolatile);
01018   setAlignment(Align);
01019   setAtomic(Order, SynchScope);
01020   AssertOK();
01021   setName(Name);
01022 }
01023 
01024 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
01025   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01026                      Load, Ptr, InsertBef) {
01027   setVolatile(false);
01028   setAlignment(0);
01029   setAtomic(NotAtomic);
01030   AssertOK();
01031   if (Name && Name[0]) setName(Name);
01032 }
01033 
01034 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
01035   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01036                      Load, Ptr, InsertAE) {
01037   setVolatile(false);
01038   setAlignment(0);
01039   setAtomic(NotAtomic);
01040   AssertOK();
01041   if (Name && Name[0]) setName(Name);
01042 }
01043 
01044 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
01045                    Instruction *InsertBef)
01046 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01047                    Load, Ptr, InsertBef) {
01048   setVolatile(isVolatile);
01049   setAlignment(0);
01050   setAtomic(NotAtomic);
01051   AssertOK();
01052   if (Name && Name[0]) setName(Name);
01053 }
01054 
01055 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
01056                    BasicBlock *InsertAE)
01057   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01058                      Load, Ptr, InsertAE) {
01059   setVolatile(isVolatile);
01060   setAlignment(0);
01061   setAtomic(NotAtomic);
01062   AssertOK();
01063   if (Name && Name[0]) setName(Name);
01064 }
01065 
01066 void LoadInst::setAlignment(unsigned Align) {
01067   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
01068   assert(Align <= MaximumAlignment &&
01069          "Alignment is greater than MaximumAlignment!");
01070   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
01071                              ((Log2_32(Align)+1)<<1));
01072   assert(getAlignment() == Align && "Alignment representation error!");
01073 }
01074 
01075 //===----------------------------------------------------------------------===//
01076 //                           StoreInst Implementation
01077 //===----------------------------------------------------------------------===//
01078 
01079 void StoreInst::AssertOK() {
01080   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
01081   assert(getOperand(1)->getType()->isPointerTy() &&
01082          "Ptr must have pointer type!");
01083   assert(getOperand(0)->getType() ==
01084                  cast<PointerType>(getOperand(1)->getType())->getElementType()
01085          && "Ptr must be a pointer to Val type!");
01086   assert(!(isAtomic() && getAlignment() == 0) &&
01087          "Alignment required for atomic store");
01088 }
01089 
01090 
01091 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
01092   : Instruction(Type::getVoidTy(val->getContext()), Store,
01093                 OperandTraits<StoreInst>::op_begin(this),
01094                 OperandTraits<StoreInst>::operands(this),
01095                 InsertBefore) {
01096   Op<0>() = val;
01097   Op<1>() = addr;
01098   setVolatile(false);
01099   setAlignment(0);
01100   setAtomic(NotAtomic);
01101   AssertOK();
01102 }
01103 
01104 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
01105   : Instruction(Type::getVoidTy(val->getContext()), Store,
01106                 OperandTraits<StoreInst>::op_begin(this),
01107                 OperandTraits<StoreInst>::operands(this),
01108                 InsertAtEnd) {
01109   Op<0>() = val;
01110   Op<1>() = addr;
01111   setVolatile(false);
01112   setAlignment(0);
01113   setAtomic(NotAtomic);
01114   AssertOK();
01115 }
01116 
01117 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01118                      Instruction *InsertBefore)
01119   : Instruction(Type::getVoidTy(val->getContext()), Store,
01120                 OperandTraits<StoreInst>::op_begin(this),
01121                 OperandTraits<StoreInst>::operands(this),
01122                 InsertBefore) {
01123   Op<0>() = val;
01124   Op<1>() = addr;
01125   setVolatile(isVolatile);
01126   setAlignment(0);
01127   setAtomic(NotAtomic);
01128   AssertOK();
01129 }
01130 
01131 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01132                      unsigned Align, Instruction *InsertBefore)
01133   : Instruction(Type::getVoidTy(val->getContext()), Store,
01134                 OperandTraits<StoreInst>::op_begin(this),
01135                 OperandTraits<StoreInst>::operands(this),
01136                 InsertBefore) {
01137   Op<0>() = val;
01138   Op<1>() = addr;
01139   setVolatile(isVolatile);
01140   setAlignment(Align);
01141   setAtomic(NotAtomic);
01142   AssertOK();
01143 }
01144 
01145 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01146                      unsigned Align, AtomicOrdering Order,
01147                      SynchronizationScope SynchScope,
01148                      Instruction *InsertBefore)
01149   : Instruction(Type::getVoidTy(val->getContext()), Store,
01150                 OperandTraits<StoreInst>::op_begin(this),
01151                 OperandTraits<StoreInst>::operands(this),
01152                 InsertBefore) {
01153   Op<0>() = val;
01154   Op<1>() = addr;
01155   setVolatile(isVolatile);
01156   setAlignment(Align);
01157   setAtomic(Order, SynchScope);
01158   AssertOK();
01159 }
01160 
01161 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01162                      BasicBlock *InsertAtEnd)
01163   : Instruction(Type::getVoidTy(val->getContext()), Store,
01164                 OperandTraits<StoreInst>::op_begin(this),
01165                 OperandTraits<StoreInst>::operands(this),
01166                 InsertAtEnd) {
01167   Op<0>() = val;
01168   Op<1>() = addr;
01169   setVolatile(isVolatile);
01170   setAlignment(0);
01171   setAtomic(NotAtomic);
01172   AssertOK();
01173 }
01174 
01175 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01176                      unsigned Align, BasicBlock *InsertAtEnd)
01177   : Instruction(Type::getVoidTy(val->getContext()), Store,
01178                 OperandTraits<StoreInst>::op_begin(this),
01179                 OperandTraits<StoreInst>::operands(this),
01180                 InsertAtEnd) {
01181   Op<0>() = val;
01182   Op<1>() = addr;
01183   setVolatile(isVolatile);
01184   setAlignment(Align);
01185   setAtomic(NotAtomic);
01186   AssertOK();
01187 }
01188 
01189 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01190                      unsigned Align, AtomicOrdering Order,
01191                      SynchronizationScope SynchScope,
01192                      BasicBlock *InsertAtEnd)
01193   : Instruction(Type::getVoidTy(val->getContext()), Store,
01194                 OperandTraits<StoreInst>::op_begin(this),
01195                 OperandTraits<StoreInst>::operands(this),
01196                 InsertAtEnd) {
01197   Op<0>() = val;
01198   Op<1>() = addr;
01199   setVolatile(isVolatile);
01200   setAlignment(Align);
01201   setAtomic(Order, SynchScope);
01202   AssertOK();
01203 }
01204 
01205 void StoreInst::setAlignment(unsigned Align) {
01206   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
01207   assert(Align <= MaximumAlignment &&
01208          "Alignment is greater than MaximumAlignment!");
01209   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
01210                              ((Log2_32(Align)+1) << 1));
01211   assert(getAlignment() == Align && "Alignment representation error!");
01212 }
01213 
01214 //===----------------------------------------------------------------------===//
01215 //                       AtomicCmpXchgInst Implementation
01216 //===----------------------------------------------------------------------===//
01217 
01218 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
01219                              AtomicOrdering SuccessOrdering,
01220                              AtomicOrdering FailureOrdering,
01221                              SynchronizationScope SynchScope) {
01222   Op<0>() = Ptr;
01223   Op<1>() = Cmp;
01224   Op<2>() = NewVal;
01225   setSuccessOrdering(SuccessOrdering);
01226   setFailureOrdering(FailureOrdering);
01227   setSynchScope(SynchScope);
01228 
01229   assert(getOperand(0) && getOperand(1) && getOperand(2) &&
01230          "All operands must be non-null!");
01231   assert(getOperand(0)->getType()->isPointerTy() &&
01232          "Ptr must have pointer type!");
01233   assert(getOperand(1)->getType() ==
01234                  cast<PointerType>(getOperand(0)->getType())->getElementType()
01235          && "Ptr must be a pointer to Cmp type!");
01236   assert(getOperand(2)->getType() ==
01237                  cast<PointerType>(getOperand(0)->getType())->getElementType()
01238          && "Ptr must be a pointer to NewVal type!");
01239   assert(SuccessOrdering != NotAtomic &&
01240          "AtomicCmpXchg instructions must be atomic!");
01241   assert(FailureOrdering != NotAtomic &&
01242          "AtomicCmpXchg instructions must be atomic!");
01243   assert(SuccessOrdering >= FailureOrdering &&
01244          "AtomicCmpXchg success ordering must be at least as strong as fail");
01245   assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
01246          "AtomicCmpXchg failure ordering cannot include release semantics");
01247 }
01248 
01249 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
01250                                      AtomicOrdering SuccessOrdering,
01251                                      AtomicOrdering FailureOrdering,
01252                                      SynchronizationScope SynchScope,
01253                                      Instruction *InsertBefore)
01254     : Instruction(
01255           StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
01256                           nullptr),
01257           AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
01258           OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
01259   Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
01260 }
01261 
01262 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
01263                                      AtomicOrdering SuccessOrdering,
01264                                      AtomicOrdering FailureOrdering,
01265                                      SynchronizationScope SynchScope,
01266                                      BasicBlock *InsertAtEnd)
01267     : Instruction(
01268           StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
01269                           nullptr),
01270           AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
01271           OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
01272   Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
01273 }
01274 
01275 //===----------------------------------------------------------------------===//
01276 //                       AtomicRMWInst Implementation
01277 //===----------------------------------------------------------------------===//
01278 
01279 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
01280                          AtomicOrdering Ordering,
01281                          SynchronizationScope SynchScope) {
01282   Op<0>() = Ptr;
01283   Op<1>() = Val;
01284   setOperation(Operation);
01285   setOrdering(Ordering);
01286   setSynchScope(SynchScope);
01287 
01288   assert(getOperand(0) && getOperand(1) &&
01289          "All operands must be non-null!");
01290   assert(getOperand(0)->getType()->isPointerTy() &&
01291          "Ptr must have pointer type!");
01292   assert(getOperand(1)->getType() ==
01293          cast<PointerType>(getOperand(0)->getType())->getElementType()
01294          && "Ptr must be a pointer to Val type!");
01295   assert(Ordering != NotAtomic &&
01296          "AtomicRMW instructions must be atomic!");
01297 }
01298 
01299 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
01300                              AtomicOrdering Ordering,
01301                              SynchronizationScope SynchScope,
01302                              Instruction *InsertBefore)
01303   : Instruction(Val->getType(), AtomicRMW,
01304                 OperandTraits<AtomicRMWInst>::op_begin(this),
01305                 OperandTraits<AtomicRMWInst>::operands(this),
01306                 InsertBefore) {
01307   Init(Operation, Ptr, Val, Ordering, SynchScope);
01308 }
01309 
01310 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
01311                              AtomicOrdering Ordering,
01312                              SynchronizationScope SynchScope,
01313                              BasicBlock *InsertAtEnd)
01314   : Instruction(Val->getType(), AtomicRMW,
01315                 OperandTraits<AtomicRMWInst>::op_begin(this),
01316                 OperandTraits<AtomicRMWInst>::operands(this),
01317                 InsertAtEnd) {
01318   Init(Operation, Ptr, Val, Ordering, SynchScope);
01319 }
01320 
01321 //===----------------------------------------------------------------------===//
01322 //                       FenceInst Implementation
01323 //===----------------------------------------------------------------------===//
01324 
01325 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
01326                      SynchronizationScope SynchScope,
01327                      Instruction *InsertBefore)
01328   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
01329   setOrdering(Ordering);
01330   setSynchScope(SynchScope);
01331 }
01332 
01333 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
01334                      SynchronizationScope SynchScope,
01335                      BasicBlock *InsertAtEnd)
01336   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
01337   setOrdering(Ordering);
01338   setSynchScope(SynchScope);
01339 }
01340 
01341 //===----------------------------------------------------------------------===//
01342 //                       GetElementPtrInst Implementation
01343 //===----------------------------------------------------------------------===//
01344 
01345 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
01346                              const Twine &Name) {
01347   assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
01348   OperandList[0] = Ptr;
01349   std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
01350   setName(Name);
01351 }
01352 
01353 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
01354   : Instruction(GEPI.getType(), GetElementPtr,
01355                 OperandTraits<GetElementPtrInst>::op_end(this)
01356                 - GEPI.getNumOperands(),
01357                 GEPI.getNumOperands()) {
01358   std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
01359   SubclassOptionalData = GEPI.SubclassOptionalData;
01360 }
01361 
01362 /// getIndexedType - Returns the type of the element that would be accessed with
01363 /// a gep instruction with the specified parameters.
01364 ///
01365 /// The Idxs pointer should point to a continuous piece of memory containing the
01366 /// indices, either as Value* or uint64_t.
01367 ///
01368 /// A null type is returned if the indices are invalid for the specified
01369 /// pointer type.
01370 ///
01371 template <typename IndexTy>
01372 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
01373   PointerType *PTy = dyn_cast<PointerType>(Ptr->getScalarType());
01374   if (!PTy) return nullptr;   // Type isn't a pointer type!
01375   Type *Agg = PTy->getElementType();
01376 
01377   // Handle the special case of the empty set index set, which is always valid.
01378   if (IdxList.empty())
01379     return Agg;
01380 
01381   // If there is at least one index, the top level type must be sized, otherwise
01382   // it cannot be 'stepped over'.
01383   if (!Agg->isSized())
01384     return nullptr;
01385 
01386   unsigned CurIdx = 1;
01387   for (; CurIdx != IdxList.size(); ++CurIdx) {
01388     CompositeType *CT = dyn_cast<CompositeType>(Agg);
01389     if (!CT || CT->isPointerTy()) return nullptr;
01390     IndexTy Index = IdxList[CurIdx];
01391     if (!CT->indexValid(Index)) return nullptr;
01392     Agg = CT->getTypeAtIndex(Index);
01393   }
01394   return CurIdx == IdxList.size() ? Agg : nullptr;
01395 }
01396 
01397 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
01398   return getIndexedTypeInternal(Ptr, IdxList);
01399 }
01400 
01401 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
01402                                         ArrayRef<Constant *> IdxList) {
01403   return getIndexedTypeInternal(Ptr, IdxList);
01404 }
01405 
01406 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
01407   return getIndexedTypeInternal(Ptr, IdxList);
01408 }
01409 
01410 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
01411 /// zeros.  If so, the result pointer and the first operand have the same
01412 /// value, just potentially different types.
01413 bool GetElementPtrInst::hasAllZeroIndices() const {
01414   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01415     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
01416       if (!CI->isZero()) return false;
01417     } else {
01418       return false;
01419     }
01420   }
01421   return true;
01422 }
01423 
01424 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
01425 /// constant integers.  If so, the result pointer and the first operand have
01426 /// a constant offset between them.
01427 bool GetElementPtrInst::hasAllConstantIndices() const {
01428   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01429     if (!isa<ConstantInt>(getOperand(i)))
01430       return false;
01431   }
01432   return true;
01433 }
01434 
01435 void GetElementPtrInst::setIsInBounds(bool B) {
01436   cast<GEPOperator>(this)->setIsInBounds(B);
01437 }
01438 
01439 bool GetElementPtrInst::isInBounds() const {
01440   return cast<GEPOperator>(this)->isInBounds();
01441 }
01442 
01443 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
01444                                                  APInt &Offset) const {
01445   // Delegate to the generic GEPOperator implementation.
01446   return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
01447 }
01448 
01449 //===----------------------------------------------------------------------===//
01450 //                           ExtractElementInst Implementation
01451 //===----------------------------------------------------------------------===//
01452 
01453 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
01454                                        const Twine &Name,
01455                                        Instruction *InsertBef)
01456   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01457                 ExtractElement,
01458                 OperandTraits<ExtractElementInst>::op_begin(this),
01459                 2, InsertBef) {
01460   assert(isValidOperands(Val, Index) &&
01461          "Invalid extractelement instruction operands!");
01462   Op<0>() = Val;
01463   Op<1>() = Index;
01464   setName(Name);
01465 }
01466 
01467 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
01468                                        const Twine &Name,
01469                                        BasicBlock *InsertAE)
01470   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01471                 ExtractElement,
01472                 OperandTraits<ExtractElementInst>::op_begin(this),
01473                 2, InsertAE) {
01474   assert(isValidOperands(Val, Index) &&
01475          "Invalid extractelement instruction operands!");
01476 
01477   Op<0>() = Val;
01478   Op<1>() = Index;
01479   setName(Name);
01480 }
01481 
01482 
01483 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
01484   if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
01485     return false;
01486   return true;
01487 }
01488 
01489 
01490 //===----------------------------------------------------------------------===//
01491 //                           InsertElementInst Implementation
01492 //===----------------------------------------------------------------------===//
01493 
01494 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
01495                                      const Twine &Name,
01496                                      Instruction *InsertBef)
01497   : Instruction(Vec->getType(), InsertElement,
01498                 OperandTraits<InsertElementInst>::op_begin(this),
01499                 3, InsertBef) {
01500   assert(isValidOperands(Vec, Elt, Index) &&
01501          "Invalid insertelement instruction operands!");
01502   Op<0>() = Vec;
01503   Op<1>() = Elt;
01504   Op<2>() = Index;
01505   setName(Name);
01506 }
01507 
01508 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
01509                                      const Twine &Name,
01510                                      BasicBlock *InsertAE)
01511   : Instruction(Vec->getType(), InsertElement,
01512                 OperandTraits<InsertElementInst>::op_begin(this),
01513                 3, InsertAE) {
01514   assert(isValidOperands(Vec, Elt, Index) &&
01515          "Invalid insertelement instruction operands!");
01516 
01517   Op<0>() = Vec;
01518   Op<1>() = Elt;
01519   Op<2>() = Index;
01520   setName(Name);
01521 }
01522 
01523 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
01524                                         const Value *Index) {
01525   if (!Vec->getType()->isVectorTy())
01526     return false;   // First operand of insertelement must be vector type.
01527   
01528   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
01529     return false;// Second operand of insertelement must be vector element type.
01530     
01531   if (!Index->getType()->isIntegerTy())
01532     return false;  // Third operand of insertelement must be i32.
01533   return true;
01534 }
01535 
01536 
01537 //===----------------------------------------------------------------------===//
01538 //                      ShuffleVectorInst Implementation
01539 //===----------------------------------------------------------------------===//
01540 
01541 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
01542                                      const Twine &Name,
01543                                      Instruction *InsertBefore)
01544 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
01545                 cast<VectorType>(Mask->getType())->getNumElements()),
01546               ShuffleVector,
01547               OperandTraits<ShuffleVectorInst>::op_begin(this),
01548               OperandTraits<ShuffleVectorInst>::operands(this),
01549               InsertBefore) {
01550   assert(isValidOperands(V1, V2, Mask) &&
01551          "Invalid shuffle vector instruction operands!");
01552   Op<0>() = V1;
01553   Op<1>() = V2;
01554   Op<2>() = Mask;
01555   setName(Name);
01556 }
01557 
01558 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
01559                                      const Twine &Name,
01560                                      BasicBlock *InsertAtEnd)
01561 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
01562                 cast<VectorType>(Mask->getType())->getNumElements()),
01563               ShuffleVector,
01564               OperandTraits<ShuffleVectorInst>::op_begin(this),
01565               OperandTraits<ShuffleVectorInst>::operands(this),
01566               InsertAtEnd) {
01567   assert(isValidOperands(V1, V2, Mask) &&
01568          "Invalid shuffle vector instruction operands!");
01569 
01570   Op<0>() = V1;
01571   Op<1>() = V2;
01572   Op<2>() = Mask;
01573   setName(Name);
01574 }
01575 
01576 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
01577                                         const Value *Mask) {
01578   // V1 and V2 must be vectors of the same type.
01579   if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
01580     return false;
01581   
01582   // Mask must be vector of i32.
01583   VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
01584   if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
01585     return false;
01586 
01587   // Check to see if Mask is valid.
01588   if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
01589     return true;
01590 
01591   if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
01592     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
01593     for (Value *Op : MV->operands()) {
01594       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
01595         if (CI->uge(V1Size*2))
01596           return false;
01597       } else if (!isa<UndefValue>(Op)) {
01598         return false;
01599       }
01600     }
01601     return true;
01602   }
01603   
01604   if (const ConstantDataSequential *CDS =
01605         dyn_cast<ConstantDataSequential>(Mask)) {
01606     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
01607     for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
01608       if (CDS->getElementAsInteger(i) >= V1Size*2)
01609         return false;
01610     return true;
01611   }
01612   
01613   // The bitcode reader can create a place holder for a forward reference
01614   // used as the shuffle mask. When this occurs, the shuffle mask will
01615   // fall into this case and fail. To avoid this error, do this bit of
01616   // ugliness to allow such a mask pass.
01617   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
01618     if (CE->getOpcode() == Instruction::UserOp1)
01619       return true;
01620 
01621   return false;
01622 }
01623 
01624 /// getMaskValue - Return the index from the shuffle mask for the specified
01625 /// output result.  This is either -1 if the element is undef or a number less
01626 /// than 2*numelements.
01627 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
01628   assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
01629   if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
01630     return CDS->getElementAsInteger(i);
01631   Constant *C = Mask->getAggregateElement(i);
01632   if (isa<UndefValue>(C))
01633     return -1;
01634   return cast<ConstantInt>(C)->getZExtValue();
01635 }
01636 
01637 /// getShuffleMask - Return the full mask for this instruction, where each
01638 /// element is the element number and undef's are returned as -1.
01639 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
01640                                        SmallVectorImpl<int> &Result) {
01641   unsigned NumElts = Mask->getType()->getVectorNumElements();
01642   
01643   if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
01644     for (unsigned i = 0; i != NumElts; ++i)
01645       Result.push_back(CDS->getElementAsInteger(i));
01646     return;
01647   }    
01648   for (unsigned i = 0; i != NumElts; ++i) {
01649     Constant *C = Mask->getAggregateElement(i);
01650     Result.push_back(isa<UndefValue>(C) ? -1 :
01651                      cast<ConstantInt>(C)->getZExtValue());
01652   }
01653 }
01654 
01655 
01656 //===----------------------------------------------------------------------===//
01657 //                             InsertValueInst Class
01658 //===----------------------------------------------------------------------===//
01659 
01660 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 
01661                            const Twine &Name) {
01662   assert(NumOperands == 2 && "NumOperands not initialized?");
01663 
01664   // There's no fundamental reason why we require at least one index
01665   // (other than weirdness with &*IdxBegin being invalid; see
01666   // getelementptr's init routine for example). But there's no
01667   // present need to support it.
01668   assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
01669 
01670   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
01671          Val->getType() && "Inserted value must match indexed type!");
01672   Op<0>() = Agg;
01673   Op<1>() = Val;
01674 
01675   Indices.append(Idxs.begin(), Idxs.end());
01676   setName(Name);
01677 }
01678 
01679 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
01680   : Instruction(IVI.getType(), InsertValue,
01681                 OperandTraits<InsertValueInst>::op_begin(this), 2),
01682     Indices(IVI.Indices) {
01683   Op<0>() = IVI.getOperand(0);
01684   Op<1>() = IVI.getOperand(1);
01685   SubclassOptionalData = IVI.SubclassOptionalData;
01686 }
01687 
01688 //===----------------------------------------------------------------------===//
01689 //                             ExtractValueInst Class
01690 //===----------------------------------------------------------------------===//
01691 
01692 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
01693   assert(NumOperands == 1 && "NumOperands not initialized?");
01694 
01695   // There's no fundamental reason why we require at least one index.
01696   // But there's no present need to support it.
01697   assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
01698 
01699   Indices.append(Idxs.begin(), Idxs.end());
01700   setName(Name);
01701 }
01702 
01703 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
01704   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
01705     Indices(EVI.Indices) {
01706   SubclassOptionalData = EVI.SubclassOptionalData;
01707 }
01708 
01709 // getIndexedType - Returns the type of the element that would be extracted
01710 // with an extractvalue instruction with the specified parameters.
01711 //
01712 // A null type is returned if the indices are invalid for the specified
01713 // pointer type.
01714 //
01715 Type *ExtractValueInst::getIndexedType(Type *Agg,
01716                                        ArrayRef<unsigned> Idxs) {
01717   for (unsigned Index : Idxs) {
01718     // We can't use CompositeType::indexValid(Index) here.
01719     // indexValid() always returns true for arrays because getelementptr allows
01720     // out-of-bounds indices. Since we don't allow those for extractvalue and
01721     // insertvalue we need to check array indexing manually.
01722     // Since the only other types we can index into are struct types it's just
01723     // as easy to check those manually as well.
01724     if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
01725       if (Index >= AT->getNumElements())
01726         return nullptr;
01727     } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
01728       if (Index >= ST->getNumElements())
01729         return nullptr;
01730     } else {
01731       // Not a valid type to index into.
01732       return nullptr;
01733     }
01734 
01735     Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
01736   }
01737   return const_cast<Type*>(Agg);
01738 }
01739 
01740 //===----------------------------------------------------------------------===//
01741 //                             BinaryOperator Class
01742 //===----------------------------------------------------------------------===//
01743 
01744 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
01745                                Type *Ty, const Twine &Name,
01746                                Instruction *InsertBefore)
01747   : Instruction(Ty, iType,
01748                 OperandTraits<BinaryOperator>::op_begin(this),
01749                 OperandTraits<BinaryOperator>::operands(this),
01750                 InsertBefore) {
01751   Op<0>() = S1;
01752   Op<1>() = S2;
01753   init(iType);
01754   setName(Name);
01755 }
01756 
01757 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
01758                                Type *Ty, const Twine &Name,
01759                                BasicBlock *InsertAtEnd)
01760   : Instruction(Ty, iType,
01761                 OperandTraits<BinaryOperator>::op_begin(this),
01762                 OperandTraits<BinaryOperator>::operands(this),
01763                 InsertAtEnd) {
01764   Op<0>() = S1;
01765   Op<1>() = S2;
01766   init(iType);
01767   setName(Name);
01768 }
01769 
01770 
01771 void BinaryOperator::init(BinaryOps iType) {
01772   Value *LHS = getOperand(0), *RHS = getOperand(1);
01773   (void)LHS; (void)RHS; // Silence warnings.
01774   assert(LHS->getType() == RHS->getType() &&
01775          "Binary operator operand types must match!");
01776 #ifndef NDEBUG
01777   switch (iType) {
01778   case Add: case Sub:
01779   case Mul:
01780     assert(getType() == LHS->getType() &&
01781            "Arithmetic operation should return same type as operands!");
01782     assert(getType()->isIntOrIntVectorTy() &&
01783            "Tried to create an integer operation on a non-integer type!");
01784     break;
01785   case FAdd: case FSub:
01786   case FMul:
01787     assert(getType() == LHS->getType() &&
01788            "Arithmetic operation should return same type as operands!");
01789     assert(getType()->isFPOrFPVectorTy() &&
01790            "Tried to create a floating-point operation on a "
01791            "non-floating-point type!");
01792     break;
01793   case UDiv: 
01794   case SDiv: 
01795     assert(getType() == LHS->getType() &&
01796            "Arithmetic operation should return same type as operands!");
01797     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
01798             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
01799            "Incorrect operand type (not integer) for S/UDIV");
01800     break;
01801   case FDiv:
01802     assert(getType() == LHS->getType() &&
01803            "Arithmetic operation should return same type as operands!");
01804     assert(getType()->isFPOrFPVectorTy() &&
01805            "Incorrect operand type (not floating point) for FDIV");
01806     break;
01807   case URem: 
01808   case SRem: 
01809     assert(getType() == LHS->getType() &&
01810            "Arithmetic operation should return same type as operands!");
01811     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
01812             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
01813            "Incorrect operand type (not integer) for S/UREM");
01814     break;
01815   case FRem:
01816     assert(getType() == LHS->getType() &&
01817            "Arithmetic operation should return same type as operands!");
01818     assert(getType()->isFPOrFPVectorTy() &&
01819            "Incorrect operand type (not floating point) for FREM");
01820     break;
01821   case Shl:
01822   case LShr:
01823   case AShr:
01824     assert(getType() == LHS->getType() &&
01825            "Shift operation should return same type as operands!");
01826     assert((getType()->isIntegerTy() ||
01827             (getType()->isVectorTy() && 
01828              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
01829            "Tried to create a shift operation on a non-integral type!");
01830     break;
01831   case And: case Or:
01832   case Xor:
01833     assert(getType() == LHS->getType() &&
01834            "Logical operation should return same type as operands!");
01835     assert((getType()->isIntegerTy() ||
01836             (getType()->isVectorTy() && 
01837              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
01838            "Tried to create a logical operation on a non-integral type!");
01839     break;
01840   default:
01841     break;
01842   }
01843 #endif
01844 }
01845 
01846 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
01847                                        const Twine &Name,
01848                                        Instruction *InsertBefore) {
01849   assert(S1->getType() == S2->getType() &&
01850          "Cannot create binary operator with two operands of differing type!");
01851   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
01852 }
01853 
01854 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
01855                                        const Twine &Name,
01856                                        BasicBlock *InsertAtEnd) {
01857   BinaryOperator *Res = Create(Op, S1, S2, Name);
01858   InsertAtEnd->getInstList().push_back(Res);
01859   return Res;
01860 }
01861 
01862 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
01863                                           Instruction *InsertBefore) {
01864   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01865   return new BinaryOperator(Instruction::Sub,
01866                             zero, Op,
01867                             Op->getType(), Name, InsertBefore);
01868 }
01869 
01870 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
01871                                           BasicBlock *InsertAtEnd) {
01872   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01873   return new BinaryOperator(Instruction::Sub,
01874                             zero, Op,
01875                             Op->getType(), Name, InsertAtEnd);
01876 }
01877 
01878 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
01879                                              Instruction *InsertBefore) {
01880   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01881   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
01882 }
01883 
01884 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
01885                                              BasicBlock *InsertAtEnd) {
01886   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01887   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
01888 }
01889 
01890 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
01891                                              Instruction *InsertBefore) {
01892   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01893   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
01894 }
01895 
01896 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
01897                                              BasicBlock *InsertAtEnd) {
01898   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01899   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
01900 }
01901 
01902 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
01903                                            Instruction *InsertBefore) {
01904   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01905   return new BinaryOperator(Instruction::FSub, zero, Op,
01906                             Op->getType(), Name, InsertBefore);
01907 }
01908 
01909 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
01910                                            BasicBlock *InsertAtEnd) {
01911   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01912   return new BinaryOperator(Instruction::FSub, zero, Op,
01913                             Op->getType(), Name, InsertAtEnd);
01914 }
01915 
01916 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
01917                                           Instruction *InsertBefore) {
01918   Constant *C = Constant::getAllOnesValue(Op->getType());
01919   return new BinaryOperator(Instruction::Xor, Op, C,
01920                             Op->getType(), Name, InsertBefore);
01921 }
01922 
01923 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
01924                                           BasicBlock *InsertAtEnd) {
01925   Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
01926   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
01927                             Op->getType(), Name, InsertAtEnd);
01928 }
01929 
01930 
01931 // isConstantAllOnes - Helper function for several functions below
01932 static inline bool isConstantAllOnes(const Value *V) {
01933   if (const Constant *C = dyn_cast<Constant>(V))
01934     return C->isAllOnesValue();
01935   return false;
01936 }
01937 
01938 bool BinaryOperator::isNeg(const Value *V) {
01939   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01940     if (Bop->getOpcode() == Instruction::Sub)
01941       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
01942         return C->isNegativeZeroValue();
01943   return false;
01944 }
01945 
01946 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
01947   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01948     if (Bop->getOpcode() == Instruction::FSub)
01949       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
01950         if (!IgnoreZeroSign)
01951           IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
01952         return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
01953       }
01954   return false;
01955 }
01956 
01957 bool BinaryOperator::isNot(const Value *V) {
01958   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01959     return (Bop->getOpcode() == Instruction::Xor &&
01960             (isConstantAllOnes(Bop->getOperand(1)) ||
01961              isConstantAllOnes(Bop->getOperand(0))));
01962   return false;
01963 }
01964 
01965 Value *BinaryOperator::getNegArgument(Value *BinOp) {
01966   return cast<BinaryOperator>(BinOp)->getOperand(1);
01967 }
01968 
01969 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
01970   return getNegArgument(const_cast<Value*>(BinOp));
01971 }
01972 
01973 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
01974   return cast<BinaryOperator>(BinOp)->getOperand(1);
01975 }
01976 
01977 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
01978   return getFNegArgument(const_cast<Value*>(BinOp));
01979 }
01980 
01981 Value *BinaryOperator::getNotArgument(Value *BinOp) {
01982   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
01983   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
01984   Value *Op0 = BO->getOperand(0);
01985   Value *Op1 = BO->getOperand(1);
01986   if (isConstantAllOnes(Op0)) return Op1;
01987 
01988   assert(isConstantAllOnes(Op1));
01989   return Op0;
01990 }
01991 
01992 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
01993   return getNotArgument(const_cast<Value*>(BinOp));
01994 }
01995 
01996 
01997 // swapOperands - Exchange the two operands to this instruction.  This
01998 // instruction is safe to use on any binary instruction and does not
01999 // modify the semantics of the instruction.  If the instruction is
02000 // order dependent (SetLT f.e.) the opcode is changed.
02001 //
02002 bool BinaryOperator::swapOperands() {
02003   if (!isCommutative())
02004     return true; // Can't commute operands
02005   Op<0>().swap(Op<1>());
02006   return false;
02007 }
02008 
02009 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
02010   cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
02011 }
02012 
02013 void BinaryOperator::setHasNoSignedWrap(bool b) {
02014   cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
02015 }
02016 
02017 void BinaryOperator::setIsExact(bool b) {
02018   cast<PossiblyExactOperator>(this)->setIsExact(b);
02019 }
02020 
02021 bool BinaryOperator::hasNoUnsignedWrap() const {
02022   return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
02023 }
02024 
02025 bool BinaryOperator::hasNoSignedWrap() const {
02026   return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
02027 }
02028 
02029 bool BinaryOperator::isExact() const {
02030   return cast<PossiblyExactOperator>(this)->isExact();
02031 }
02032 
02033 //===----------------------------------------------------------------------===//
02034 //                             FPMathOperator Class
02035 //===----------------------------------------------------------------------===//
02036 
02037 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
02038 /// An accuracy of 0.0 means that the operation should be performed with the
02039 /// default precision.
02040 float FPMathOperator::getFPAccuracy() const {
02041   const MDNode *MD =
02042     cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
02043   if (!MD)
02044     return 0.0;
02045   ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
02046   return Accuracy->getValueAPF().convertToFloat();
02047 }
02048 
02049 
02050 //===----------------------------------------------------------------------===//
02051 //                                CastInst Class
02052 //===----------------------------------------------------------------------===//
02053 
02054 void CastInst::anchor() {}
02055 
02056 // Just determine if this cast only deals with integral->integral conversion.
02057 bool CastInst::isIntegerCast() const {
02058   switch (getOpcode()) {
02059     default: return false;
02060     case Instruction::ZExt:
02061     case Instruction::SExt:
02062     case Instruction::Trunc:
02063       return true;
02064     case Instruction::BitCast:
02065       return getOperand(0)->getType()->isIntegerTy() &&
02066         getType()->isIntegerTy();
02067   }
02068 }
02069 
02070 bool CastInst::isLosslessCast() const {
02071   // Only BitCast can be lossless, exit fast if we're not BitCast
02072   if (getOpcode() != Instruction::BitCast)
02073     return false;
02074 
02075   // Identity cast is always lossless
02076   Type* SrcTy = getOperand(0)->getType();
02077   Type* DstTy = getType();
02078   if (SrcTy == DstTy)
02079     return true;
02080   
02081   // Pointer to pointer is always lossless.
02082   if (SrcTy->isPointerTy())
02083     return DstTy->isPointerTy();
02084   return false;  // Other types have no identity values
02085 }
02086 
02087 /// This function determines if the CastInst does not require any bits to be
02088 /// changed in order to effect the cast. Essentially, it identifies cases where
02089 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
02090 /// example, the following are all no-op casts:
02091 /// # bitcast i32* %x to i8*
02092 /// # bitcast <2 x i32> %x to <4 x i16> 
02093 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
02094 /// @brief Determine if the described cast is a no-op.
02095 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
02096                           Type *SrcTy,
02097                           Type *DestTy,
02098                           Type *IntPtrTy) {
02099   switch (Opcode) {
02100     default: llvm_unreachable("Invalid CastOp");
02101     case Instruction::Trunc:
02102     case Instruction::ZExt:
02103     case Instruction::SExt: 
02104     case Instruction::FPTrunc:
02105     case Instruction::FPExt:
02106     case Instruction::UIToFP:
02107     case Instruction::SIToFP:
02108     case Instruction::FPToUI:
02109     case Instruction::FPToSI:
02110     case Instruction::AddrSpaceCast:
02111       // TODO: Target informations may give a more accurate answer here.
02112       return false;
02113     case Instruction::BitCast:
02114       return true;  // BitCast never modifies bits.
02115     case Instruction::PtrToInt:
02116       return IntPtrTy->getScalarSizeInBits() ==
02117              DestTy->getScalarSizeInBits();
02118     case Instruction::IntToPtr:
02119       return IntPtrTy->getScalarSizeInBits() ==
02120              SrcTy->getScalarSizeInBits();
02121   }
02122 }
02123 
02124 /// @brief Determine if a cast is a no-op.
02125 bool CastInst::isNoopCast(Type *IntPtrTy) const {
02126   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
02127 }
02128 
02129 bool CastInst::isNoopCast(const DataLayout *DL) const {
02130   if (!DL) {
02131     // Assume maximum pointer size.
02132     return isNoopCast(Type::getInt64Ty(getContext()));
02133   }
02134 
02135   Type *PtrOpTy = nullptr;
02136   if (getOpcode() == Instruction::PtrToInt)
02137     PtrOpTy = getOperand(0)->getType();
02138   else if (getOpcode() == Instruction::IntToPtr)
02139     PtrOpTy = getType();
02140 
02141   Type *IntPtrTy = PtrOpTy
02142                  ? DL->getIntPtrType(PtrOpTy)
02143                  : DL->getIntPtrType(getContext(), 0);
02144 
02145   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
02146 }
02147 
02148 /// This function determines if a pair of casts can be eliminated and what
02149 /// opcode should be used in the elimination. This assumes that there are two
02150 /// instructions like this:
02151 /// *  %F = firstOpcode SrcTy %x to MidTy
02152 /// *  %S = secondOpcode MidTy %F to DstTy
02153 /// The function returns a resultOpcode so these two casts can be replaced with:
02154 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
02155 /// If no such cast is permited, the function returns 0.
02156 unsigned CastInst::isEliminableCastPair(
02157   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
02158   Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
02159   Type *DstIntPtrTy) {
02160   // Define the 144 possibilities for these two cast instructions. The values
02161   // in this matrix determine what to do in a given situation and select the
02162   // case in the switch below.  The rows correspond to firstOp, the columns 
02163   // correspond to secondOp.  In looking at the table below, keep in  mind
02164   // the following cast properties:
02165   //
02166   //          Size Compare       Source               Destination
02167   // Operator  Src ? Size   Type       Sign         Type       Sign
02168   // -------- ------------ -------------------   ---------------------
02169   // TRUNC         >       Integer      Any        Integral     Any
02170   // ZEXT          <       Integral   Unsigned     Integer      Any
02171   // SEXT          <       Integral    Signed      Integer      Any
02172   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
02173   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed
02174   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a
02175   // SITOFP       n/a      Integral    Signed      FloatPt      n/a
02176   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a
02177   // FPEXT         <       FloatPt      n/a        FloatPt      n/a
02178   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
02179   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
02180   // BITCAST       =       FirstClass   n/a       FirstClass    n/a
02181   // ADDRSPCST    n/a      Pointer      n/a        Pointer      n/a
02182   //
02183   // NOTE: some transforms are safe, but we consider them to be non-profitable.
02184   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
02185   // into "fptoui double to i64", but this loses information about the range
02186   // of the produced value (we no longer know the top-part is all zeros).
02187   // Further this conversion is often much more expensive for typical hardware,
02188   // and causes issues when building libgcc.  We disallow fptosi+sext for the
02189   // same reason.
02190   const unsigned numCastOps =
02191     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
02192   static const uint8_t CastResults[numCastOps][numCastOps] = {
02193     // T        F  F  U  S  F  F  P  I  B  A  -+
02194     // R  Z  S  P  P  I  I  T  P  2  N  T  S   |
02195     // U  E  E  2  2  2  2  R  E  I  T  C  C   +- secondOp
02196     // N  X  X  U  S  F  F  N  X  N  2  V  V   |
02197     // C  T  T  I  I  P  P  C  T  T  P  T  T  -+
02198     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc         -+
02199     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3, 0}, // ZExt           |
02200     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt           |
02201     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI         |
02202     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI         |
02203     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP         +- firstOp
02204     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP         |
02205     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4, 0}, // FPTrunc        |
02206     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt          |
02207     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt       |
02208     { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr       |
02209     {  5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast        |
02210     {  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
02211   };
02212 
02213   // If either of the casts are a bitcast from scalar to vector, disallow the
02214   // merging. However, bitcast of A->B->A are allowed.
02215   bool isFirstBitcast  = (firstOp == Instruction::BitCast);
02216   bool isSecondBitcast = (secondOp == Instruction::BitCast);
02217   bool chainedBitcast  = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
02218 
02219   // Check if any of the bitcasts convert scalars<->vectors.
02220   if ((isFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
02221       (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
02222     // Unless we are bitcasing to the original type, disallow optimizations.
02223     if (!chainedBitcast) return 0;
02224 
02225   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
02226                             [secondOp-Instruction::CastOpsBegin];
02227   switch (ElimCase) {
02228     case 0: 
02229       // Categorically disallowed.
02230       return 0;
02231     case 1: 
02232       // Allowed, use first cast's opcode.
02233       return firstOp;
02234     case 2: 
02235       // Allowed, use second cast's opcode.
02236       return secondOp;
02237     case 3: 
02238       // No-op cast in second op implies firstOp as long as the DestTy
02239       // is integer and we are not converting between a vector and a
02240       // non-vector type.
02241       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
02242         return firstOp;
02243       return 0;
02244     case 4:
02245       // No-op cast in second op implies firstOp as long as the DestTy
02246       // is floating point.
02247       if (DstTy->isFloatingPointTy())
02248         return firstOp;
02249       return 0;
02250     case 5: 
02251       // No-op cast in first op implies secondOp as long as the SrcTy
02252       // is an integer.
02253       if (SrcTy->isIntegerTy())
02254         return secondOp;
02255       return 0;
02256     case 6:
02257       // No-op cast in first op implies secondOp as long as the SrcTy
02258       // is a floating point.
02259       if (SrcTy->isFloatingPointTy())
02260         return secondOp;
02261       return 0;
02262     case 7: {
02263       // Cannot simplify if address spaces are different!
02264       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
02265         return 0;
02266 
02267       unsigned MidSize = MidTy->getScalarSizeInBits();
02268       // We can still fold this without knowing the actual sizes as long we
02269       // know that the intermediate pointer is the largest possible
02270       // pointer size.
02271       // FIXME: Is this always true?
02272       if (MidSize == 64)
02273         return Instruction::BitCast;
02274 
02275       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
02276       if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
02277         return 0;
02278       unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
02279       if (MidSize >= PtrSize)
02280         return Instruction::BitCast;
02281       return 0;
02282     }
02283     case 8: {
02284       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
02285       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
02286       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
02287       unsigned SrcSize = SrcTy->getScalarSizeInBits();
02288       unsigned DstSize = DstTy->getScalarSizeInBits();
02289       if (SrcSize == DstSize)
02290         return Instruction::BitCast;
02291       else if (SrcSize < DstSize)
02292         return firstOp;
02293       return secondOp;
02294     }
02295     case 9:
02296       // zext, sext -> zext, because sext can't sign extend after zext
02297       return Instruction::ZExt;
02298     case 10:
02299       // fpext followed by ftrunc is allowed if the bit size returned to is
02300       // the same as the original, in which case its just a bitcast
02301       if (SrcTy == DstTy)
02302         return Instruction::BitCast;
02303       return 0; // If the types are not the same we can't eliminate it.
02304     case 11: {
02305       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
02306       if (!MidIntPtrTy)
02307         return 0;
02308       unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
02309       unsigned SrcSize = SrcTy->getScalarSizeInBits();
02310       unsigned DstSize = DstTy->getScalarSizeInBits();
02311       if (SrcSize <= PtrSize && SrcSize == DstSize)
02312         return Instruction::BitCast;
02313       return 0;
02314     }
02315     case 12: {
02316       // addrspacecast, addrspacecast -> bitcast,       if SrcAS == DstAS
02317       // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
02318       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
02319         return Instruction::AddrSpaceCast;
02320       return Instruction::BitCast;
02321     }
02322     case 13:
02323       // FIXME: this state can be merged with (1), but the following assert
02324       // is useful to check the correcteness of the sequence due to semantic
02325       // change of bitcast.
02326       assert(
02327         SrcTy->isPtrOrPtrVectorTy() &&
02328         MidTy->isPtrOrPtrVectorTy() &&
02329         DstTy->isPtrOrPtrVectorTy() &&
02330         SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
02331         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
02332         "Illegal addrspacecast, bitcast sequence!");
02333       // Allowed, use first cast's opcode
02334       return firstOp;
02335     case 14:
02336       // bitcast, addrspacecast -> addrspacecast if the element type of
02337       // bitcast's source is the same as that of addrspacecast's destination.
02338       if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
02339         return Instruction::AddrSpaceCast;
02340       return 0;
02341 
02342     case 15:
02343       // FIXME: this state can be merged with (1), but the following assert
02344       // is useful to check the correcteness of the sequence due to semantic
02345       // change of bitcast.
02346       assert(
02347         SrcTy->isIntOrIntVectorTy() &&
02348         MidTy->isPtrOrPtrVectorTy() &&
02349         DstTy->isPtrOrPtrVectorTy() &&
02350         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
02351         "Illegal inttoptr, bitcast sequence!");
02352       // Allowed, use first cast's opcode
02353       return firstOp;
02354     case 16:
02355       // FIXME: this state can be merged with (2), but the following assert
02356       // is useful to check the correcteness of the sequence due to semantic
02357       // change of bitcast.
02358       assert(
02359         SrcTy->isPtrOrPtrVectorTy() &&
02360         MidTy->isPtrOrPtrVectorTy() &&
02361         DstTy->isIntOrIntVectorTy() &&
02362         SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
02363         "Illegal bitcast, ptrtoint sequence!");
02364       // Allowed, use second cast's opcode
02365       return secondOp;
02366     case 99: 
02367       // Cast combination can't happen (error in input). This is for all cases
02368       // where the MidTy is not the same for the two cast instructions.
02369       llvm_unreachable("Invalid Cast Combination");
02370     default:
02371       llvm_unreachable("Error in CastResults table!!!");
02372   }
02373 }
02374 
02375 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 
02376   const Twine &Name, Instruction *InsertBefore) {
02377   assert(castIsValid(op, S, Ty) && "Invalid cast!");
02378   // Construct and return the appropriate CastInst subclass
02379   switch (op) {
02380   case Trunc:         return new TruncInst         (S, Ty, Name, InsertBefore);
02381   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertBefore);
02382   case SExt:          return new SExtInst          (S, Ty, Name, InsertBefore);
02383   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertBefore);
02384   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertBefore);
02385   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertBefore);
02386   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertBefore);
02387   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertBefore);
02388   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertBefore);
02389   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertBefore);
02390   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertBefore);
02391   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertBefore);
02392   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
02393   default: llvm_unreachable("Invalid opcode provided");
02394   }
02395 }
02396 
02397 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
02398   const Twine &Name, BasicBlock *InsertAtEnd) {
02399   assert(castIsValid(op, S, Ty) && "Invalid cast!");
02400   // Construct and return the appropriate CastInst subclass
02401   switch (op) {
02402   case Trunc:         return new TruncInst         (S, Ty, Name, InsertAtEnd);
02403   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertAtEnd);
02404   case SExt:          return new SExtInst          (S, Ty, Name, InsertAtEnd);
02405   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertAtEnd);
02406   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertAtEnd);
02407   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertAtEnd);
02408   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertAtEnd);
02409   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertAtEnd);
02410   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertAtEnd);
02411   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertAtEnd);
02412   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertAtEnd);
02413   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertAtEnd);
02414   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
02415   default: llvm_unreachable("Invalid opcode provided");
02416   }
02417 }
02418 
02419 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
02420                                         const Twine &Name,
02421                                         Instruction *InsertBefore) {
02422   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02423     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02424   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
02425 }
02426 
02427 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
02428                                         const Twine &Name,
02429                                         BasicBlock *InsertAtEnd) {
02430   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02431     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02432   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
02433 }
02434 
02435 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
02436                                         const Twine &Name,
02437                                         Instruction *InsertBefore) {
02438   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02439     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02440   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
02441 }
02442 
02443 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
02444                                         const Twine &Name,
02445                                         BasicBlock *InsertAtEnd) {
02446   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02447     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02448   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
02449 }
02450 
02451 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
02452                                          const Twine &Name,
02453                                          Instruction *InsertBefore) {
02454   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02455     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02456   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
02457 }
02458 
02459 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
02460                                          const Twine &Name, 
02461                                          BasicBlock *InsertAtEnd) {
02462   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02463     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02464   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
02465 }
02466 
02467 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
02468                                       const Twine &Name,
02469                                       BasicBlock *InsertAtEnd) {
02470   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
02471   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
02472          "Invalid cast");
02473   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
02474   assert((!Ty->isVectorTy() ||
02475           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
02476          "Invalid cast");
02477 
02478   if (Ty->isIntOrIntVectorTy())
02479     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
02480 
02481   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
02482 }
02483 
02484 /// @brief Create a BitCast or a PtrToInt cast instruction
02485 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
02486                                       const Twine &Name,
02487                                       Instruction *InsertBefore) {
02488   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
02489   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
02490          "Invalid cast");
02491   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
02492   assert((!Ty->isVectorTy() ||
02493           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
02494          "Invalid cast");
02495 
02496   if (Ty->isIntOrIntVectorTy())
02497     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
02498 
02499   return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
02500 }
02501 
02502 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
02503   Value *S, Type *Ty,
02504   const Twine &Name,
02505   BasicBlock *InsertAtEnd) {
02506   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
02507   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
02508 
02509   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
02510     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
02511 
02512   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02513 }
02514 
02515 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
02516   Value *S, Type *Ty,
02517   const Twine &Name,
02518   Instruction *InsertBefore) {
02519   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
02520   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
02521 
02522   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
02523     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
02524 
02525   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02526 }
02527 
02528 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
02529                                       bool isSigned, const Twine &Name,
02530                                       Instruction *InsertBefore) {
02531   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
02532          "Invalid integer cast");
02533   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02534   unsigned DstBits = Ty->getScalarSizeInBits();
02535   Instruction::CastOps opcode =
02536     (SrcBits == DstBits ? Instruction::BitCast :
02537      (SrcBits > DstBits ? Instruction::Trunc :
02538       (isSigned ? Instruction::SExt : Instruction::ZExt)));
02539   return Create(opcode, C, Ty, Name, InsertBefore);
02540 }
02541 
02542 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
02543                                       bool isSigned, const Twine &Name,
02544                                       BasicBlock *InsertAtEnd) {
02545   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
02546          "Invalid cast");
02547   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02548   unsigned DstBits = Ty->getScalarSizeInBits();
02549   Instruction::CastOps opcode =
02550     (SrcBits == DstBits ? Instruction::BitCast :
02551      (SrcBits > DstBits ? Instruction::Trunc :
02552       (isSigned ? Instruction::SExt : Instruction::ZExt)));
02553   return Create(opcode, C, Ty, Name, InsertAtEnd);
02554 }
02555 
02556 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
02557                                  const Twine &Name, 
02558                                  Instruction *InsertBefore) {
02559   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
02560          "Invalid cast");
02561   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02562   unsigned DstBits = Ty->getScalarSizeInBits();
02563   Instruction::CastOps opcode =
02564     (SrcBits == DstBits ? Instruction::BitCast :
02565      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
02566   return Create(opcode, C, Ty, Name, InsertBefore);
02567 }
02568 
02569 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
02570                                  const Twine &Name, 
02571                                  BasicBlock *InsertAtEnd) {
02572   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
02573          "Invalid cast");
02574   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02575   unsigned DstBits = Ty->getScalarSizeInBits();
02576   Instruction::CastOps opcode =
02577     (SrcBits == DstBits ? Instruction::BitCast :
02578      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
02579   return Create(opcode, C, Ty, Name, InsertAtEnd);
02580 }
02581 
02582 // Check whether it is valid to call getCastOpcode for these types.
02583 // This routine must be kept in sync with getCastOpcode.
02584 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
02585   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
02586     return false;
02587 
02588   if (SrcTy == DestTy)
02589     return true;
02590 
02591   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
02592     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
02593       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
02594         // An element by element cast.  Valid if casting the elements is valid.
02595         SrcTy = SrcVecTy->getElementType();
02596         DestTy = DestVecTy->getElementType();
02597       }
02598 
02599   // Get the bit sizes, we'll need these
02600   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
02601   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
02602 
02603   // Run through the possibilities ...
02604   if (DestTy->isIntegerTy()) {               // Casting to integral
02605     if (SrcTy->isIntegerTy()) {                // Casting from integral
02606         return true;
02607     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
02608       return true;
02609     } else if (SrcTy->isVectorTy()) {          // Casting from vector
02610       return DestBits == SrcBits;
02611     } else {                                   // Casting from something else
02612       return SrcTy->isPointerTy();
02613     }
02614   } else if (DestTy->isFloatingPointTy()) {  // Casting to floating pt
02615     if (SrcTy->isIntegerTy()) {                // Casting from integral
02616       return true;
02617     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
02618       return true;
02619     } else if (SrcTy->isVectorTy()) {          // Casting from vector
02620       return DestBits == SrcBits;
02621     } else {                                   // Casting from something else
02622       return false;
02623     }
02624   } else if (DestTy->isVectorTy()) {         // Casting to vector
02625     return DestBits == SrcBits;
02626   } else if (DestTy->isPointerTy()) {        // Casting to pointer
02627     if (SrcTy->isPointerTy()) {                // Casting from pointer
02628       return true;
02629     } else if (SrcTy->isIntegerTy()) {         // Casting from integral
02630       return true;
02631     } else {                                   // Casting from something else
02632       return false;
02633     }
02634   } else if (DestTy->isX86_MMXTy()) {
02635     if (SrcTy->isVectorTy()) {
02636       return DestBits == SrcBits;       // 64-bit vector to MMX
02637     } else {
02638       return false;
02639     }
02640   } else {                                   // Casting to something else
02641     return false;
02642   }
02643 }
02644 
02645 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
02646   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
02647     return false;
02648 
02649   if (SrcTy == DestTy)
02650     return true;
02651 
02652   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
02653     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
02654       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
02655         // An element by element cast. Valid if casting the elements is valid.
02656         SrcTy = SrcVecTy->getElementType();
02657         DestTy = DestVecTy->getElementType();
02658       }
02659     }
02660   }
02661 
02662   if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
02663     if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
02664       return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
02665     }
02666   }
02667 
02668   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
02669   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
02670 
02671   // Could still have vectors of pointers if the number of elements doesn't
02672   // match
02673   if (SrcBits == 0 || DestBits == 0)
02674     return false;
02675 
02676   if (SrcBits != DestBits)
02677     return false;
02678 
02679   if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
02680     return false;
02681 
02682   return true;
02683 }
02684 
02685 // Provide a way to get a "cast" where the cast opcode is inferred from the
02686 // types and size of the operand. This, basically, is a parallel of the
02687 // logic in the castIsValid function below.  This axiom should hold:
02688 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
02689 // should not assert in castIsValid. In other words, this produces a "correct"
02690 // casting opcode for the arguments passed to it.
02691 // This routine must be kept in sync with isCastable.
02692 Instruction::CastOps
02693 CastInst::getCastOpcode(
02694   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
02695   Type *SrcTy = Src->getType();
02696 
02697   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
02698          "Only first class types are castable!");
02699 
02700   if (SrcTy == DestTy)
02701     return BitCast;
02702 
02703   // FIXME: Check address space sizes here
02704   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
02705     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
02706       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
02707         // An element by element cast.  Find the appropriate opcode based on the
02708         // element types.
02709         SrcTy = SrcVecTy->getElementType();
02710         DestTy = DestVecTy->getElementType();
02711       }
02712 
02713   // Get the bit sizes, we'll need these
02714   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
02715   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
02716 
02717   // Run through the possibilities ...
02718   if (DestTy->isIntegerTy()) {                      // Casting to integral
02719     if (SrcTy->isIntegerTy()) {                     // Casting from integral
02720       if (DestBits < SrcBits)
02721         return Trunc;                               // int -> smaller int
02722       else if (DestBits > SrcBits) {                // its an extension
02723         if (SrcIsSigned)
02724           return SExt;                              // signed -> SEXT
02725         else
02726           return ZExt;                              // unsigned -> ZEXT
02727       } else {
02728         return BitCast;                             // Same size, No-op cast
02729       }
02730     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
02731       if (DestIsSigned) 
02732         return FPToSI;                              // FP -> sint
02733       else
02734         return FPToUI;                              // FP -> uint 
02735     } else if (SrcTy->isVectorTy()) {
02736       assert(DestBits == SrcBits &&
02737              "Casting vector to integer of different width");
02738       return BitCast;                             // Same size, no-op cast
02739     } else {
02740       assert(SrcTy->isPointerTy() &&
02741              "Casting from a value that is not first-class type");
02742       return PtrToInt;                              // ptr -> int
02743     }
02744   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
02745     if (SrcTy->isIntegerTy()) {                     // Casting from integral
02746       if (SrcIsSigned)
02747         return SIToFP;                              // sint -> FP
02748       else
02749         return UIToFP;                              // uint -> FP
02750     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
02751       if (DestBits < SrcBits) {
02752         return FPTrunc;                             // FP -> smaller FP
02753       } else if (DestBits > SrcBits) {
02754         return FPExt;                               // FP -> larger FP
02755       } else  {
02756         return BitCast;                             // same size, no-op cast
02757       }
02758     } else if (SrcTy->isVectorTy()) {
02759       assert(DestBits == SrcBits &&
02760              "Casting vector to floating point of different width");
02761       return BitCast;                             // same size, no-op cast
02762     }
02763     llvm_unreachable("Casting pointer or non-first class to float");
02764   } else if (DestTy->isVectorTy()) {
02765     assert(DestBits == SrcBits &&
02766            "Illegal cast to vector (wrong type or size)");
02767     return BitCast;
02768   } else if (DestTy->isPointerTy()) {
02769     if (SrcTy->isPointerTy()) {
02770       if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
02771         return AddrSpaceCast;
02772       return BitCast;                               // ptr -> ptr
02773     } else if (SrcTy->isIntegerTy()) {
02774       return IntToPtr;                              // int -> ptr
02775     }
02776     llvm_unreachable("Casting pointer to other than pointer or int");
02777   } else if (DestTy->isX86_MMXTy()) {
02778     if (SrcTy->isVectorTy()) {
02779       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
02780       return BitCast;                               // 64-bit vector to MMX
02781     }
02782     llvm_unreachable("Illegal cast to X86_MMX");
02783   }
02784   llvm_unreachable("Casting to type that is not first-class");
02785 }
02786 
02787 //===----------------------------------------------------------------------===//
02788 //                    CastInst SubClass Constructors
02789 //===----------------------------------------------------------------------===//
02790 
02791 /// Check that the construction parameters for a CastInst are correct. This
02792 /// could be broken out into the separate constructors but it is useful to have
02793 /// it in one place and to eliminate the redundant code for getting the sizes
02794 /// of the types involved.
02795 bool 
02796 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
02797 
02798   // Check for type sanity on the arguments
02799   Type *SrcTy = S->getType();
02800 
02801   // If this is a cast to the same type then it's trivially true.
02802   if (SrcTy == DstTy)
02803     return true;
02804 
02805   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
02806       SrcTy->isAggregateType() || DstTy->isAggregateType())
02807     return false;
02808 
02809   // Get the size of the types in bits, we'll need this later
02810   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
02811   unsigned DstBitSize = DstTy->getScalarSizeInBits();
02812 
02813   // If these are vector types, get the lengths of the vectors (using zero for
02814   // scalar types means that checking that vector lengths match also checks that
02815   // scalars are not being converted to vectors or vectors to scalars).
02816   unsigned SrcLength = SrcTy->isVectorTy() ?
02817     cast<VectorType>(SrcTy)->getNumElements() : 0;
02818   unsigned DstLength = DstTy->isVectorTy() ?
02819     cast<VectorType>(DstTy)->getNumElements() : 0;
02820 
02821   // Switch on the opcode provided
02822   switch (op) {
02823   default: return false; // This is an input error
02824   case Instruction::Trunc:
02825     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
02826       SrcLength == DstLength && SrcBitSize > DstBitSize;
02827   case Instruction::ZExt:
02828     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
02829       SrcLength == DstLength && SrcBitSize < DstBitSize;
02830   case Instruction::SExt: 
02831     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
02832       SrcLength == DstLength && SrcBitSize < DstBitSize;
02833   case Instruction::FPTrunc:
02834     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
02835       SrcLength == DstLength && SrcBitSize > DstBitSize;
02836   case Instruction::FPExt:
02837     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
02838       SrcLength == DstLength && SrcBitSize < DstBitSize;
02839   case Instruction::UIToFP:
02840   case Instruction::SIToFP:
02841     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
02842       SrcLength == DstLength;
02843   case Instruction::FPToUI:
02844   case Instruction::FPToSI:
02845     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
02846       SrcLength == DstLength;
02847   case Instruction::PtrToInt:
02848     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
02849       return false;
02850     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
02851       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
02852         return false;
02853     return SrcTy->getScalarType()->isPointerTy() &&
02854            DstTy->getScalarType()->isIntegerTy();
02855   case Instruction::IntToPtr:
02856     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
02857       return false;
02858     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
02859       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
02860         return false;
02861     return SrcTy->getScalarType()->isIntegerTy() &&
02862            DstTy->getScalarType()->isPointerTy();
02863   case Instruction::BitCast: {
02864     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
02865     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
02866 
02867     // BitCast implies a no-op cast of type only. No bits change.
02868     // However, you can't cast pointers to anything but pointers.
02869     if (!SrcPtrTy != !DstPtrTy)
02870       return false;
02871 
02872     // For non-pointer cases, the cast is okay if the source and destination bit
02873     // widths are identical.
02874     if (!SrcPtrTy)
02875       return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
02876 
02877     // If both are pointers then the address spaces must match.
02878     if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
02879       return false;
02880 
02881     // A vector of pointers must have the same number of elements.
02882     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
02883       if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
02884         return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
02885 
02886       return false;
02887     }
02888 
02889     return true;
02890   }
02891   case Instruction::AddrSpaceCast: {
02892     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
02893     if (!SrcPtrTy)
02894       return false;
02895 
02896     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
02897     if (!DstPtrTy)
02898       return false;
02899 
02900     if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
02901       return false;
02902 
02903     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
02904       if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
02905         return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
02906 
02907       return false;
02908     }
02909 
02910     return true;
02911   }
02912   }
02913 }
02914 
02915 TruncInst::TruncInst(
02916   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02917 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
02918   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
02919 }
02920 
02921 TruncInst::TruncInst(
02922   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02923 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
02924   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
02925 }
02926 
02927 ZExtInst::ZExtInst(
02928   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02929 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
02930   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
02931 }
02932 
02933 ZExtInst::ZExtInst(
02934   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02935 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
02936   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
02937 }
02938 SExtInst::SExtInst(
02939   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02940 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
02941   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
02942 }
02943 
02944 SExtInst::SExtInst(
02945   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02946 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
02947   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
02948 }
02949 
02950 FPTruncInst::FPTruncInst(
02951   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02952 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
02953   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
02954 }
02955 
02956 FPTruncInst::FPTruncInst(
02957   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02958 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
02959   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
02960 }
02961 
02962 FPExtInst::FPExtInst(
02963   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02964 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
02965   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
02966 }
02967 
02968 FPExtInst::FPExtInst(
02969   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02970 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
02971   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
02972 }
02973 
02974 UIToFPInst::UIToFPInst(
02975   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02976 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
02977   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
02978 }
02979 
02980 UIToFPInst::UIToFPInst(
02981   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02982 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
02983   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
02984 }
02985 
02986 SIToFPInst::SIToFPInst(
02987   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02988 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
02989   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
02990 }
02991 
02992 SIToFPInst::SIToFPInst(
02993   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02994 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
02995   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
02996 }
02997 
02998 FPToUIInst::FPToUIInst(
02999   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03000 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
03001   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
03002 }
03003 
03004 FPToUIInst::FPToUIInst(
03005   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03006 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
03007   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
03008 }
03009 
03010 FPToSIInst::FPToSIInst(
03011   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03012 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
03013   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
03014 }
03015 
03016 FPToSIInst::FPToSIInst(
03017   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03018 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
03019   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
03020 }
03021 
03022 PtrToIntInst::PtrToIntInst(
03023   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03024 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
03025   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
03026 }
03027 
03028 PtrToIntInst::PtrToIntInst(
03029   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03030 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
03031   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
03032 }
03033 
03034 IntToPtrInst::IntToPtrInst(
03035   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03036 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
03037   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
03038 }
03039 
03040 IntToPtrInst::IntToPtrInst(
03041   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03042 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
03043   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
03044 }
03045 
03046 BitCastInst::BitCastInst(
03047   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03048 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
03049   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
03050 }
03051 
03052 BitCastInst::BitCastInst(
03053   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03054 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
03055   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
03056 }
03057 
03058 AddrSpaceCastInst::AddrSpaceCastInst(
03059   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03060 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
03061   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
03062 }
03063 
03064 AddrSpaceCastInst::AddrSpaceCastInst(
03065   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03066 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
03067   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
03068 }
03069 
03070 //===----------------------------------------------------------------------===//
03071 //                               CmpInst Classes
03072 //===----------------------------------------------------------------------===//
03073 
03074 void CmpInst::anchor() {}
03075 
03076 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
03077                  Value *LHS, Value *RHS, const Twine &Name,
03078                  Instruction *InsertBefore)
03079   : Instruction(ty, op,
03080                 OperandTraits<CmpInst>::op_begin(this),
03081                 OperandTraits<CmpInst>::operands(this),
03082                 InsertBefore) {
03083     Op<0>() = LHS;
03084     Op<1>() = RHS;
03085   setPredicate((Predicate)predicate);
03086   setName(Name);
03087 }
03088 
03089 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
03090                  Value *LHS, Value *RHS, const Twine &Name,
03091                  BasicBlock *InsertAtEnd)
03092   : Instruction(ty, op,
03093                 OperandTraits<CmpInst>::op_begin(this),
03094                 OperandTraits<CmpInst>::operands(this),
03095                 InsertAtEnd) {
03096   Op<0>() = LHS;
03097   Op<1>() = RHS;
03098   setPredicate((Predicate)predicate);
03099   setName(Name);
03100 }
03101 
03102 CmpInst *
03103 CmpInst::Create(OtherOps Op, unsigned short predicate,
03104                 Value *S1, Value *S2, 
03105                 const Twine &Name, Instruction *InsertBefore) {
03106   if (Op == Instruction::ICmp) {
03107     if (InsertBefore)
03108       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
03109                           S1, S2, Name);
03110     else
03111       return new ICmpInst(CmpInst::Predicate(predicate),
03112                           S1, S2, Name);
03113   }
03114   
03115   if (InsertBefore)
03116     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
03117                         S1, S2, Name);
03118   else
03119     return new FCmpInst(CmpInst::Predicate(predicate),
03120                         S1, S2, Name);
03121 }
03122 
03123 CmpInst *
03124 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
03125                 const Twine &Name, BasicBlock *InsertAtEnd) {
03126   if (Op == Instruction::ICmp) {
03127     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
03128                         S1, S2, Name);
03129   }
03130   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
03131                       S1, S2, Name);
03132 }
03133 
03134 void CmpInst::swapOperands() {
03135   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
03136     IC->swapOperands();
03137   else
03138     cast<FCmpInst>(this)->swapOperands();
03139 }
03140 
03141 bool CmpInst::isCommutative() const {
03142   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
03143     return IC->isCommutative();
03144   return cast<FCmpInst>(this)->isCommutative();
03145 }
03146 
03147 bool CmpInst::isEquality() const {
03148   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
03149     return IC->isEquality();
03150   return cast<FCmpInst>(this)->isEquality();
03151 }
03152 
03153 
03154 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
03155   switch (pred) {
03156     default: llvm_unreachable("Unknown cmp predicate!");
03157     case ICMP_EQ: return ICMP_NE;
03158     case ICMP_NE: return ICMP_EQ;
03159     case ICMP_UGT: return ICMP_ULE;
03160     case ICMP_ULT: return ICMP_UGE;
03161     case ICMP_UGE: return ICMP_ULT;
03162     case ICMP_ULE: return ICMP_UGT;
03163     case ICMP_SGT: return ICMP_SLE;
03164     case ICMP_SLT: return ICMP_SGE;
03165     case ICMP_SGE: return ICMP_SLT;
03166     case ICMP_SLE: return ICMP_SGT;
03167 
03168     case FCMP_OEQ: return FCMP_UNE;
03169     case FCMP_ONE: return FCMP_UEQ;
03170     case FCMP_OGT: return FCMP_ULE;
03171     case FCMP_OLT: return FCMP_UGE;
03172     case FCMP_OGE: return FCMP_ULT;
03173     case FCMP_OLE: return FCMP_UGT;
03174     case FCMP_UEQ: return FCMP_ONE;
03175     case FCMP_UNE: return FCMP_OEQ;
03176     case FCMP_UGT: return FCMP_OLE;
03177     case FCMP_ULT: return FCMP_OGE;
03178     case FCMP_UGE: return FCMP_OLT;
03179     case FCMP_ULE: return FCMP_OGT;
03180     case FCMP_ORD: return FCMP_UNO;
03181     case FCMP_UNO: return FCMP_ORD;
03182     case FCMP_TRUE: return FCMP_FALSE;
03183     case FCMP_FALSE: return FCMP_TRUE;
03184   }
03185 }
03186 
03187 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
03188   switch (pred) {
03189     default: llvm_unreachable("Unknown icmp predicate!");
03190     case ICMP_EQ: case ICMP_NE: 
03191     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
03192        return pred;
03193     case ICMP_UGT: return ICMP_SGT;
03194     case ICMP_ULT: return ICMP_SLT;
03195     case ICMP_UGE: return ICMP_SGE;
03196     case ICMP_ULE: return ICMP_SLE;
03197   }
03198 }
03199 
03200 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
03201   switch (pred) {
03202     default: llvm_unreachable("Unknown icmp predicate!");
03203     case ICMP_EQ: case ICMP_NE: 
03204     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
03205        return pred;
03206     case ICMP_SGT: return ICMP_UGT;
03207     case ICMP_SLT: return ICMP_ULT;
03208     case ICMP_SGE: return ICMP_UGE;
03209     case ICMP_SLE: return ICMP_ULE;
03210   }
03211 }
03212 
03213 /// Initialize a set of values that all satisfy the condition with C.
03214 ///
03215 ConstantRange 
03216 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
03217   APInt Lower(C);
03218   APInt Upper(C);
03219   uint32_t BitWidth = C.getBitWidth();
03220   switch (pred) {
03221   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
03222   case ICmpInst::ICMP_EQ: ++Upper; break;
03223   case ICmpInst::ICMP_NE: ++Lower; break;
03224   case ICmpInst::ICMP_ULT:
03225     Lower = APInt::getMinValue(BitWidth);
03226     // Check for an empty-set condition.
03227     if (Lower == Upper)
03228       return ConstantRange(BitWidth, /*isFullSet=*/false);
03229     break;
03230   case ICmpInst::ICMP_SLT:
03231     Lower = APInt::getSignedMinValue(BitWidth);
03232     // Check for an empty-set condition.
03233     if (Lower == Upper)
03234       return ConstantRange(BitWidth, /*isFullSet=*/false);
03235     break;
03236   case ICmpInst::ICMP_UGT: 
03237     ++Lower; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
03238     // Check for an empty-set condition.
03239     if (Lower == Upper)
03240       return ConstantRange(BitWidth, /*isFullSet=*/false);
03241     break;
03242   case ICmpInst::ICMP_SGT:
03243     ++Lower; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
03244     // Check for an empty-set condition.
03245     if (Lower == Upper)
03246       return ConstantRange(BitWidth, /*isFullSet=*/false);
03247     break;
03248   case ICmpInst::ICMP_ULE: 
03249     Lower = APInt::getMinValue(BitWidth); ++Upper; 
03250     // Check for a full-set condition.
03251     if (Lower == Upper)
03252       return ConstantRange(BitWidth, /*isFullSet=*/true);
03253     break;
03254   case ICmpInst::ICMP_SLE: 
03255     Lower = APInt::getSignedMinValue(BitWidth); ++Upper; 
03256     // Check for a full-set condition.
03257     if (Lower == Upper)
03258       return ConstantRange(BitWidth, /*isFullSet=*/true);
03259     break;
03260   case ICmpInst::ICMP_UGE:
03261     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
03262     // Check for a full-set condition.
03263     if (Lower == Upper)
03264       return ConstantRange(BitWidth, /*isFullSet=*/true);
03265     break;
03266   case ICmpInst::ICMP_SGE:
03267     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
03268     // Check for a full-set condition.
03269     if (Lower == Upper)
03270       return ConstantRange(BitWidth, /*isFullSet=*/true);
03271     break;
03272   }
03273   return ConstantRange(Lower, Upper);
03274 }
03275 
03276 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
03277   switch (pred) {
03278     default: llvm_unreachable("Unknown cmp predicate!");
03279     case ICMP_EQ: case ICMP_NE:
03280       return pred;
03281     case ICMP_SGT: return ICMP_SLT;
03282     case ICMP_SLT: return ICMP_SGT;
03283     case ICMP_SGE: return ICMP_SLE;
03284     case ICMP_SLE: return ICMP_SGE;
03285     case ICMP_UGT: return ICMP_ULT;
03286     case ICMP_ULT: return ICMP_UGT;
03287     case ICMP_UGE: return ICMP_ULE;
03288     case ICMP_ULE: return ICMP_UGE;
03289   
03290     case FCMP_FALSE: case FCMP_TRUE:
03291     case FCMP_OEQ: case FCMP_ONE:
03292     case FCMP_UEQ: case FCMP_UNE:
03293     case FCMP_ORD: case FCMP_UNO:
03294       return pred;
03295     case FCMP_OGT: return FCMP_OLT;
03296     case FCMP_OLT: return FCMP_OGT;
03297     case FCMP_OGE: return FCMP_OLE;
03298     case FCMP_OLE: return FCMP_OGE;
03299     case FCMP_UGT: return FCMP_ULT;
03300     case FCMP_ULT: return FCMP_UGT;
03301     case FCMP_UGE: return FCMP_ULE;
03302     case FCMP_ULE: return FCMP_UGE;
03303   }
03304 }
03305 
03306 bool CmpInst::isUnsigned(unsigned short predicate) {
03307   switch (predicate) {
03308     default: return false;
03309     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
03310     case ICmpInst::ICMP_UGE: return true;
03311   }
03312 }
03313 
03314 bool CmpInst::isSigned(unsigned short predicate) {
03315   switch (predicate) {
03316     default: return false;
03317     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
03318     case ICmpInst::ICMP_SGE: return true;
03319   }
03320 }
03321 
03322 bool CmpInst::isOrdered(unsigned short predicate) {
03323   switch (predicate) {
03324     default: return false;
03325     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
03326     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
03327     case FCmpInst::FCMP_ORD: return true;
03328   }
03329 }
03330       
03331 bool CmpInst::isUnordered(unsigned short predicate) {
03332   switch (predicate) {
03333     default: return false;
03334     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
03335     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
03336     case FCmpInst::FCMP_UNO: return true;
03337   }
03338 }
03339 
03340 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
03341   switch(predicate) {
03342     default: return false;
03343     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
03344     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
03345   }
03346 }
03347 
03348 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
03349   switch(predicate) {
03350   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
03351   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
03352   default: return false;
03353   }
03354 }
03355 
03356 
03357 //===----------------------------------------------------------------------===//
03358 //                        SwitchInst Implementation
03359 //===----------------------------------------------------------------------===//
03360 
03361 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
03362   assert(Value && Default && NumReserved);
03363   ReservedSpace = NumReserved;
03364   NumOperands = 2;
03365   OperandList = allocHungoffUses(ReservedSpace);
03366 
03367   OperandList[0] = Value;
03368   OperandList[1] = Default;
03369 }
03370 
03371 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
03372 /// switch on and a default destination.  The number of additional cases can
03373 /// be specified here to make memory allocation more efficient.  This
03374 /// constructor can also autoinsert before another instruction.
03375 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
03376                        Instruction *InsertBefore)
03377   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
03378                    nullptr, 0, InsertBefore) {
03379   init(Value, Default, 2+NumCases*2);
03380 }
03381 
03382 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
03383 /// switch on and a default destination.  The number of additional cases can
03384 /// be specified here to make memory allocation more efficient.  This
03385 /// constructor also autoinserts at the end of the specified BasicBlock.
03386 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
03387                        BasicBlock *InsertAtEnd)
03388   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
03389                    nullptr, 0, InsertAtEnd) {
03390   init(Value, Default, 2+NumCases*2);
03391 }
03392 
03393 SwitchInst::SwitchInst(const SwitchInst &SI)
03394   : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
03395   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
03396   NumOperands = SI.getNumOperands();
03397   Use *OL = OperandList, *InOL = SI.OperandList;
03398   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
03399     OL[i] = InOL[i];
03400     OL[i+1] = InOL[i+1];
03401   }
03402   SubclassOptionalData = SI.SubclassOptionalData;
03403 }
03404 
03405 SwitchInst::~SwitchInst() {
03406   dropHungoffUses();
03407 }
03408 
03409 
03410 /// addCase - Add an entry to the switch instruction...
03411 ///
03412 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
03413   unsigned NewCaseIdx = getNumCases(); 
03414   unsigned OpNo = NumOperands;
03415   if (OpNo+2 > ReservedSpace)
03416     growOperands();  // Get more space!
03417   // Initialize some new operands.
03418   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
03419   NumOperands = OpNo+2;
03420   CaseIt Case(this, NewCaseIdx);
03421   Case.setValue(OnVal);
03422   Case.setSuccessor(Dest);
03423 }
03424 
03425 /// removeCase - This method removes the specified case and its successor
03426 /// from the switch instruction.
03427 void SwitchInst::removeCase(CaseIt i) {
03428   unsigned idx = i.getCaseIndex();
03429   
03430   assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
03431 
03432   unsigned NumOps = getNumOperands();
03433   Use *OL = OperandList;
03434 
03435   // Overwrite this case with the end of the list.
03436   if (2 + (idx + 1) * 2 != NumOps) {
03437     OL[2 + idx * 2] = OL[NumOps - 2];
03438     OL[2 + idx * 2 + 1] = OL[NumOps - 1];
03439   }
03440 
03441   // Nuke the last value.
03442   OL[NumOps-2].set(nullptr);
03443   OL[NumOps-2+1].set(nullptr);
03444   NumOperands = NumOps-2;
03445 }
03446 
03447 /// growOperands - grow operands - This grows the operand list in response
03448 /// to a push_back style of operation.  This grows the number of ops by 3 times.
03449 ///
03450 void SwitchInst::growOperands() {
03451   unsigned e = getNumOperands();
03452   unsigned NumOps = e*3;
03453 
03454   ReservedSpace = NumOps;
03455   Use *NewOps = allocHungoffUses(NumOps);
03456   Use *OldOps = OperandList;
03457   for (unsigned i = 0; i != e; ++i) {
03458       NewOps[i] = OldOps[i];
03459   }
03460   OperandList = NewOps;
03461   Use::zap(OldOps, OldOps + e, true);
03462 }
03463 
03464 
03465 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
03466   return getSuccessor(idx);
03467 }
03468 unsigned SwitchInst::getNumSuccessorsV() const {
03469   return getNumSuccessors();
03470 }
03471 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
03472   setSuccessor(idx, B);
03473 }
03474 
03475 //===----------------------------------------------------------------------===//
03476 //                        IndirectBrInst Implementation
03477 //===----------------------------------------------------------------------===//
03478 
03479 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
03480   assert(Address && Address->getType()->isPointerTy() &&
03481          "Address of indirectbr must be a pointer");
03482   ReservedSpace = 1+NumDests;
03483   NumOperands = 1;
03484   OperandList = allocHungoffUses(ReservedSpace);
03485   
03486   OperandList[0] = Address;
03487 }
03488 
03489 
03490 /// growOperands - grow operands - This grows the operand list in response
03491 /// to a push_back style of operation.  This grows the number of ops by 2 times.
03492 ///
03493 void IndirectBrInst::growOperands() {
03494   unsigned e = getNumOperands();
03495   unsigned NumOps = e*2;
03496   
03497   ReservedSpace = NumOps;
03498   Use *NewOps = allocHungoffUses(NumOps);
03499   Use *OldOps = OperandList;
03500   for (unsigned i = 0; i != e; ++i)
03501     NewOps[i] = OldOps[i];
03502   OperandList = NewOps;
03503   Use::zap(OldOps, OldOps + e, true);
03504 }
03505 
03506 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
03507                                Instruction *InsertBefore)
03508 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
03509                  nullptr, 0, InsertBefore) {
03510   init(Address, NumCases);
03511 }
03512 
03513 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
03514                                BasicBlock *InsertAtEnd)
03515 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
03516                  nullptr, 0, InsertAtEnd) {
03517   init(Address, NumCases);
03518 }
03519 
03520 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
03521   : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
03522                    allocHungoffUses(IBI.getNumOperands()),
03523                    IBI.getNumOperands()) {
03524   Use *OL = OperandList, *InOL = IBI.OperandList;
03525   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
03526     OL[i] = InOL[i];
03527   SubclassOptionalData = IBI.SubclassOptionalData;
03528 }
03529 
03530 IndirectBrInst::~IndirectBrInst() {
03531   dropHungoffUses();
03532 }
03533 
03534 /// addDestination - Add a destination.
03535 ///
03536 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
03537   unsigned OpNo = NumOperands;
03538   if (OpNo+1 > ReservedSpace)
03539     growOperands();  // Get more space!
03540   // Initialize some new operands.
03541   assert(OpNo < ReservedSpace && "Growing didn't work!");
03542   NumOperands = OpNo+1;
03543   OperandList[OpNo] = DestBB;
03544 }
03545 
03546 /// removeDestination - This method removes the specified successor from the
03547 /// indirectbr instruction.
03548 void IndirectBrInst::removeDestination(unsigned idx) {
03549   assert(idx < getNumOperands()-1 && "Successor index out of range!");
03550   
03551   unsigned NumOps = getNumOperands();
03552   Use *OL = OperandList;
03553 
03554   // Replace this value with the last one.
03555   OL[idx+1] = OL[NumOps-1];
03556   
03557   // Nuke the last value.
03558   OL[NumOps-1].set(nullptr);
03559   NumOperands = NumOps-1;
03560 }
03561 
03562 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
03563   return getSuccessor(idx);
03564 }
03565 unsigned IndirectBrInst::getNumSuccessorsV() const {
03566   return getNumSuccessors();
03567 }
03568 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
03569   setSuccessor(idx, B);
03570 }
03571 
03572 //===----------------------------------------------------------------------===//
03573 //                           clone_impl() implementations
03574 //===----------------------------------------------------------------------===//
03575 
03576 // Define these methods here so vtables don't get emitted into every translation
03577 // unit that uses these classes.
03578 
03579 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
03580   return new (getNumOperands()) GetElementPtrInst(*this);
03581 }
03582 
03583 BinaryOperator *BinaryOperator::clone_impl() const {
03584   return Create(getOpcode(), Op<0>(), Op<1>());
03585 }
03586 
03587 FCmpInst* FCmpInst::clone_impl() const {
03588   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
03589 }
03590 
03591 ICmpInst* ICmpInst::clone_impl() const {
03592   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
03593 }
03594 
03595 ExtractValueInst *ExtractValueInst::clone_impl() const {
03596   return new ExtractValueInst(*this);
03597 }
03598 
03599 InsertValueInst *InsertValueInst::clone_impl() const {
03600   return new InsertValueInst(*this);
03601 }
03602 
03603 AllocaInst *AllocaInst::clone_impl() const {
03604   AllocaInst *Result = new AllocaInst(getAllocatedType(),
03605                                       (Value *)getOperand(0), getAlignment());
03606   Result->setUsedWithInAlloca(isUsedWithInAlloca());
03607   return Result;
03608 }
03609 
03610 LoadInst *LoadInst::clone_impl() const {
03611   return new LoadInst(getOperand(0), Twine(), isVolatile(),
03612                       getAlignment(), getOrdering(), getSynchScope());
03613 }
03614 
03615 StoreInst *StoreInst::clone_impl() const {
03616   return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
03617                        getAlignment(), getOrdering(), getSynchScope());
03618   
03619 }
03620 
03621 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
03622   AtomicCmpXchgInst *Result =
03623     new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
03624                           getSuccessOrdering(), getFailureOrdering(),
03625                           getSynchScope());
03626   Result->setVolatile(isVolatile());
03627   Result->setWeak(isWeak());
03628   return Result;
03629 }
03630 
03631 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
03632   AtomicRMWInst *Result =
03633     new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
03634                       getOrdering(), getSynchScope());
03635   Result->setVolatile(isVolatile());
03636   return Result;
03637 }
03638 
03639 FenceInst *FenceInst::clone_impl() const {
03640   return new FenceInst(getContext(), getOrdering(), getSynchScope());
03641 }
03642 
03643 TruncInst *TruncInst::clone_impl() const {
03644   return new TruncInst(getOperand(0), getType());
03645 }
03646 
03647 ZExtInst *ZExtInst::clone_impl() const {
03648   return new ZExtInst(getOperand(0), getType());
03649 }
03650 
03651 SExtInst *SExtInst::clone_impl() const {
03652   return new SExtInst(getOperand(0), getType());
03653 }
03654 
03655 FPTruncInst *FPTruncInst::clone_impl() const {
03656   return new FPTruncInst(getOperand(0), getType());
03657 }
03658 
03659 FPExtInst *FPExtInst::clone_impl() const {
03660   return new FPExtInst(getOperand(0), getType());
03661 }
03662 
03663 UIToFPInst *UIToFPInst::clone_impl() const {
03664   return new UIToFPInst(getOperand(0), getType());
03665 }
03666 
03667 SIToFPInst *SIToFPInst::clone_impl() const {
03668   return new SIToFPInst(getOperand(0), getType());
03669 }
03670 
03671 FPToUIInst *FPToUIInst::clone_impl() const {
03672   return new FPToUIInst(getOperand(0), getType());
03673 }
03674 
03675 FPToSIInst *FPToSIInst::clone_impl() const {
03676   return new FPToSIInst(getOperand(0), getType());
03677 }
03678 
03679 PtrToIntInst *PtrToIntInst::clone_impl() const {
03680   return new PtrToIntInst(getOperand(0), getType());
03681 }
03682 
03683 IntToPtrInst *IntToPtrInst::clone_impl() const {
03684   return new IntToPtrInst(getOperand(0), getType());
03685 }
03686 
03687 BitCastInst *BitCastInst::clone_impl() const {
03688   return new BitCastInst(getOperand(0), getType());
03689 }
03690 
03691 AddrSpaceCastInst *AddrSpaceCastInst::clone_impl() const {
03692   return new AddrSpaceCastInst(getOperand(0), getType());
03693 }
03694 
03695 CallInst *CallInst::clone_impl() const {
03696   return  new(getNumOperands()) CallInst(*this);
03697 }
03698 
03699 SelectInst *SelectInst::clone_impl() const {
03700   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
03701 }
03702 
03703 VAArgInst *VAArgInst::clone_impl() const {
03704   return new VAArgInst(getOperand(0), getType());
03705 }
03706 
03707 ExtractElementInst *ExtractElementInst::clone_impl() const {
03708   return ExtractElementInst::Create(getOperand(0), getOperand(1));
03709 }
03710 
03711 InsertElementInst *InsertElementInst::clone_impl() const {
03712   return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
03713 }
03714 
03715 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
03716   return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
03717 }
03718 
03719 PHINode *PHINode::clone_impl() const {
03720   return new PHINode(*this);
03721 }
03722 
03723 LandingPadInst *LandingPadInst::clone_impl() const {
03724   return new LandingPadInst(*this);
03725 }
03726 
03727 ReturnInst *ReturnInst::clone_impl() const {
03728   return new(getNumOperands()) ReturnInst(*this);
03729 }
03730 
03731 BranchInst *BranchInst::clone_impl() const {
03732   return new(getNumOperands()) BranchInst(*this);
03733 }
03734 
03735 SwitchInst *SwitchInst::clone_impl() const {
03736   return new SwitchInst(*this);
03737 }
03738 
03739 IndirectBrInst *IndirectBrInst::clone_impl() const {
03740   return new IndirectBrInst(*this);
03741 }
03742 
03743 
03744 InvokeInst *InvokeInst::clone_impl() const {
03745   return new(getNumOperands()) InvokeInst(*this);
03746 }
03747 
03748 ResumeInst *ResumeInst::clone_impl() const {
03749   return new(1) ResumeInst(*this);
03750 }
03751 
03752 UnreachableInst *UnreachableInst::clone_impl() const {
03753   LLVMContext &Context = getContext();
03754   return new UnreachableInst(Context);
03755 }