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