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