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