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 assert(InsertBefore->getParent() &&
30 "Instruction to insert before is not in a basic block!");
31 InsertBefore->getParent()->getInstList().insert(InsertBefore, 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 void Instruction::removeFromParent() {
62 getParent()->getInstList().remove(this);
65 iplist<Instruction>::iterator Instruction::eraseFromParent() {
66 return getParent()->getInstList().erase(this);
69 /// insertBefore - Insert an unlinked instructions into a basic block
70 /// immediately before the specified instruction.
71 void Instruction::insertBefore(Instruction *InsertPos) {
72 InsertPos->getParent()->getInstList().insert(InsertPos, this);
75 /// insertAfter - Insert an unlinked instructions into a basic block
76 /// immediately after the specified instruction.
77 void Instruction::insertAfter(Instruction *InsertPos) {
78 InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
81 /// moveBefore - Unlink this instruction from its current basic block and
82 /// insert it into the basic block that MovePos lives in, right before
84 void Instruction::moveBefore(Instruction *MovePos) {
85 MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
89 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
90 /// operator which supports this flag. See LangRef.html for the meaning of this
92 void Instruction::setHasUnsafeAlgebra(bool B) {
93 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
94 cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
97 /// Set or clear the NoNaNs flag on this instruction, which must be an operator
98 /// which supports this flag. See LangRef.html for the meaning of this flag.
99 void Instruction::setHasNoNaNs(bool B) {
100 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
101 cast<FPMathOperator>(this)->setHasNoNaNs(B);
104 /// Set or clear the no-infs flag on this instruction, which must be an operator
105 /// which supports this flag. See LangRef.html for the meaning of this flag.
106 void Instruction::setHasNoInfs(bool B) {
107 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
108 cast<FPMathOperator>(this)->setHasNoInfs(B);
111 /// Set or clear the no-signed-zeros flag on this instruction, which must be an
112 /// operator which supports this flag. See LangRef.html for the meaning of this
114 void Instruction::setHasNoSignedZeros(bool B) {
115 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
116 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
119 /// Set or clear the allow-reciprocal flag on this instruction, which must be an
120 /// operator which supports this flag. See LangRef.html for the meaning of this
122 void Instruction::setHasAllowReciprocal(bool B) {
123 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
124 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
127 /// Convenience function for setting all the fast-math flags on this
128 /// instruction, which must be an operator which supports these flags. See
129 /// LangRef.html for the meaning of these flats.
130 void Instruction::setFastMathFlags(FastMathFlags FMF) {
131 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
132 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
135 void Instruction::copyFastMathFlags(FastMathFlags FMF) {
136 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
137 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
140 /// Determine whether the unsafe-algebra flag is set.
141 bool Instruction::hasUnsafeAlgebra() const {
142 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
143 return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
146 /// Determine whether the no-NaNs flag is set.
147 bool Instruction::hasNoNaNs() const {
148 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
149 return cast<FPMathOperator>(this)->hasNoNaNs();
152 /// Determine whether the no-infs flag is set.
153 bool Instruction::hasNoInfs() const {
154 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
155 return cast<FPMathOperator>(this)->hasNoInfs();
158 /// Determine whether the no-signed-zeros flag is set.
159 bool Instruction::hasNoSignedZeros() const {
160 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
161 return cast<FPMathOperator>(this)->hasNoSignedZeros();
164 /// Determine whether the allow-reciprocal flag is set.
165 bool Instruction::hasAllowReciprocal() const {
166 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
167 return cast<FPMathOperator>(this)->hasAllowReciprocal();
170 /// Convenience function for getting all the fast-math flags, which must be an
171 /// operator which supports these flags. See LangRef.html for the meaning of
173 FastMathFlags Instruction::getFastMathFlags() const {
174 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
175 return cast<FPMathOperator>(this)->getFastMathFlags();
178 /// Copy I's fast-math flags
179 void Instruction::copyFastMathFlags(const Instruction *I) {
180 copyFastMathFlags(I->getFastMathFlags());
184 const char *Instruction::getOpcodeName(unsigned OpCode) {
187 case Ret: return "ret";
188 case Br: return "br";
189 case Switch: return "switch";
190 case IndirectBr: return "indirectbr";
191 case Invoke: return "invoke";
192 case Resume: return "resume";
193 case Unreachable: return "unreachable";
195 // Standard binary operators...
196 case Add: return "add";
197 case FAdd: return "fadd";
198 case Sub: return "sub";
199 case FSub: return "fsub";
200 case Mul: return "mul";
201 case FMul: return "fmul";
202 case UDiv: return "udiv";
203 case SDiv: return "sdiv";
204 case FDiv: return "fdiv";
205 case URem: return "urem";
206 case SRem: return "srem";
207 case FRem: return "frem";
209 // Logical operators...
210 case And: return "and";
211 case Or : return "or";
212 case Xor: return "xor";
214 // Memory instructions...
215 case Alloca: return "alloca";
216 case Load: return "load";
217 case Store: return "store";
218 case AtomicCmpXchg: return "cmpxchg";
219 case AtomicRMW: return "atomicrmw";
220 case Fence: return "fence";
221 case GetElementPtr: return "getelementptr";
223 // Convert instructions...
224 case Trunc: return "trunc";
225 case ZExt: return "zext";
226 case SExt: return "sext";
227 case FPTrunc: return "fptrunc";
228 case FPExt: return "fpext";
229 case FPToUI: return "fptoui";
230 case FPToSI: return "fptosi";
231 case UIToFP: return "uitofp";
232 case SIToFP: return "sitofp";
233 case IntToPtr: return "inttoptr";
234 case PtrToInt: return "ptrtoint";
235 case BitCast: return "bitcast";
236 case AddrSpaceCast: return "addrspacecast";
238 // Other instructions...
239 case ICmp: return "icmp";
240 case FCmp: return "fcmp";
241 case PHI: return "phi";
242 case Select: return "select";
243 case Call: return "call";
244 case Shl: return "shl";
245 case LShr: return "lshr";
246 case AShr: return "ashr";
247 case VAArg: return "va_arg";
248 case ExtractElement: return "extractelement";
249 case InsertElement: return "insertelement";
250 case ShuffleVector: return "shufflevector";
251 case ExtractValue: return "extractvalue";
252 case InsertValue: return "insertvalue";
253 case LandingPad: return "landingpad";
255 default: return "<Invalid operator> ";
259 /// Return true if both instructions have the same special state
260 /// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp.
261 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
262 bool IgnoreAlignment = false) {
263 assert(I1->getOpcode() == I2->getOpcode() &&
264 "Can not compare special state of different instructions");
266 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
267 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
268 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
270 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
271 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
272 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
273 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
274 (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
276 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
277 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
278 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
279 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
280 if (const CallInst *CI = dyn_cast<CallInst>(I1))
281 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
282 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
283 CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
284 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
285 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
286 CI->getAttributes() ==
287 cast<InvokeInst>(I2)->getAttributes();
288 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
289 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
290 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
291 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
292 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
293 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
294 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
295 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
296 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
297 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
298 CXI->getSuccessOrdering() ==
299 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
300 CXI->getFailureOrdering() ==
301 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
302 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
303 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
304 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
305 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
306 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
307 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
312 /// isIdenticalTo - Return true if the specified instruction is exactly
313 /// identical to the current one. This means that all operands match and any
314 /// extra information (e.g. load is volatile) agree.
315 bool Instruction::isIdenticalTo(const Instruction *I) const {
316 return isIdenticalToWhenDefined(I) &&
317 SubclassOptionalData == I->SubclassOptionalData;
320 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
321 /// ignores the SubclassOptionalData flags, which specify conditions
322 /// under which the instruction's result is undefined.
323 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
324 if (getOpcode() != I->getOpcode() ||
325 getNumOperands() != I->getNumOperands() ||
326 getType() != I->getType())
329 // If both instructions have no operands, they are identical.
330 if (getNumOperands() == 0 && I->getNumOperands() == 0)
331 return haveSameSpecialState(this, I);
333 // We have two instructions of identical opcode and #operands. Check to see
334 // if all operands are the same.
335 if (!std::equal(op_begin(), op_end(), I->op_begin()))
338 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
339 const PHINode *otherPHI = cast<PHINode>(I);
340 return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
341 otherPHI->block_begin());
344 return haveSameSpecialState(this, I);
348 // This should be kept in sync with isEquivalentOperation in
349 // lib/Transforms/IPO/MergeFunctions.cpp.
350 bool Instruction::isSameOperationAs(const Instruction *I,
351 unsigned flags) const {
352 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
353 bool UseScalarTypes = flags & CompareUsingScalarTypes;
355 if (getOpcode() != I->getOpcode() ||
356 getNumOperands() != I->getNumOperands() ||
358 getType()->getScalarType() != I->getType()->getScalarType() :
359 getType() != I->getType()))
362 // We have two instructions of identical opcode and #operands. Check to see
363 // if all operands are the same type
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
366 getOperand(i)->getType()->getScalarType() !=
367 I->getOperand(i)->getType()->getScalarType() :
368 getOperand(i)->getType() != I->getOperand(i)->getType())
371 return haveSameSpecialState(this, I, IgnoreAlignment);
374 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
375 /// specified block. Note that PHI nodes are considered to evaluate their
376 /// operands in the corresponding predecessor block.
377 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
378 for (const Use &U : uses()) {
379 // PHI nodes uses values in the corresponding predecessor block. For other
380 // instructions, just check to see whether the parent of the use matches up.
381 const Instruction *I = cast<Instruction>(U.getUser());
382 const PHINode *PN = dyn_cast<PHINode>(I);
384 if (I->getParent() != BB)
389 if (PN->getIncomingBlock(U) != BB)
395 /// mayReadFromMemory - Return true if this instruction may read memory.
397 bool Instruction::mayReadFromMemory() const {
398 switch (getOpcode()) {
399 default: return false;
400 case Instruction::VAArg:
401 case Instruction::Load:
402 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
403 case Instruction::AtomicCmpXchg:
404 case Instruction::AtomicRMW:
406 case Instruction::Call:
407 return !cast<CallInst>(this)->doesNotAccessMemory();
408 case Instruction::Invoke:
409 return !cast<InvokeInst>(this)->doesNotAccessMemory();
410 case Instruction::Store:
411 return !cast<StoreInst>(this)->isUnordered();
415 /// mayWriteToMemory - Return true if this instruction may modify memory.
417 bool Instruction::mayWriteToMemory() const {
418 switch (getOpcode()) {
419 default: return false;
420 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
421 case Instruction::Store:
422 case Instruction::VAArg:
423 case Instruction::AtomicCmpXchg:
424 case Instruction::AtomicRMW:
426 case Instruction::Call:
427 return !cast<CallInst>(this)->onlyReadsMemory();
428 case Instruction::Invoke:
429 return !cast<InvokeInst>(this)->onlyReadsMemory();
430 case Instruction::Load:
431 return !cast<LoadInst>(this)->isUnordered();
435 bool Instruction::isAtomic() const {
436 switch (getOpcode()) {
439 case Instruction::AtomicCmpXchg:
440 case Instruction::AtomicRMW:
441 case Instruction::Fence:
443 case Instruction::Load:
444 return cast<LoadInst>(this)->getOrdering() != NotAtomic;
445 case Instruction::Store:
446 return cast<StoreInst>(this)->getOrdering() != NotAtomic;
450 bool Instruction::mayThrow() const {
451 if (const CallInst *CI = dyn_cast<CallInst>(this))
452 return !CI->doesNotThrow();
453 return isa<ResumeInst>(this);
456 bool Instruction::mayReturn() const {
457 if (const CallInst *CI = dyn_cast<CallInst>(this))
458 return !CI->doesNotReturn();
462 /// isAssociative - Return true if the instruction is associative:
464 /// Associative operators satisfy: x op (y op z) === (x op y) op z
466 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
468 bool Instruction::isAssociative(unsigned Opcode) {
469 return Opcode == And || Opcode == Or || Opcode == Xor ||
470 Opcode == Add || Opcode == Mul;
473 bool Instruction::isAssociative() const {
474 unsigned Opcode = getOpcode();
475 if (isAssociative(Opcode))
481 return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
487 /// isCommutative - Return true if the instruction is commutative:
489 /// Commutative operators satisfy: (x op y) === (y op x)
491 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
492 /// applied to any type.
494 bool Instruction::isCommutative(unsigned op) {
509 /// isIdempotent - Return true if the instruction is idempotent:
511 /// Idempotent operators satisfy: x op x === x
513 /// In LLVM, the And and Or operators are idempotent.
515 bool Instruction::isIdempotent(unsigned Opcode) {
516 return Opcode == And || Opcode == Or;
519 /// isNilpotent - Return true if the instruction is nilpotent:
521 /// Nilpotent operators satisfy: x op x === Id,
523 /// where Id is the identity for the operator, i.e. a constant such that
524 /// x op Id === x and Id op x === x for all x.
526 /// In LLVM, the Xor operator is nilpotent.
528 bool Instruction::isNilpotent(unsigned Opcode) {
529 return Opcode == Xor;
532 Instruction *Instruction::clone() const {
533 Instruction *New = clone_impl();
534 New->SubclassOptionalData = SubclassOptionalData;
538 // Otherwise, enumerate and copy over metadata from the old instruction to the
540 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
541 getAllMetadataOtherThanDebugLoc(TheMDs);
542 for (const auto &MD : TheMDs)
543 New->setMetadata(MD.first, MD.second);
545 New->setDebugLoc(getDebugLoc());