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