1 //===-- Instruction.cpp - Implement the Instruction class -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Instruction class for the IR library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Instruction.h"
15 #include "llvm/IR/CallSite.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IR/Operator.h"
20 #include "llvm/IR/Type.h"
23 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
24 Instruction *InsertBefore)
25 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
27 // If requested, insert this instruction into a basic block...
29 BasicBlock *BB = InsertBefore->getParent();
30 assert(BB && "Instruction to insert before is not in a basic block!");
31 BB->getInstList().insert(InsertBefore->getIterator(), this);
35 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
36 BasicBlock *InsertAtEnd)
37 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
39 // append this instruction into the basic block
40 assert(InsertAtEnd && "Basic block to append to may not be NULL!");
41 InsertAtEnd->getInstList().push_back(this);
45 // Out of line virtual method, so the vtable, etc has a home.
46 Instruction::~Instruction() {
47 assert(!Parent && "Instruction still linked in the program!");
48 if (hasMetadataHashEntry())
49 clearMetadataHashEntries();
53 void Instruction::setParent(BasicBlock *P) {
57 const Module *Instruction::getModule() const {
58 return getParent()->getModule();
61 Module *Instruction::getModule() {
62 return getParent()->getModule();
66 void Instruction::removeFromParent() {
67 getParent()->getInstList().remove(getIterator());
70 iplist<Instruction>::iterator Instruction::eraseFromParent() {
71 return getParent()->getInstList().erase(getIterator());
74 /// insertBefore - Insert an unlinked instructions into a basic block
75 /// immediately before the specified instruction.
76 void Instruction::insertBefore(Instruction *InsertPos) {
77 InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
80 /// insertAfter - Insert an unlinked instructions into a basic block
81 /// immediately after the specified instruction.
82 void Instruction::insertAfter(Instruction *InsertPos) {
83 InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
87 /// moveBefore - Unlink this instruction from its current basic block and
88 /// insert it into the basic block that MovePos lives in, right before
90 void Instruction::moveBefore(Instruction *MovePos) {
91 MovePos->getParent()->getInstList().splice(
92 MovePos->getIterator(), getParent()->getInstList(), getIterator());
95 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
96 /// operator which supports this flag. See LangRef.html for the meaning of this
98 void Instruction::setHasUnsafeAlgebra(bool B) {
99 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
100 cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
103 /// Set or clear the NoNaNs flag on this instruction, which must be an operator
104 /// which supports this flag. See LangRef.html for the meaning of this flag.
105 void Instruction::setHasNoNaNs(bool B) {
106 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
107 cast<FPMathOperator>(this)->setHasNoNaNs(B);
110 /// Set or clear the no-infs flag on this instruction, which must be an operator
111 /// which supports this flag. See LangRef.html for the meaning of this flag.
112 void Instruction::setHasNoInfs(bool B) {
113 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
114 cast<FPMathOperator>(this)->setHasNoInfs(B);
117 /// Set or clear the no-signed-zeros flag on this instruction, which must be an
118 /// operator which supports this flag. See LangRef.html for the meaning of this
120 void Instruction::setHasNoSignedZeros(bool B) {
121 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
122 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
125 /// Set or clear the allow-reciprocal flag on this instruction, which must be an
126 /// operator which supports this flag. See LangRef.html for the meaning of this
128 void Instruction::setHasAllowReciprocal(bool B) {
129 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
130 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
133 /// Convenience function for setting all the fast-math flags on this
134 /// instruction, which must be an operator which supports these flags. See
135 /// LangRef.html for the meaning of these flats.
136 void Instruction::setFastMathFlags(FastMathFlags FMF) {
137 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
138 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
141 void Instruction::copyFastMathFlags(FastMathFlags FMF) {
142 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
143 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
146 /// Determine whether the unsafe-algebra flag is set.
147 bool Instruction::hasUnsafeAlgebra() const {
148 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
149 return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
152 /// Determine whether the no-NaNs flag is set.
153 bool Instruction::hasNoNaNs() const {
154 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
155 return cast<FPMathOperator>(this)->hasNoNaNs();
158 /// Determine whether the no-infs flag is set.
159 bool Instruction::hasNoInfs() const {
160 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
161 return cast<FPMathOperator>(this)->hasNoInfs();
164 /// Determine whether the no-signed-zeros flag is set.
165 bool Instruction::hasNoSignedZeros() const {
166 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
167 return cast<FPMathOperator>(this)->hasNoSignedZeros();
170 /// Determine whether the allow-reciprocal flag is set.
171 bool Instruction::hasAllowReciprocal() const {
172 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
173 return cast<FPMathOperator>(this)->hasAllowReciprocal();
176 /// Convenience function for getting all the fast-math flags, which must be an
177 /// operator which supports these flags. See LangRef.html for the meaning of
179 FastMathFlags Instruction::getFastMathFlags() const {
180 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
181 return cast<FPMathOperator>(this)->getFastMathFlags();
184 /// Copy I's fast-math flags
185 void Instruction::copyFastMathFlags(const Instruction *I) {
186 copyFastMathFlags(I->getFastMathFlags());
190 const char *Instruction::getOpcodeName(unsigned OpCode) {
193 case Ret: return "ret";
194 case Br: return "br";
195 case Switch: return "switch";
196 case IndirectBr: return "indirectbr";
197 case Invoke: return "invoke";
198 case Resume: return "resume";
199 case Unreachable: return "unreachable";
200 case CleanupEndPad: return "cleanupendpad";
201 case CleanupRet: return "cleanupret";
202 case CatchEndPad: return "catchendpad";
203 case CatchRet: return "catchret";
204 case CatchPad: return "catchpad";
205 case TerminatePad: return "terminatepad";
207 // Standard binary operators...
208 case Add: return "add";
209 case FAdd: return "fadd";
210 case Sub: return "sub";
211 case FSub: return "fsub";
212 case Mul: return "mul";
213 case FMul: return "fmul";
214 case UDiv: return "udiv";
215 case SDiv: return "sdiv";
216 case FDiv: return "fdiv";
217 case URem: return "urem";
218 case SRem: return "srem";
219 case FRem: return "frem";
221 // Logical operators...
222 case And: return "and";
223 case Or : return "or";
224 case Xor: return "xor";
226 // Memory instructions...
227 case Alloca: return "alloca";
228 case Load: return "load";
229 case Store: return "store";
230 case AtomicCmpXchg: return "cmpxchg";
231 case AtomicRMW: return "atomicrmw";
232 case Fence: return "fence";
233 case GetElementPtr: return "getelementptr";
235 // Convert instructions...
236 case Trunc: return "trunc";
237 case ZExt: return "zext";
238 case SExt: return "sext";
239 case FPTrunc: return "fptrunc";
240 case FPExt: return "fpext";
241 case FPToUI: return "fptoui";
242 case FPToSI: return "fptosi";
243 case UIToFP: return "uitofp";
244 case SIToFP: return "sitofp";
245 case IntToPtr: return "inttoptr";
246 case PtrToInt: return "ptrtoint";
247 case BitCast: return "bitcast";
248 case AddrSpaceCast: return "addrspacecast";
250 // Other instructions...
251 case ICmp: return "icmp";
252 case FCmp: return "fcmp";
253 case PHI: return "phi";
254 case Select: return "select";
255 case Call: return "call";
256 case Shl: return "shl";
257 case LShr: return "lshr";
258 case AShr: return "ashr";
259 case VAArg: return "va_arg";
260 case ExtractElement: return "extractelement";
261 case InsertElement: return "insertelement";
262 case ShuffleVector: return "shufflevector";
263 case ExtractValue: return "extractvalue";
264 case InsertValue: return "insertvalue";
265 case LandingPad: return "landingpad";
266 case CleanupPad: return "cleanuppad";
268 default: return "<Invalid operator> ";
272 /// Return true if both instructions have the same special state
273 /// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp.
274 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
275 bool IgnoreAlignment = false) {
276 assert(I1->getOpcode() == I2->getOpcode() &&
277 "Can not compare special state of different instructions");
279 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
280 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
281 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
283 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
284 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
285 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
286 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
287 (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
289 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
290 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
291 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
292 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
293 if (const CallInst *CI = dyn_cast<CallInst>(I1))
294 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
295 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
296 CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
297 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
298 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
299 CI->getAttributes() ==
300 cast<InvokeInst>(I2)->getAttributes();
301 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
302 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
303 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
304 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
305 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
306 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
307 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
308 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
309 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
310 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
311 CXI->getSuccessOrdering() ==
312 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
313 CXI->getFailureOrdering() ==
314 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
315 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
316 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
317 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
318 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
319 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
320 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
325 /// isIdenticalTo - Return true if the specified instruction is exactly
326 /// identical to the current one. This means that all operands match and any
327 /// extra information (e.g. load is volatile) agree.
328 bool Instruction::isIdenticalTo(const Instruction *I) const {
329 return isIdenticalToWhenDefined(I) &&
330 SubclassOptionalData == I->SubclassOptionalData;
333 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
334 /// ignores the SubclassOptionalData flags, which specify conditions
335 /// under which the instruction's result is undefined.
336 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
337 if (getOpcode() != I->getOpcode() ||
338 getNumOperands() != I->getNumOperands() ||
339 getType() != I->getType())
342 // If both instructions have no operands, they are identical.
343 if (getNumOperands() == 0 && I->getNumOperands() == 0)
344 return haveSameSpecialState(this, I);
346 // We have two instructions of identical opcode and #operands. Check to see
347 // if all operands are the same.
348 if (!std::equal(op_begin(), op_end(), I->op_begin()))
351 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
352 const PHINode *otherPHI = cast<PHINode>(I);
353 return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
354 otherPHI->block_begin());
357 return haveSameSpecialState(this, I);
361 // This should be kept in sync with isEquivalentOperation in
362 // lib/Transforms/IPO/MergeFunctions.cpp.
363 bool Instruction::isSameOperationAs(const Instruction *I,
364 unsigned flags) const {
365 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
366 bool UseScalarTypes = flags & CompareUsingScalarTypes;
368 if (getOpcode() != I->getOpcode() ||
369 getNumOperands() != I->getNumOperands() ||
371 getType()->getScalarType() != I->getType()->getScalarType() :
372 getType() != I->getType()))
375 // We have two instructions of identical opcode and #operands. Check to see
376 // if all operands are the same type
377 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
379 getOperand(i)->getType()->getScalarType() !=
380 I->getOperand(i)->getType()->getScalarType() :
381 getOperand(i)->getType() != I->getOperand(i)->getType())
384 return haveSameSpecialState(this, I, IgnoreAlignment);
387 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
388 /// specified block. Note that PHI nodes are considered to evaluate their
389 /// operands in the corresponding predecessor block.
390 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
391 for (const Use &U : uses()) {
392 // PHI nodes uses values in the corresponding predecessor block. For other
393 // instructions, just check to see whether the parent of the use matches up.
394 const Instruction *I = cast<Instruction>(U.getUser());
395 const PHINode *PN = dyn_cast<PHINode>(I);
397 if (I->getParent() != BB)
402 if (PN->getIncomingBlock(U) != BB)
408 /// mayReadFromMemory - Return true if this instruction may read memory.
410 bool Instruction::mayReadFromMemory() const {
411 switch (getOpcode()) {
412 default: return false;
413 case Instruction::VAArg:
414 case Instruction::Load:
415 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
416 case Instruction::AtomicCmpXchg:
417 case Instruction::AtomicRMW:
418 case Instruction::CatchPad:
419 case Instruction::CatchRet:
420 case Instruction::TerminatePad:
422 case Instruction::Call:
423 return !cast<CallInst>(this)->doesNotAccessMemory();
424 case Instruction::Invoke:
425 return !cast<InvokeInst>(this)->doesNotAccessMemory();
426 case Instruction::Store:
427 return !cast<StoreInst>(this)->isUnordered();
431 /// mayWriteToMemory - Return true if this instruction may modify memory.
433 bool Instruction::mayWriteToMemory() const {
434 switch (getOpcode()) {
435 default: return false;
436 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
437 case Instruction::Store:
438 case Instruction::VAArg:
439 case Instruction::AtomicCmpXchg:
440 case Instruction::AtomicRMW:
441 case Instruction::CatchPad:
442 case Instruction::CatchRet:
443 case Instruction::TerminatePad:
445 case Instruction::Call:
446 return !cast<CallInst>(this)->onlyReadsMemory();
447 case Instruction::Invoke:
448 return !cast<InvokeInst>(this)->onlyReadsMemory();
449 case Instruction::Load:
450 return !cast<LoadInst>(this)->isUnordered();
454 bool Instruction::isAtomic() const {
455 switch (getOpcode()) {
458 case Instruction::AtomicCmpXchg:
459 case Instruction::AtomicRMW:
460 case Instruction::Fence:
462 case Instruction::Load:
463 return cast<LoadInst>(this)->getOrdering() != NotAtomic;
464 case Instruction::Store:
465 return cast<StoreInst>(this)->getOrdering() != NotAtomic;
469 bool Instruction::mayThrow() const {
470 if (const CallInst *CI = dyn_cast<CallInst>(this))
471 return !CI->doesNotThrow();
472 if (const auto *CRI = dyn_cast<CleanupReturnInst>(this))
473 return CRI->unwindsToCaller();
474 if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(this))
475 return CEPI->unwindsToCaller();
476 if (const auto *CEPI = dyn_cast<CatchEndPadInst>(this))
477 return CEPI->unwindsToCaller();
478 if (const auto *TPI = dyn_cast<TerminatePadInst>(this))
479 return TPI->unwindsToCaller();
480 return isa<ResumeInst>(this);
483 bool Instruction::mayReturn() const {
484 if (const CallInst *CI = dyn_cast<CallInst>(this))
485 return !CI->doesNotReturn();
489 /// isAssociative - Return true if the instruction is associative:
491 /// Associative operators satisfy: x op (y op z) === (x op y) op z
493 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
495 bool Instruction::isAssociative(unsigned Opcode) {
496 return Opcode == And || Opcode == Or || Opcode == Xor ||
497 Opcode == Add || Opcode == Mul;
500 bool Instruction::isAssociative() const {
501 unsigned Opcode = getOpcode();
502 if (isAssociative(Opcode))
508 return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
514 /// isCommutative - Return true if the instruction is commutative:
516 /// Commutative operators satisfy: (x op y) === (y op x)
518 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
519 /// applied to any type.
521 bool Instruction::isCommutative(unsigned op) {
536 /// isIdempotent - Return true if the instruction is idempotent:
538 /// Idempotent operators satisfy: x op x === x
540 /// In LLVM, the And and Or operators are idempotent.
542 bool Instruction::isIdempotent(unsigned Opcode) {
543 return Opcode == And || Opcode == Or;
546 /// isNilpotent - Return true if the instruction is nilpotent:
548 /// Nilpotent operators satisfy: x op x === Id,
550 /// where Id is the identity for the operator, i.e. a constant such that
551 /// x op Id === x and Id op x === x for all x.
553 /// In LLVM, the Xor operator is nilpotent.
555 bool Instruction::isNilpotent(unsigned Opcode) {
556 return Opcode == Xor;
559 Instruction *Instruction::cloneImpl() const {
560 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
563 Instruction *Instruction::clone() const {
564 Instruction *New = nullptr;
565 switch (getOpcode()) {
567 llvm_unreachable("Unhandled Opcode.");
568 #define HANDLE_INST(num, opc, clas) \
569 case Instruction::opc: \
570 New = cast<clas>(this)->cloneImpl(); \
572 #include "llvm/IR/Instruction.def"
576 New->SubclassOptionalData = SubclassOptionalData;
580 // Otherwise, enumerate and copy over metadata from the old instruction to the
582 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
583 getAllMetadataOtherThanDebugLoc(TheMDs);
584 for (const auto &MD : TheMDs)
585 New->setMetadata(MD.first, MD.second);
587 New->setDebugLoc(getDebugLoc());