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