LLVM API Documentation

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