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