1 //===-- Instruction.cpp - Implement the Instruction class -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Instruction class for the IR library.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/IR/Instruction.h"
14 #include "llvm/IR/IntrinsicInst.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/MDBuilder.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 BasicBlock *BB = InsertBefore->getParent();
30 assert(BB && "Instruction to insert before is not in a basic block!");
31 BB->getInstList().insert(InsertBefore->getIterator(), 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
~Instruction()44 Instruction::~Instruction() {
45 assert(!Parent && "Instruction still linked in the program!");
46 if (hasMetadataHashEntry())
47 clearMetadataHashEntries();
48 }
49
50
setParent(BasicBlock * P)51 void Instruction::setParent(BasicBlock *P) {
52 Parent = P;
53 }
54
getModule() const55 const Module *Instruction::getModule() const {
56 return getParent()->getModule();
57 }
58
getFunction() const59 const Function *Instruction::getFunction() const {
60 return getParent()->getParent();
61 }
62
removeFromParent()63 void Instruction::removeFromParent() {
64 getParent()->getInstList().remove(getIterator());
65 }
66
eraseFromParent()67 iplist<Instruction>::iterator Instruction::eraseFromParent() {
68 return getParent()->getInstList().erase(getIterator());
69 }
70
71 /// Insert an unlinked instruction into a basic block immediately before the
72 /// specified instruction.
insertBefore(Instruction * InsertPos)73 void Instruction::insertBefore(Instruction *InsertPos) {
74 InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
75 }
76
77 /// Insert an unlinked instruction into a basic block immediately after the
78 /// specified instruction.
insertAfter(Instruction * InsertPos)79 void Instruction::insertAfter(Instruction *InsertPos) {
80 InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
81 this);
82 }
83
84 /// Unlink this instruction from its current basic block and insert it into the
85 /// basic block that MovePos lives in, right before MovePos.
moveBefore(Instruction * MovePos)86 void Instruction::moveBefore(Instruction *MovePos) {
87 moveBefore(*MovePos->getParent(), MovePos->getIterator());
88 }
89
moveAfter(Instruction * MovePos)90 void Instruction::moveAfter(Instruction *MovePos) {
91 moveBefore(*MovePos->getParent(), ++MovePos->getIterator());
92 }
93
moveBefore(BasicBlock & BB,SymbolTableList<Instruction>::iterator I)94 void Instruction::moveBefore(BasicBlock &BB,
95 SymbolTableList<Instruction>::iterator I) {
96 assert(I == BB.end() || I->getParent() == &BB);
97 BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
98 }
99
setHasNoUnsignedWrap(bool b)100 void Instruction::setHasNoUnsignedWrap(bool b) {
101 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
102 }
103
setHasNoSignedWrap(bool b)104 void Instruction::setHasNoSignedWrap(bool b) {
105 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
106 }
107
setIsExact(bool b)108 void Instruction::setIsExact(bool b) {
109 cast<PossiblyExactOperator>(this)->setIsExact(b);
110 }
111
hasNoUnsignedWrap() const112 bool Instruction::hasNoUnsignedWrap() const {
113 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
114 }
115
hasNoSignedWrap() const116 bool Instruction::hasNoSignedWrap() const {
117 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
118 }
119
dropPoisonGeneratingFlags()120 void Instruction::dropPoisonGeneratingFlags() {
121 switch (getOpcode()) {
122 case Instruction::Add:
123 case Instruction::Sub:
124 case Instruction::Mul:
125 case Instruction::Shl:
126 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
127 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
128 break;
129
130 case Instruction::UDiv:
131 case Instruction::SDiv:
132 case Instruction::AShr:
133 case Instruction::LShr:
134 cast<PossiblyExactOperator>(this)->setIsExact(false);
135 break;
136
137 case Instruction::GetElementPtr:
138 cast<GetElementPtrInst>(this)->setIsInBounds(false);
139 break;
140 }
141 // TODO: FastMathFlags!
142 }
143
144
isExact() const145 bool Instruction::isExact() const {
146 return cast<PossiblyExactOperator>(this)->isExact();
147 }
148
setFast(bool B)149 void Instruction::setFast(bool B) {
150 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
151 cast<FPMathOperator>(this)->setFast(B);
152 }
153
setHasAllowReassoc(bool B)154 void Instruction::setHasAllowReassoc(bool B) {
155 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
156 cast<FPMathOperator>(this)->setHasAllowReassoc(B);
157 }
158
setHasNoNaNs(bool B)159 void Instruction::setHasNoNaNs(bool B) {
160 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
161 cast<FPMathOperator>(this)->setHasNoNaNs(B);
162 }
163
setHasNoInfs(bool B)164 void Instruction::setHasNoInfs(bool B) {
165 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
166 cast<FPMathOperator>(this)->setHasNoInfs(B);
167 }
168
setHasNoSignedZeros(bool B)169 void Instruction::setHasNoSignedZeros(bool B) {
170 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
171 cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
172 }
173
setHasAllowReciprocal(bool B)174 void Instruction::setHasAllowReciprocal(bool B) {
175 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
176 cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
177 }
178
setHasApproxFunc(bool B)179 void Instruction::setHasApproxFunc(bool B) {
180 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
181 cast<FPMathOperator>(this)->setHasApproxFunc(B);
182 }
183
setFastMathFlags(FastMathFlags FMF)184 void Instruction::setFastMathFlags(FastMathFlags FMF) {
185 assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
186 cast<FPMathOperator>(this)->setFastMathFlags(FMF);
187 }
188
copyFastMathFlags(FastMathFlags FMF)189 void Instruction::copyFastMathFlags(FastMathFlags FMF) {
190 assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
191 cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
192 }
193
isFast() const194 bool Instruction::isFast() const {
195 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
196 return cast<FPMathOperator>(this)->isFast();
197 }
198
hasAllowReassoc() const199 bool Instruction::hasAllowReassoc() const {
200 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
201 return cast<FPMathOperator>(this)->hasAllowReassoc();
202 }
203
hasNoNaNs() const204 bool Instruction::hasNoNaNs() const {
205 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
206 return cast<FPMathOperator>(this)->hasNoNaNs();
207 }
208
hasNoInfs() const209 bool Instruction::hasNoInfs() const {
210 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
211 return cast<FPMathOperator>(this)->hasNoInfs();
212 }
213
hasNoSignedZeros() const214 bool Instruction::hasNoSignedZeros() const {
215 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
216 return cast<FPMathOperator>(this)->hasNoSignedZeros();
217 }
218
hasAllowReciprocal() const219 bool Instruction::hasAllowReciprocal() const {
220 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
221 return cast<FPMathOperator>(this)->hasAllowReciprocal();
222 }
223
hasAllowContract() const224 bool Instruction::hasAllowContract() const {
225 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
226 return cast<FPMathOperator>(this)->hasAllowContract();
227 }
228
hasApproxFunc() const229 bool Instruction::hasApproxFunc() const {
230 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
231 return cast<FPMathOperator>(this)->hasApproxFunc();
232 }
233
getFastMathFlags() const234 FastMathFlags Instruction::getFastMathFlags() const {
235 assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
236 return cast<FPMathOperator>(this)->getFastMathFlags();
237 }
238
copyFastMathFlags(const Instruction * I)239 void Instruction::copyFastMathFlags(const Instruction *I) {
240 copyFastMathFlags(I->getFastMathFlags());
241 }
242
copyIRFlags(const Value * V,bool IncludeWrapFlags)243 void Instruction::copyIRFlags(const Value *V, bool IncludeWrapFlags) {
244 // Copy the wrapping flags.
245 if (IncludeWrapFlags && isa<OverflowingBinaryOperator>(this)) {
246 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
247 setHasNoSignedWrap(OB->hasNoSignedWrap());
248 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
249 }
250 }
251
252 // Copy the exact flag.
253 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
254 if (isa<PossiblyExactOperator>(this))
255 setIsExact(PE->isExact());
256
257 // Copy the fast-math flags.
258 if (auto *FP = dyn_cast<FPMathOperator>(V))
259 if (isa<FPMathOperator>(this))
260 copyFastMathFlags(FP->getFastMathFlags());
261
262 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
263 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
264 DestGEP->setIsInBounds(SrcGEP->isInBounds() | DestGEP->isInBounds());
265 }
266
andIRFlags(const Value * V)267 void Instruction::andIRFlags(const Value *V) {
268 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
269 if (isa<OverflowingBinaryOperator>(this)) {
270 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
271 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
272 }
273 }
274
275 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
276 if (isa<PossiblyExactOperator>(this))
277 setIsExact(isExact() & PE->isExact());
278
279 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
280 if (isa<FPMathOperator>(this)) {
281 FastMathFlags FM = getFastMathFlags();
282 FM &= FP->getFastMathFlags();
283 copyFastMathFlags(FM);
284 }
285 }
286
287 if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
288 if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
289 DestGEP->setIsInBounds(SrcGEP->isInBounds() & DestGEP->isInBounds());
290 }
291
getOpcodeName(unsigned OpCode)292 const char *Instruction::getOpcodeName(unsigned OpCode) {
293 switch (OpCode) {
294 // Terminators
295 case Ret: return "ret";
296 case Br: return "br";
297 case Switch: return "switch";
298 case IndirectBr: return "indirectbr";
299 case Invoke: return "invoke";
300 case Resume: return "resume";
301 case Unreachable: return "unreachable";
302 case CleanupRet: return "cleanupret";
303 case CatchRet: return "catchret";
304 case CatchPad: return "catchpad";
305 case CatchSwitch: return "catchswitch";
306 case CallBr: return "callbr";
307
308 // Standard unary operators...
309 case FNeg: return "fneg";
310
311 // Standard binary operators...
312 case Add: return "add";
313 case FAdd: return "fadd";
314 case Sub: return "sub";
315 case FSub: return "fsub";
316 case Mul: return "mul";
317 case FMul: return "fmul";
318 case UDiv: return "udiv";
319 case SDiv: return "sdiv";
320 case FDiv: return "fdiv";
321 case URem: return "urem";
322 case SRem: return "srem";
323 case FRem: return "frem";
324
325 // Logical operators...
326 case And: return "and";
327 case Or : return "or";
328 case Xor: return "xor";
329
330 // Memory instructions...
331 case Alloca: return "alloca";
332 case Load: return "load";
333 case Store: return "store";
334 case AtomicCmpXchg: return "cmpxchg";
335 case AtomicRMW: return "atomicrmw";
336 case Fence: return "fence";
337 case GetElementPtr: return "getelementptr";
338
339 // Convert instructions...
340 case Trunc: return "trunc";
341 case ZExt: return "zext";
342 case SExt: return "sext";
343 case FPTrunc: return "fptrunc";
344 case FPExt: return "fpext";
345 case FPToUI: return "fptoui";
346 case FPToSI: return "fptosi";
347 case UIToFP: return "uitofp";
348 case SIToFP: return "sitofp";
349 case IntToPtr: return "inttoptr";
350 case PtrToInt: return "ptrtoint";
351 case BitCast: return "bitcast";
352 case AddrSpaceCast: return "addrspacecast";
353
354 // Other instructions...
355 case ICmp: return "icmp";
356 case FCmp: return "fcmp";
357 case PHI: return "phi";
358 case Select: return "select";
359 case Call: return "call";
360 case Shl: return "shl";
361 case LShr: return "lshr";
362 case AShr: return "ashr";
363 case VAArg: return "va_arg";
364 case ExtractElement: return "extractelement";
365 case InsertElement: return "insertelement";
366 case ShuffleVector: return "shufflevector";
367 case ExtractValue: return "extractvalue";
368 case InsertValue: return "insertvalue";
369 case LandingPad: return "landingpad";
370 case CleanupPad: return "cleanuppad";
371 case Freeze: return "freeze";
372
373 default: return "<Invalid operator> ";
374 }
375 }
376
377 /// Return true if both instructions have the same special state. This must be
378 /// kept in sync with FunctionComparator::cmpOperations in
379 /// lib/Transforms/IPO/MergeFunctions.cpp.
haveSameSpecialState(const Instruction * I1,const Instruction * I2,bool IgnoreAlignment=false)380 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
381 bool IgnoreAlignment = false) {
382 assert(I1->getOpcode() == I2->getOpcode() &&
383 "Can not compare special state of different instructions");
384
385 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
386 return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
387 (AI->getAlignment() == cast<AllocaInst>(I2)->getAlignment() ||
388 IgnoreAlignment);
389 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
390 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
391 (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
392 IgnoreAlignment) &&
393 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
394 LI->getSyncScopeID() == cast<LoadInst>(I2)->getSyncScopeID();
395 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
396 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
397 (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
398 IgnoreAlignment) &&
399 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
400 SI->getSyncScopeID() == cast<StoreInst>(I2)->getSyncScopeID();
401 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
402 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
403 if (const CallInst *CI = dyn_cast<CallInst>(I1))
404 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
405 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
406 CI->getAttributes() == cast<CallInst>(I2)->getAttributes() &&
407 CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
408 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
409 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
410 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() &&
411 CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
412 if (const CallBrInst *CI = dyn_cast<CallBrInst>(I1))
413 return CI->getCallingConv() == cast<CallBrInst>(I2)->getCallingConv() &&
414 CI->getAttributes() == cast<CallBrInst>(I2)->getAttributes() &&
415 CI->hasIdenticalOperandBundleSchema(*cast<CallBrInst>(I2));
416 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
417 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
418 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
419 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
420 if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
421 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
422 FI->getSyncScopeID() == cast<FenceInst>(I2)->getSyncScopeID();
423 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
424 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
425 CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
426 CXI->getSuccessOrdering() ==
427 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
428 CXI->getFailureOrdering() ==
429 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
430 CXI->getSyncScopeID() ==
431 cast<AtomicCmpXchgInst>(I2)->getSyncScopeID();
432 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
433 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
434 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
435 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
436 RMWI->getSyncScopeID() == cast<AtomicRMWInst>(I2)->getSyncScopeID();
437
438 return true;
439 }
440
isIdenticalTo(const Instruction * I) const441 bool Instruction::isIdenticalTo(const Instruction *I) const {
442 return isIdenticalToWhenDefined(I) &&
443 SubclassOptionalData == I->SubclassOptionalData;
444 }
445
isIdenticalToWhenDefined(const Instruction * I) const446 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
447 if (getOpcode() != I->getOpcode() ||
448 getNumOperands() != I->getNumOperands() ||
449 getType() != I->getType())
450 return false;
451
452 // If both instructions have no operands, they are identical.
453 if (getNumOperands() == 0 && I->getNumOperands() == 0)
454 return haveSameSpecialState(this, I);
455
456 // We have two instructions of identical opcode and #operands. Check to see
457 // if all operands are the same.
458 if (!std::equal(op_begin(), op_end(), I->op_begin()))
459 return false;
460
461 if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
462 const PHINode *otherPHI = cast<PHINode>(I);
463 return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
464 otherPHI->block_begin());
465 }
466
467 return haveSameSpecialState(this, I);
468 }
469
470 // Keep this in sync with FunctionComparator::cmpOperations in
471 // lib/Transforms/IPO/MergeFunctions.cpp.
isSameOperationAs(const Instruction * I,unsigned flags) const472 bool Instruction::isSameOperationAs(const Instruction *I,
473 unsigned flags) const {
474 bool IgnoreAlignment = flags & CompareIgnoringAlignment;
475 bool UseScalarTypes = flags & CompareUsingScalarTypes;
476
477 if (getOpcode() != I->getOpcode() ||
478 getNumOperands() != I->getNumOperands() ||
479 (UseScalarTypes ?
480 getType()->getScalarType() != I->getType()->getScalarType() :
481 getType() != I->getType()))
482 return false;
483
484 // We have two instructions of identical opcode and #operands. Check to see
485 // if all operands are the same type
486 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
487 if (UseScalarTypes ?
488 getOperand(i)->getType()->getScalarType() !=
489 I->getOperand(i)->getType()->getScalarType() :
490 getOperand(i)->getType() != I->getOperand(i)->getType())
491 return false;
492
493 return haveSameSpecialState(this, I, IgnoreAlignment);
494 }
495
isUsedOutsideOfBlock(const BasicBlock * BB) const496 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
497 for (const Use &U : uses()) {
498 // PHI nodes uses values in the corresponding predecessor block. For other
499 // instructions, just check to see whether the parent of the use matches up.
500 const Instruction *I = cast<Instruction>(U.getUser());
501 const PHINode *PN = dyn_cast<PHINode>(I);
502 if (!PN) {
503 if (I->getParent() != BB)
504 return true;
505 continue;
506 }
507
508 if (PN->getIncomingBlock(U) != BB)
509 return true;
510 }
511 return false;
512 }
513
mayReadFromMemory() const514 bool Instruction::mayReadFromMemory() const {
515 switch (getOpcode()) {
516 default: return false;
517 case Instruction::VAArg:
518 case Instruction::Load:
519 case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
520 case Instruction::AtomicCmpXchg:
521 case Instruction::AtomicRMW:
522 case Instruction::CatchPad:
523 case Instruction::CatchRet:
524 return true;
525 case Instruction::Call:
526 case Instruction::Invoke:
527 case Instruction::CallBr:
528 return !cast<CallBase>(this)->doesNotReadMemory();
529 case Instruction::Store:
530 return !cast<StoreInst>(this)->isUnordered();
531 }
532 }
533
mayWriteToMemory() const534 bool Instruction::mayWriteToMemory() const {
535 switch (getOpcode()) {
536 default: return false;
537 case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
538 case Instruction::Store:
539 case Instruction::VAArg:
540 case Instruction::AtomicCmpXchg:
541 case Instruction::AtomicRMW:
542 case Instruction::CatchPad:
543 case Instruction::CatchRet:
544 return true;
545 case Instruction::Call:
546 case Instruction::Invoke:
547 case Instruction::CallBr:
548 return !cast<CallBase>(this)->onlyReadsMemory();
549 case Instruction::Load:
550 return !cast<LoadInst>(this)->isUnordered();
551 }
552 }
553
isAtomic() const554 bool Instruction::isAtomic() const {
555 switch (getOpcode()) {
556 default:
557 return false;
558 case Instruction::AtomicCmpXchg:
559 case Instruction::AtomicRMW:
560 case Instruction::Fence:
561 return true;
562 case Instruction::Load:
563 return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
564 case Instruction::Store:
565 return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
566 }
567 }
568
hasAtomicLoad() const569 bool Instruction::hasAtomicLoad() const {
570 assert(isAtomic());
571 switch (getOpcode()) {
572 default:
573 return false;
574 case Instruction::AtomicCmpXchg:
575 case Instruction::AtomicRMW:
576 case Instruction::Load:
577 return true;
578 }
579 }
580
hasAtomicStore() const581 bool Instruction::hasAtomicStore() const {
582 assert(isAtomic());
583 switch (getOpcode()) {
584 default:
585 return false;
586 case Instruction::AtomicCmpXchg:
587 case Instruction::AtomicRMW:
588 case Instruction::Store:
589 return true;
590 }
591 }
592
mayThrow() const593 bool Instruction::mayThrow() const {
594 if (const CallInst *CI = dyn_cast<CallInst>(this))
595 return !CI->doesNotThrow();
596 if (const auto *CRI = dyn_cast<CleanupReturnInst>(this))
597 return CRI->unwindsToCaller();
598 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this))
599 return CatchSwitch->unwindsToCaller();
600 return isa<ResumeInst>(this);
601 }
602
isSafeToRemove() const603 bool Instruction::isSafeToRemove() const {
604 return (!isa<CallInst>(this) || !this->mayHaveSideEffects()) &&
605 !this->isTerminator();
606 }
607
isLifetimeStartOrEnd() const608 bool Instruction::isLifetimeStartOrEnd() const {
609 auto II = dyn_cast<IntrinsicInst>(this);
610 if (!II)
611 return false;
612 Intrinsic::ID ID = II->getIntrinsicID();
613 return ID == Intrinsic::lifetime_start || ID == Intrinsic::lifetime_end;
614 }
615
getNextNonDebugInstruction() const616 const Instruction *Instruction::getNextNonDebugInstruction() const {
617 for (const Instruction *I = getNextNode(); I; I = I->getNextNode())
618 if (!isa<DbgInfoIntrinsic>(I))
619 return I;
620 return nullptr;
621 }
622
getPrevNonDebugInstruction() const623 const Instruction *Instruction::getPrevNonDebugInstruction() const {
624 for (const Instruction *I = getPrevNode(); I; I = I->getPrevNode())
625 if (!isa<DbgInfoIntrinsic>(I))
626 return I;
627 return nullptr;
628 }
629
isAssociative() const630 bool Instruction::isAssociative() const {
631 unsigned Opcode = getOpcode();
632 if (isAssociative(Opcode))
633 return true;
634
635 switch (Opcode) {
636 case FMul:
637 case FAdd:
638 return cast<FPMathOperator>(this)->hasAllowReassoc() &&
639 cast<FPMathOperator>(this)->hasNoSignedZeros();
640 default:
641 return false;
642 }
643 }
644
getNumSuccessors() const645 unsigned Instruction::getNumSuccessors() const {
646 switch (getOpcode()) {
647 #define HANDLE_TERM_INST(N, OPC, CLASS) \
648 case Instruction::OPC: \
649 return static_cast<const CLASS *>(this)->getNumSuccessors();
650 #include "llvm/IR/Instruction.def"
651 default:
652 break;
653 }
654 llvm_unreachable("not a terminator");
655 }
656
getSuccessor(unsigned idx) const657 BasicBlock *Instruction::getSuccessor(unsigned idx) const {
658 switch (getOpcode()) {
659 #define HANDLE_TERM_INST(N, OPC, CLASS) \
660 case Instruction::OPC: \
661 return static_cast<const CLASS *>(this)->getSuccessor(idx);
662 #include "llvm/IR/Instruction.def"
663 default:
664 break;
665 }
666 llvm_unreachable("not a terminator");
667 }
668
setSuccessor(unsigned idx,BasicBlock * B)669 void Instruction::setSuccessor(unsigned idx, BasicBlock *B) {
670 switch (getOpcode()) {
671 #define HANDLE_TERM_INST(N, OPC, CLASS) \
672 case Instruction::OPC: \
673 return static_cast<CLASS *>(this)->setSuccessor(idx, B);
674 #include "llvm/IR/Instruction.def"
675 default:
676 break;
677 }
678 llvm_unreachable("not a terminator");
679 }
680
replaceSuccessorWith(BasicBlock * OldBB,BasicBlock * NewBB)681 void Instruction::replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB) {
682 for (unsigned Idx = 0, NumSuccessors = Instruction::getNumSuccessors();
683 Idx != NumSuccessors; ++Idx)
684 if (getSuccessor(Idx) == OldBB)
685 setSuccessor(Idx, NewBB);
686 }
687
cloneImpl() const688 Instruction *Instruction::cloneImpl() const {
689 llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
690 }
691
swapProfMetadata()692 void Instruction::swapProfMetadata() {
693 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
694 if (!ProfileData || ProfileData->getNumOperands() != 3 ||
695 !isa<MDString>(ProfileData->getOperand(0)))
696 return;
697
698 MDString *MDName = cast<MDString>(ProfileData->getOperand(0));
699 if (MDName->getString() != "branch_weights")
700 return;
701
702 // The first operand is the name. Fetch them backwards and build a new one.
703 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
704 ProfileData->getOperand(1)};
705 setMetadata(LLVMContext::MD_prof,
706 MDNode::get(ProfileData->getContext(), Ops));
707 }
708
copyMetadata(const Instruction & SrcInst,ArrayRef<unsigned> WL)709 void Instruction::copyMetadata(const Instruction &SrcInst,
710 ArrayRef<unsigned> WL) {
711 if (!SrcInst.hasMetadata())
712 return;
713
714 DenseSet<unsigned> WLS;
715 for (unsigned M : WL)
716 WLS.insert(M);
717
718 // Otherwise, enumerate and copy over metadata from the old instruction to the
719 // new one.
720 SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
721 SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
722 for (const auto &MD : TheMDs) {
723 if (WL.empty() || WLS.count(MD.first))
724 setMetadata(MD.first, MD.second);
725 }
726 if (WL.empty() || WLS.count(LLVMContext::MD_dbg))
727 setDebugLoc(SrcInst.getDebugLoc());
728 }
729
clone() const730 Instruction *Instruction::clone() const {
731 Instruction *New = nullptr;
732 switch (getOpcode()) {
733 default:
734 llvm_unreachable("Unhandled Opcode.");
735 #define HANDLE_INST(num, opc, clas) \
736 case Instruction::opc: \
737 New = cast<clas>(this)->cloneImpl(); \
738 break;
739 #include "llvm/IR/Instruction.def"
740 #undef HANDLE_INST
741 }
742
743 New->SubclassOptionalData = SubclassOptionalData;
744 New->copyMetadata(*this);
745 return New;
746 }
747
setProfWeight(uint64_t W)748 void Instruction::setProfWeight(uint64_t W) {
749 assert(isa<CallBase>(this) &&
750 "Can only set weights for call like instructions");
751 SmallVector<uint32_t, 1> Weights;
752 Weights.push_back(W);
753 MDBuilder MDB(getContext());
754 setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
755 }
756