1 //===-- Instruction.cpp - Implement the Instruction class -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Instruction class for the IR library.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
21 using namespace llvm;
22
Instruction(Type * ty,unsigned it,Use * Ops,unsigned NumOps,Instruction * InsertBefore)23 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
24 Instruction *InsertBefore)
25 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
26
27 // If requested, insert this instruction into a basic block...
28 if (InsertBefore) {
29 assert(InsertBefore->getParent() &&
30 "Instruction to insert before is not in a basic block!");
31 InsertBefore->getParent()->getInstList().insert(InsertBefore, this);
32 }
33 }
34
Instruction(Type * ty,unsigned it,Use * Ops,unsigned NumOps,BasicBlock * InsertAtEnd)35 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
36 BasicBlock *InsertAtEnd)
37 : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
38
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);
42 }
43
44
45 // Out of line virtual method, so the vtable, etc has a home.
~Instruction()46 Instruction::~Instruction() {
47 assert(!Parent && "Instruction still linked in the program!");
48 if (hasMetadataHashEntry())
49 clearMetadataHashEntries();
50 }
51
52
setParent(BasicBlock * P)53 void Instruction::setParent(BasicBlock *P) {
54 Parent = P;
55 }
56
getModule() const57 const Module *Instruction::getModule() const {
58 return getParent()->getModule();
59 }
60
removeFromParent()61 void Instruction::removeFromParent() {
62 getParent()->getInstList().remove(this);
63 }
64
eraseFromParent()65 iplist<Instruction>::iterator Instruction::eraseFromParent() {
66 return getParent()->getInstList().erase(this);
67 }
68
69 /// insertBefore - Insert an unlinked instructions into a basic block
70 /// immediately before the specified instruction.
insertBefore(Instruction * InsertPos)71 void Instruction::insertBefore(Instruction *InsertPos) {
72 InsertPos->getParent()->getInstList().insert(InsertPos, this);
73 }
74
75 /// insertAfter - Insert an unlinked instructions into a basic block
76 /// immediately after the specified instruction.
insertAfter(Instruction * InsertPos)77 void Instruction::insertAfter(Instruction *InsertPos) {
78 InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
79 }
80
81 /// moveBefore - Unlink this instruction from its current basic block and
82 /// insert it into the basic block that MovePos lives in, right before
83 /// MovePos.
moveBefore(Instruction * MovePos)84 void Instruction::moveBefore(Instruction *MovePos) {
85 MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
86 this);
87 }
88
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
91 /// flag.
setHasUnsafeAlgebra(bool B)92 void Instruction::setHasUnsafeAlgebra(bool B) {
93 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
94 cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
95 }
96
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.
setHasNoNaNs(bool B)99 void Instruction::setHasNoNaNs(bool B) {
100 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
101 cast<FPMathOperator>(this)->setHasNoNaNs(B);
102 }
103
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.
setHasNoInfs(bool B)106 void Instruction::setHasNoInfs(bool B) {
107 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
108 cast<FPMathOperator>(this)->setHasNoInfs(B);
109 }
110
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
113 /// flag.
setHasNoSignedZeros(bool B)114 void Instruction::setHasNoSignedZeros(bool B) {
115 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
116 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
117 }
118
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
121 /// flag.
setHasAllowReciprocal(bool B)122 void Instruction::setHasAllowReciprocal(bool B) {
123 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
124 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
125 }
126
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.
setFastMathFlags(FastMathFlags FMF)130 void Instruction::setFastMathFlags(FastMathFlags FMF) {
131 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
132 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
133 }
134
copyFastMathFlags(FastMathFlags 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);
138 }
139
140 /// Determine whether the unsafe-algebra flag is set.
hasUnsafeAlgebra() const141 bool Instruction::hasUnsafeAlgebra() const {
142 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
143 return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
144 }
145
146 /// Determine whether the no-NaNs flag is set.
hasNoNaNs() const147 bool Instruction::hasNoNaNs() const {
148 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
149 return cast<FPMathOperator>(this)->hasNoNaNs();
150 }
151
152 /// Determine whether the no-infs flag is set.
hasNoInfs() const153 bool Instruction::hasNoInfs() const {
154 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
155 return cast<FPMathOperator>(this)->hasNoInfs();
156 }
157
158 /// Determine whether the no-signed-zeros flag is set.
hasNoSignedZeros() const159 bool Instruction::hasNoSignedZeros() const {
160 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
161 return cast<FPMathOperator>(this)->hasNoSignedZeros();
162 }
163
164 /// Determine whether the allow-reciprocal flag is set.
hasAllowReciprocal() const165 bool Instruction::hasAllowReciprocal() const {
166 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
167 return cast<FPMathOperator>(this)->hasAllowReciprocal();
168 }
169
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
172 /// these flags.
getFastMathFlags() const173 FastMathFlags Instruction::getFastMathFlags() const {
174 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
175 return cast<FPMathOperator>(this)->getFastMathFlags();
176 }
177
178 /// Copy I's fast-math flags
copyFastMathFlags(const Instruction * I)179 void Instruction::copyFastMathFlags(const Instruction *I) {
180 copyFastMathFlags(I->getFastMathFlags());
181 }
182
183
getOpcodeName(unsigned OpCode)184 const char *Instruction::getOpcodeName(unsigned OpCode) {
185 switch (OpCode) {
186 // Terminators
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";
194
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";
208
209 // Logical operators...
210 case And: return "and";
211 case Or : return "or";
212 case Xor: return "xor";
213
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";
222
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";
237
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";
254
255 default: return "<Invalid operator> ";
256 }
257 }
258
259 /// Return true if both instructions have the same special state
260 /// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp.
haveSameSpecialState(const Instruction * I1,const Instruction * I2,bool IgnoreAlignment=false)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");
265
266 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
267 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
268 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
269 IgnoreAlignment) &&
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() ||
275 IgnoreAlignment) &&
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();
308
309 return true;
310 }
311
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.
isIdenticalTo(const Instruction * I) const315 bool Instruction::isIdenticalTo(const Instruction *I) const {
316 return isIdenticalToWhenDefined(I) &&
317 SubclassOptionalData == I->SubclassOptionalData;
318 }
319
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.
isIdenticalToWhenDefined(const Instruction * I) const323 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
324 if (getOpcode() != I->getOpcode() ||
325 getNumOperands() != I->getNumOperands() ||
326 getType() != I->getType())
327 return false;
328
329 // If both instructions have no operands, they are identical.
330 if (getNumOperands() == 0 && I->getNumOperands() == 0)
331 return haveSameSpecialState(this, I);
332
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()))
336 return false;
337
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());
342 }
343
344 return haveSameSpecialState(this, I);
345 }
346
347 // isSameOperationAs
348 // This should be kept in sync with isEquivalentOperation in
349 // lib/Transforms/IPO/MergeFunctions.cpp.
isSameOperationAs(const Instruction * I,unsigned flags) const350 bool Instruction::isSameOperationAs(const Instruction *I,
351 unsigned flags) const {
352 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
353 bool UseScalarTypes = flags & CompareUsingScalarTypes;
354
355 if (getOpcode() != I->getOpcode() ||
356 getNumOperands() != I->getNumOperands() ||
357 (UseScalarTypes ?
358 getType()->getScalarType() != I->getType()->getScalarType() :
359 getType() != I->getType()))
360 return false;
361
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)
365 if (UseScalarTypes ?
366 getOperand(i)->getType()->getScalarType() !=
367 I->getOperand(i)->getType()->getScalarType() :
368 getOperand(i)->getType() != I->getOperand(i)->getType())
369 return false;
370
371 return haveSameSpecialState(this, I, IgnoreAlignment);
372 }
373
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.
isUsedOutsideOfBlock(const BasicBlock * BB) const377 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);
383 if (!PN) {
384 if (I->getParent() != BB)
385 return true;
386 continue;
387 }
388
389 if (PN->getIncomingBlock(U) != BB)
390 return true;
391 }
392 return false;
393 }
394
395 /// mayReadFromMemory - Return true if this instruction may read memory.
396 ///
mayReadFromMemory() const397 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:
405 return true;
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();
412 }
413 }
414
415 /// mayWriteToMemory - Return true if this instruction may modify memory.
416 ///
mayWriteToMemory() const417 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:
425 return true;
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();
432 }
433 }
434
isAtomic() const435 bool Instruction::isAtomic() const {
436 switch (getOpcode()) {
437 default:
438 return false;
439 case Instruction::AtomicCmpXchg:
440 case Instruction::AtomicRMW:
441 case Instruction::Fence:
442 return true;
443 case Instruction::Load:
444 return cast<LoadInst>(this)->getOrdering() != NotAtomic;
445 case Instruction::Store:
446 return cast<StoreInst>(this)->getOrdering() != NotAtomic;
447 }
448 }
449
mayThrow() const450 bool Instruction::mayThrow() const {
451 if (const CallInst *CI = dyn_cast<CallInst>(this))
452 return !CI->doesNotThrow();
453 return isa<ResumeInst>(this);
454 }
455
mayReturn() const456 bool Instruction::mayReturn() const {
457 if (const CallInst *CI = dyn_cast<CallInst>(this))
458 return !CI->doesNotReturn();
459 return true;
460 }
461
462 /// isAssociative - Return true if the instruction is associative:
463 ///
464 /// Associative operators satisfy: x op (y op z) === (x op y) op z
465 ///
466 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
467 ///
isAssociative(unsigned Opcode)468 bool Instruction::isAssociative(unsigned Opcode) {
469 return Opcode == And || Opcode == Or || Opcode == Xor ||
470 Opcode == Add || Opcode == Mul;
471 }
472
isAssociative() const473 bool Instruction::isAssociative() const {
474 unsigned Opcode = getOpcode();
475 if (isAssociative(Opcode))
476 return true;
477
478 switch (Opcode) {
479 case FMul:
480 case FAdd:
481 return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
482 default:
483 return false;
484 }
485 }
486
487 /// isCommutative - Return true if the instruction is commutative:
488 ///
489 /// Commutative operators satisfy: (x op y) === (y op x)
490 ///
491 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
492 /// applied to any type.
493 ///
isCommutative(unsigned op)494 bool Instruction::isCommutative(unsigned op) {
495 switch (op) {
496 case Add:
497 case FAdd:
498 case Mul:
499 case FMul:
500 case And:
501 case Or:
502 case Xor:
503 return true;
504 default:
505 return false;
506 }
507 }
508
509 /// isIdempotent - Return true if the instruction is idempotent:
510 ///
511 /// Idempotent operators satisfy: x op x === x
512 ///
513 /// In LLVM, the And and Or operators are idempotent.
514 ///
isIdempotent(unsigned Opcode)515 bool Instruction::isIdempotent(unsigned Opcode) {
516 return Opcode == And || Opcode == Or;
517 }
518
519 /// isNilpotent - Return true if the instruction is nilpotent:
520 ///
521 /// Nilpotent operators satisfy: x op x === Id,
522 ///
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.
525 ///
526 /// In LLVM, the Xor operator is nilpotent.
527 ///
isNilpotent(unsigned Opcode)528 bool Instruction::isNilpotent(unsigned Opcode) {
529 return Opcode == Xor;
530 }
531
clone() const532 Instruction *Instruction::clone() const {
533 Instruction *New = clone_impl();
534 New->SubclassOptionalData = SubclassOptionalData;
535 if (!hasMetadata())
536 return New;
537
538 // Otherwise, enumerate and copy over metadata from the old instruction to the
539 // new one.
540 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
541 getAllMetadataOtherThanDebugLoc(TheMDs);
542 for (const auto &MD : TheMDs)
543 New->setMetadata(MD.first, MD.second);
544
545 New->setDebugLoc(getDebugLoc());
546 return New;
547 }
548