LLVM API Documentation

Instruction.cpp
Go to the documentation of this file.
00001 //===-- Instruction.cpp - Implement the Instruction class -----------------===//
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 the Instruction class for the IR library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Instruction.h"
00015 #include "llvm/IR/CallSite.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/Instructions.h"
00018 #include "llvm/IR/Module.h"
00019 #include "llvm/IR/Operator.h"
00020 #include "llvm/IR/Type.h"
00021 using namespace llvm;
00022 
00023 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
00024                          Instruction *InsertBefore)
00025   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
00026 
00027   // If requested, insert this instruction into a basic block...
00028   if (InsertBefore) {
00029     assert(InsertBefore->getParent() &&
00030            "Instruction to insert before is not in a basic block!");
00031     InsertBefore->getParent()->getInstList().insert(InsertBefore, this);
00032   }
00033 }
00034 
00035 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
00036                          BasicBlock *InsertAtEnd)
00037   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
00038 
00039   // append this instruction into the basic block
00040   assert(InsertAtEnd && "Basic block to append to may not be NULL!");
00041   InsertAtEnd->getInstList().push_back(this);
00042 }
00043 
00044 
00045 // Out of line virtual method, so the vtable, etc has a home.
00046 Instruction::~Instruction() {
00047   assert(!Parent && "Instruction still linked in the program!");
00048   if (hasMetadataHashEntry())
00049     clearMetadataHashEntries();
00050 }
00051 
00052 
00053 void Instruction::setParent(BasicBlock *P) {
00054   Parent = P;
00055 }
00056 
00057 const Module *Instruction::getModule() const {
00058   return getParent()->getModule();
00059 }
00060 
00061 void Instruction::removeFromParent() {
00062   getParent()->getInstList().remove(this);
00063 }
00064 
00065 void Instruction::eraseFromParent() {
00066   getParent()->getInstList().erase(this);
00067 }
00068 
00069 /// insertBefore - Insert an unlinked instructions into a basic block
00070 /// immediately before the specified instruction.
00071 void Instruction::insertBefore(Instruction *InsertPos) {
00072   InsertPos->getParent()->getInstList().insert(InsertPos, this);
00073 }
00074 
00075 /// insertAfter - Insert an unlinked instructions into a basic block
00076 /// immediately after the specified instruction.
00077 void Instruction::insertAfter(Instruction *InsertPos) {
00078   InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
00079 }
00080 
00081 /// moveBefore - Unlink this instruction from its current basic block and
00082 /// insert it into the basic block that MovePos lives in, right before
00083 /// MovePos.
00084 void Instruction::moveBefore(Instruction *MovePos) {
00085   MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
00086                                              this);
00087 }
00088 
00089 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
00090 /// operator which supports this flag. See LangRef.html for the meaning of this
00091 /// flag.
00092 void Instruction::setHasUnsafeAlgebra(bool B) {
00093   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00094   cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
00095 }
00096 
00097 /// Set or clear the NoNaNs flag on this instruction, which must be an operator
00098 /// which supports this flag. See LangRef.html for the meaning of this flag.
00099 void Instruction::setHasNoNaNs(bool B) {
00100   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00101   cast<FPMathOperator>(this)->setHasNoNaNs(B);
00102 }
00103 
00104 /// Set or clear the no-infs flag on this instruction, which must be an operator
00105 /// which supports this flag. See LangRef.html for the meaning of this flag.
00106 void Instruction::setHasNoInfs(bool B) {
00107   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00108   cast<FPMathOperator>(this)->setHasNoInfs(B);
00109 }
00110 
00111 /// Set or clear the no-signed-zeros flag on this instruction, which must be an
00112 /// operator which supports this flag. See LangRef.html for the meaning of this
00113 /// flag.
00114 void Instruction::setHasNoSignedZeros(bool B) {
00115   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00116   cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
00117 }
00118 
00119 /// Set or clear the allow-reciprocal flag on this instruction, which must be an
00120 /// operator which supports this flag. See LangRef.html for the meaning of this
00121 /// flag.
00122 void Instruction::setHasAllowReciprocal(bool B) {
00123   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00124   cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
00125 }
00126 
00127 /// Convenience function for setting all the fast-math flags on this
00128 /// instruction, which must be an operator which supports these flags. See
00129 /// LangRef.html for the meaning of these flats.
00130 void Instruction::setFastMathFlags(FastMathFlags FMF) {
00131   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
00132   cast<FPMathOperator>(this)->setFastMathFlags(FMF);
00133 }
00134 
00135 void Instruction::copyFastMathFlags(FastMathFlags FMF) {
00136   assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
00137   cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
00138 }
00139 
00140 /// Determine whether the unsafe-algebra flag is set.
00141 bool Instruction::hasUnsafeAlgebra() const {
00142   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00143   return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
00144 }
00145 
00146 /// Determine whether the no-NaNs flag is set.
00147 bool Instruction::hasNoNaNs() const {
00148   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00149   return cast<FPMathOperator>(this)->hasNoNaNs();
00150 }
00151 
00152 /// Determine whether the no-infs flag is set.
00153 bool Instruction::hasNoInfs() const {
00154   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00155   return cast<FPMathOperator>(this)->hasNoInfs();
00156 }
00157 
00158 /// Determine whether the no-signed-zeros flag is set.
00159 bool Instruction::hasNoSignedZeros() const {
00160   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00161   return cast<FPMathOperator>(this)->hasNoSignedZeros();
00162 }
00163 
00164 /// Determine whether the allow-reciprocal flag is set.
00165 bool Instruction::hasAllowReciprocal() const {
00166   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00167   return cast<FPMathOperator>(this)->hasAllowReciprocal();
00168 }
00169 
00170 /// Convenience function for getting all the fast-math flags, which must be an
00171 /// operator which supports these flags. See LangRef.html for the meaning of
00172 /// these flags.
00173 FastMathFlags Instruction::getFastMathFlags() const {
00174   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
00175   return cast<FPMathOperator>(this)->getFastMathFlags();
00176 }
00177 
00178 /// Copy I's fast-math flags
00179 void Instruction::copyFastMathFlags(const Instruction *I) {
00180   copyFastMathFlags(I->getFastMathFlags());
00181 }
00182 
00183 
00184 const char *Instruction::getOpcodeName(unsigned OpCode) {
00185   switch (OpCode) {
00186   // Terminators
00187   case Ret:    return "ret";
00188   case Br:     return "br";
00189   case Switch: return "switch";
00190   case IndirectBr: return "indirectbr";
00191   case Invoke: return "invoke";
00192   case Resume: return "resume";
00193   case Unreachable: return "unreachable";
00194 
00195   // Standard binary operators...
00196   case Add: return "add";
00197   case FAdd: return "fadd";
00198   case Sub: return "sub";
00199   case FSub: return "fsub";
00200   case Mul: return "mul";
00201   case FMul: return "fmul";
00202   case UDiv: return "udiv";
00203   case SDiv: return "sdiv";
00204   case FDiv: return "fdiv";
00205   case URem: return "urem";
00206   case SRem: return "srem";
00207   case FRem: return "frem";
00208 
00209   // Logical operators...
00210   case And: return "and";
00211   case Or : return "or";
00212   case Xor: return "xor";
00213 
00214   // Memory instructions...
00215   case Alloca:        return "alloca";
00216   case Load:          return "load";
00217   case Store:         return "store";
00218   case AtomicCmpXchg: return "cmpxchg";
00219   case AtomicRMW:     return "atomicrmw";
00220   case Fence:         return "fence";
00221   case GetElementPtr: return "getelementptr";
00222 
00223   // Convert instructions...
00224   case Trunc:         return "trunc";
00225   case ZExt:          return "zext";
00226   case SExt:          return "sext";
00227   case FPTrunc:       return "fptrunc";
00228   case FPExt:         return "fpext";
00229   case FPToUI:        return "fptoui";
00230   case FPToSI:        return "fptosi";
00231   case UIToFP:        return "uitofp";
00232   case SIToFP:        return "sitofp";
00233   case IntToPtr:      return "inttoptr";
00234   case PtrToInt:      return "ptrtoint";
00235   case BitCast:       return "bitcast";
00236   case AddrSpaceCast: return "addrspacecast";
00237 
00238   // Other instructions...
00239   case ICmp:           return "icmp";
00240   case FCmp:           return "fcmp";
00241   case PHI:            return "phi";
00242   case Select:         return "select";
00243   case Call:           return "call";
00244   case Shl:            return "shl";
00245   case LShr:           return "lshr";
00246   case AShr:           return "ashr";
00247   case VAArg:          return "va_arg";
00248   case ExtractElement: return "extractelement";
00249   case InsertElement:  return "insertelement";
00250   case ShuffleVector:  return "shufflevector";
00251   case ExtractValue:   return "extractvalue";
00252   case InsertValue:    return "insertvalue";
00253   case LandingPad:     return "landingpad";
00254 
00255   default: return "<Invalid operator> ";
00256   }
00257 }
00258 
00259 /// Return true if both instructions have the same special state
00260 /// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp.
00261 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
00262                                  bool IgnoreAlignment = false) {
00263   assert(I1->getOpcode() == I2->getOpcode() &&
00264          "Can not compare special state of different instructions");
00265 
00266   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
00267     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
00268            (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
00269             IgnoreAlignment) &&
00270            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
00271            LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
00272   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
00273     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
00274            (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
00275             IgnoreAlignment) &&
00276            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
00277            SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
00278   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
00279     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
00280   if (const CallInst *CI = dyn_cast<CallInst>(I1))
00281     return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
00282            CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
00283            CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
00284   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
00285     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
00286            CI->getAttributes() ==
00287              cast<InvokeInst>(I2)->getAttributes();
00288   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
00289     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
00290   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
00291     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
00292   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
00293     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
00294            FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
00295   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
00296     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
00297            CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
00298            CXI->getSuccessOrdering() ==
00299                cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
00300            CXI->getFailureOrdering() ==
00301                cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
00302            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
00303   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
00304     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
00305            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
00306            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
00307            RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
00308 
00309   return true;
00310 }
00311 
00312 /// isIdenticalTo - Return true if the specified instruction is exactly
00313 /// identical to the current one.  This means that all operands match and any
00314 /// extra information (e.g. load is volatile) agree.
00315 bool Instruction::isIdenticalTo(const Instruction *I) const {
00316   return isIdenticalToWhenDefined(I) &&
00317          SubclassOptionalData == I->SubclassOptionalData;
00318 }
00319 
00320 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
00321 /// ignores the SubclassOptionalData flags, which specify conditions
00322 /// under which the instruction's result is undefined.
00323 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
00324   if (getOpcode() != I->getOpcode() ||
00325       getNumOperands() != I->getNumOperands() ||
00326       getType() != I->getType())
00327     return false;
00328 
00329   // If both instructions have no operands, they are identical.
00330   if (getNumOperands() == 0 && I->getNumOperands() == 0)
00331     return haveSameSpecialState(this, I);
00332 
00333   // We have two instructions of identical opcode and #operands.  Check to see
00334   // if all operands are the same.
00335   if (!std::equal(op_begin(), op_end(), I->op_begin()))
00336     return false;
00337 
00338   if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
00339     const PHINode *otherPHI = cast<PHINode>(I);
00340     return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
00341                       otherPHI->block_begin());
00342   }
00343 
00344   return haveSameSpecialState(this, I);
00345 }
00346 
00347 // isSameOperationAs
00348 // This should be kept in sync with isEquivalentOperation in
00349 // lib/Transforms/IPO/MergeFunctions.cpp.
00350 bool Instruction::isSameOperationAs(const Instruction *I,
00351                                     unsigned flags) const {
00352   bool IgnoreAlignment = flags & CompareIgnoringAlignment;
00353   bool UseScalarTypes  = flags & CompareUsingScalarTypes;
00354 
00355   if (getOpcode() != I->getOpcode() ||
00356       getNumOperands() != I->getNumOperands() ||
00357       (UseScalarTypes ?
00358        getType()->getScalarType() != I->getType()->getScalarType() :
00359        getType() != I->getType()))
00360     return false;
00361 
00362   // We have two instructions of identical opcode and #operands.  Check to see
00363   // if all operands are the same type
00364   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00365     if (UseScalarTypes ?
00366         getOperand(i)->getType()->getScalarType() !=
00367           I->getOperand(i)->getType()->getScalarType() :
00368         getOperand(i)->getType() != I->getOperand(i)->getType())
00369       return false;
00370 
00371   return haveSameSpecialState(this, I, IgnoreAlignment);
00372 }
00373 
00374 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
00375 /// specified block.  Note that PHI nodes are considered to evaluate their
00376 /// operands in the corresponding predecessor block.
00377 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
00378   for (const Use &U : uses()) {
00379     // PHI nodes uses values in the corresponding predecessor block.  For other
00380     // instructions, just check to see whether the parent of the use matches up.
00381     const Instruction *I = cast<Instruction>(U.getUser());
00382     const PHINode *PN = dyn_cast<PHINode>(I);
00383     if (!PN) {
00384       if (I->getParent() != BB)
00385         return true;
00386       continue;
00387     }
00388 
00389     if (PN->getIncomingBlock(U) != BB)
00390       return true;
00391   }
00392   return false;
00393 }
00394 
00395 /// mayReadFromMemory - Return true if this instruction may read memory.
00396 ///
00397 bool Instruction::mayReadFromMemory() const {
00398   switch (getOpcode()) {
00399   default: return false;
00400   case Instruction::VAArg:
00401   case Instruction::Load:
00402   case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
00403   case Instruction::AtomicCmpXchg:
00404   case Instruction::AtomicRMW:
00405     return true;
00406   case Instruction::Call:
00407     return !cast<CallInst>(this)->doesNotAccessMemory();
00408   case Instruction::Invoke:
00409     return !cast<InvokeInst>(this)->doesNotAccessMemory();
00410   case Instruction::Store:
00411     return !cast<StoreInst>(this)->isUnordered();
00412   }
00413 }
00414 
00415 /// mayWriteToMemory - Return true if this instruction may modify memory.
00416 ///
00417 bool Instruction::mayWriteToMemory() const {
00418   switch (getOpcode()) {
00419   default: return false;
00420   case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
00421   case Instruction::Store:
00422   case Instruction::VAArg:
00423   case Instruction::AtomicCmpXchg:
00424   case Instruction::AtomicRMW:
00425     return true;
00426   case Instruction::Call:
00427     return !cast<CallInst>(this)->onlyReadsMemory();
00428   case Instruction::Invoke:
00429     return !cast<InvokeInst>(this)->onlyReadsMemory();
00430   case Instruction::Load:
00431     return !cast<LoadInst>(this)->isUnordered();
00432   }
00433 }
00434 
00435 bool Instruction::isAtomic() const {
00436   switch (getOpcode()) {
00437   default:
00438     return false;
00439   case Instruction::AtomicCmpXchg:
00440   case Instruction::AtomicRMW:
00441   case Instruction::Fence:
00442     return true;
00443   case Instruction::Load:
00444     return cast<LoadInst>(this)->getOrdering() != NotAtomic;
00445   case Instruction::Store:
00446     return cast<StoreInst>(this)->getOrdering() != NotAtomic;
00447   }
00448 }
00449 
00450 bool Instruction::mayThrow() const {
00451   if (const CallInst *CI = dyn_cast<CallInst>(this))
00452     return !CI->doesNotThrow();
00453   return isa<ResumeInst>(this);
00454 }
00455 
00456 bool Instruction::mayReturn() const {
00457   if (const CallInst *CI = dyn_cast<CallInst>(this))
00458     return !CI->doesNotReturn();
00459   return true;
00460 }
00461 
00462 /// isAssociative - Return true if the instruction is associative:
00463 ///
00464 ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
00465 ///
00466 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
00467 ///
00468 bool Instruction::isAssociative(unsigned Opcode) {
00469   return Opcode == And || Opcode == Or || Opcode == Xor ||
00470          Opcode == Add || Opcode == Mul;
00471 }
00472 
00473 bool Instruction::isAssociative() const {
00474   unsigned Opcode = getOpcode();
00475   if (isAssociative(Opcode))
00476     return true;
00477 
00478   switch (Opcode) {
00479   case FMul:
00480   case FAdd:
00481     return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
00482   default:
00483     return false;
00484   }
00485 }
00486 
00487 /// isCommutative - Return true if the instruction is commutative:
00488 ///
00489 ///   Commutative operators satisfy: (x op y) === (y op x)
00490 ///
00491 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
00492 /// applied to any type.
00493 ///
00494 bool Instruction::isCommutative(unsigned op) {
00495   switch (op) {
00496   case Add:
00497   case FAdd:
00498   case Mul:
00499   case FMul:
00500   case And:
00501   case Or:
00502   case Xor:
00503     return true;
00504   default:
00505     return false;
00506   }
00507 }
00508 
00509 /// isIdempotent - Return true if the instruction is idempotent:
00510 ///
00511 ///   Idempotent operators satisfy:  x op x === x
00512 ///
00513 /// In LLVM, the And and Or operators are idempotent.
00514 ///
00515 bool Instruction::isIdempotent(unsigned Opcode) {
00516   return Opcode == And || Opcode == Or;
00517 }
00518 
00519 /// isNilpotent - Return true if the instruction is nilpotent:
00520 ///
00521 ///   Nilpotent operators satisfy:  x op x === Id,
00522 ///
00523 ///   where Id is the identity for the operator, i.e. a constant such that
00524 ///     x op Id === x and Id op x === x for all x.
00525 ///
00526 /// In LLVM, the Xor operator is nilpotent.
00527 ///
00528 bool Instruction::isNilpotent(unsigned Opcode) {
00529   return Opcode == Xor;
00530 }
00531 
00532 Instruction *Instruction::clone() const {
00533   Instruction *New = clone_impl();
00534   New->SubclassOptionalData = SubclassOptionalData;
00535   if (!hasMetadata())
00536     return New;
00537 
00538   // Otherwise, enumerate and copy over metadata from the old instruction to the
00539   // new one.
00540   SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
00541   getAllMetadataOtherThanDebugLoc(TheMDs);
00542   for (const auto &MD : TheMDs)
00543     New->setMetadata(MD.first, MD.second);
00544 
00545   New->setDebugLoc(getDebugLoc());
00546   return New;
00547 }