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/ADT/DenseSet.h"
15 #include "llvm/IR/Instruction.h"
16 #include "llvm/IR/CallSite.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/Operator.h"
21 #include "llvm/IR/Type.h"
22 using namespace llvm;
23 
24 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
25                          Instruction *InsertBefore)
26   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
27 
28   // If requested, insert this instruction into a basic block...
29   if (InsertBefore) {
30     BasicBlock *BB = InsertBefore->getParent();
31     assert(BB && "Instruction to insert before is not in a basic block!");
32     BB->getInstList().insert(InsertBefore->getIterator(), this);
33   }
34 }
35 
36 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
37                          BasicBlock *InsertAtEnd)
38   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
39 
40   // append this instruction into the basic block
41   assert(InsertAtEnd && "Basic block to append to may not be NULL!");
42   InsertAtEnd->getInstList().push_back(this);
43 }
44 
45 
46 // Out of line virtual method, so the vtable, etc has a home.
47 Instruction::~Instruction() {
48   assert(!Parent && "Instruction still linked in the program!");
49   if (hasMetadataHashEntry())
50     clearMetadataHashEntries();
51 }
52 
53 
54 void Instruction::setParent(BasicBlock *P) {
55   Parent = P;
56 }
57 
58 const Module *Instruction::getModule() const {
59   return getParent()->getModule();
60 }
61 
62 Module *Instruction::getModule() {
63   return getParent()->getModule();
64 }
65 
66 Function *Instruction::getFunction() { return getParent()->getParent(); }
67 
68 const Function *Instruction::getFunction() const {
69   return getParent()->getParent();
70 }
71 
72 void Instruction::removeFromParent() {
73   getParent()->getInstList().remove(getIterator());
74 }
75 
76 iplist<Instruction>::iterator Instruction::eraseFromParent() {
77   return getParent()->getInstList().erase(getIterator());
78 }
79 
80 /// Insert an unlinked instruction into a basic block immediately before the
81 /// specified instruction.
82 void Instruction::insertBefore(Instruction *InsertPos) {
83   InsertPos->getParent()->getInstList().insert(InsertPos->getIterator(), this);
84 }
85 
86 /// Insert an unlinked instruction into a basic block immediately after the
87 /// specified instruction.
88 void Instruction::insertAfter(Instruction *InsertPos) {
89   InsertPos->getParent()->getInstList().insertAfter(InsertPos->getIterator(),
90                                                     this);
91 }
92 
93 /// Unlink this instruction from its current basic block and insert it into the
94 /// basic block that MovePos lives in, right before MovePos.
95 void Instruction::moveBefore(Instruction *MovePos) {
96   moveBefore(*MovePos->getParent(), MovePos->getIterator());
97 }
98 
99 void Instruction::moveBefore(BasicBlock &BB,
100                              SymbolTableList<Instruction>::iterator I) {
101   assert(I == BB.end() || I->getParent() == &BB);
102   BB.getInstList().splice(I, getParent()->getInstList(), getIterator());
103 }
104 
105 void Instruction::setHasNoUnsignedWrap(bool b) {
106   cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
107 }
108 
109 void Instruction::setHasNoSignedWrap(bool b) {
110   cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
111 }
112 
113 void Instruction::setIsExact(bool b) {
114   cast<PossiblyExactOperator>(this)->setIsExact(b);
115 }
116 
117 bool Instruction::hasNoUnsignedWrap() const {
118   return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
119 }
120 
121 bool Instruction::hasNoSignedWrap() const {
122   return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
123 }
124 
125 void Instruction::dropPoisonGeneratingFlags() {
126   switch (getOpcode()) {
127   case Instruction::Add:
128   case Instruction::Sub:
129   case Instruction::Mul:
130   case Instruction::Shl:
131     cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(false);
132     cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(false);
133     break;
134 
135   case Instruction::UDiv:
136   case Instruction::SDiv:
137   case Instruction::AShr:
138   case Instruction::LShr:
139     cast<PossiblyExactOperator>(this)->setIsExact(false);
140     break;
141 
142   case Instruction::GetElementPtr:
143     cast<GetElementPtrInst>(this)->setIsInBounds(false);
144     break;
145   }
146 }
147 
148 bool Instruction::isExact() const {
149   return cast<PossiblyExactOperator>(this)->isExact();
150 }
151 
152 void Instruction::setHasUnsafeAlgebra(bool B) {
153   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
154   cast<FPMathOperator>(this)->setHasUnsafeAlgebra(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::setFastMathFlags(FastMathFlags FMF) {
178   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
179   cast<FPMathOperator>(this)->setFastMathFlags(FMF);
180 }
181 
182 void Instruction::copyFastMathFlags(FastMathFlags FMF) {
183   assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
184   cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
185 }
186 
187 bool Instruction::hasUnsafeAlgebra() const {
188   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
189   return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
190 }
191 
192 bool Instruction::hasNoNaNs() const {
193   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
194   return cast<FPMathOperator>(this)->hasNoNaNs();
195 }
196 
197 bool Instruction::hasNoInfs() const {
198   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
199   return cast<FPMathOperator>(this)->hasNoInfs();
200 }
201 
202 bool Instruction::hasNoSignedZeros() const {
203   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
204   return cast<FPMathOperator>(this)->hasNoSignedZeros();
205 }
206 
207 bool Instruction::hasAllowReciprocal() const {
208   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
209   return cast<FPMathOperator>(this)->hasAllowReciprocal();
210 }
211 
212 FastMathFlags Instruction::getFastMathFlags() const {
213   assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
214   return cast<FPMathOperator>(this)->getFastMathFlags();
215 }
216 
217 void Instruction::copyFastMathFlags(const Instruction *I) {
218   copyFastMathFlags(I->getFastMathFlags());
219 }
220 
221 void Instruction::copyIRFlags(const Value *V) {
222   // Copy the wrapping flags.
223   if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
224     if (isa<OverflowingBinaryOperator>(this)) {
225       setHasNoSignedWrap(OB->hasNoSignedWrap());
226       setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
227     }
228   }
229 
230   // Copy the exact flag.
231   if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
232     if (isa<PossiblyExactOperator>(this))
233       setIsExact(PE->isExact());
234 
235   // Copy the fast-math flags.
236   if (auto *FP = dyn_cast<FPMathOperator>(V))
237     if (isa<FPMathOperator>(this))
238       copyFastMathFlags(FP->getFastMathFlags());
239 
240   if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
241     if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
242       DestGEP->setIsInBounds(SrcGEP->isInBounds() | DestGEP->isInBounds());
243 }
244 
245 void Instruction::andIRFlags(const Value *V) {
246   if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
247     if (isa<OverflowingBinaryOperator>(this)) {
248       setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
249       setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
250     }
251   }
252 
253   if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
254     if (isa<PossiblyExactOperator>(this))
255       setIsExact(isExact() & PE->isExact());
256 
257   if (auto *FP = dyn_cast<FPMathOperator>(V)) {
258     if (isa<FPMathOperator>(this)) {
259       FastMathFlags FM = getFastMathFlags();
260       FM &= FP->getFastMathFlags();
261       copyFastMathFlags(FM);
262     }
263   }
264 
265   if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(V))
266     if (auto *DestGEP = dyn_cast<GetElementPtrInst>(this))
267       DestGEP->setIsInBounds(SrcGEP->isInBounds() & DestGEP->isInBounds());
268 }
269 
270 const char *Instruction::getOpcodeName(unsigned OpCode) {
271   switch (OpCode) {
272   // Terminators
273   case Ret:    return "ret";
274   case Br:     return "br";
275   case Switch: return "switch";
276   case IndirectBr: return "indirectbr";
277   case Invoke: return "invoke";
278   case Resume: return "resume";
279   case Unreachable: return "unreachable";
280   case CleanupRet: return "cleanupret";
281   case CatchRet: return "catchret";
282   case CatchPad: return "catchpad";
283   case CatchSwitch: return "catchswitch";
284 
285   // Standard binary operators...
286   case Add: return "add";
287   case FAdd: return "fadd";
288   case Sub: return "sub";
289   case FSub: return "fsub";
290   case Mul: return "mul";
291   case FMul: return "fmul";
292   case UDiv: return "udiv";
293   case SDiv: return "sdiv";
294   case FDiv: return "fdiv";
295   case URem: return "urem";
296   case SRem: return "srem";
297   case FRem: return "frem";
298 
299   // Logical operators...
300   case And: return "and";
301   case Or : return "or";
302   case Xor: return "xor";
303 
304   // Memory instructions...
305   case Alloca:        return "alloca";
306   case Load:          return "load";
307   case Store:         return "store";
308   case AtomicCmpXchg: return "cmpxchg";
309   case AtomicRMW:     return "atomicrmw";
310   case Fence:         return "fence";
311   case GetElementPtr: return "getelementptr";
312 
313   // Convert instructions...
314   case Trunc:         return "trunc";
315   case ZExt:          return "zext";
316   case SExt:          return "sext";
317   case FPTrunc:       return "fptrunc";
318   case FPExt:         return "fpext";
319   case FPToUI:        return "fptoui";
320   case FPToSI:        return "fptosi";
321   case UIToFP:        return "uitofp";
322   case SIToFP:        return "sitofp";
323   case IntToPtr:      return "inttoptr";
324   case PtrToInt:      return "ptrtoint";
325   case BitCast:       return "bitcast";
326   case AddrSpaceCast: return "addrspacecast";
327 
328   // Other instructions...
329   case ICmp:           return "icmp";
330   case FCmp:           return "fcmp";
331   case PHI:            return "phi";
332   case Select:         return "select";
333   case Call:           return "call";
334   case Shl:            return "shl";
335   case LShr:           return "lshr";
336   case AShr:           return "ashr";
337   case VAArg:          return "va_arg";
338   case ExtractElement: return "extractelement";
339   case InsertElement:  return "insertelement";
340   case ShuffleVector:  return "shufflevector";
341   case ExtractValue:   return "extractvalue";
342   case InsertValue:    return "insertvalue";
343   case LandingPad:     return "landingpad";
344   case CleanupPad:     return "cleanuppad";
345 
346   default: return "<Invalid operator> ";
347   }
348 }
349 
350 /// Return true if both instructions have the same special state. This must be
351 /// kept in sync with FunctionComparator::cmpOperations in
352 /// lib/Transforms/IPO/MergeFunctions.cpp.
353 static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
354                                  bool IgnoreAlignment = false) {
355   assert(I1->getOpcode() == I2->getOpcode() &&
356          "Can not compare special state of different instructions");
357 
358   if (const AllocaInst *AI = dyn_cast<AllocaInst>(I1))
359     return AI->getAllocatedType() == cast<AllocaInst>(I2)->getAllocatedType() &&
360            (AI->getAlignment() == cast<AllocaInst>(I2)->getAlignment() ||
361             IgnoreAlignment);
362   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
363     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
364            (LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
365             IgnoreAlignment) &&
366            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
367            LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
368   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
369     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
370            (SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
371             IgnoreAlignment) &&
372            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
373            SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
374   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
375     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
376   if (const CallInst *CI = dyn_cast<CallInst>(I1))
377     return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
378            CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
379            CI->getAttributes() == cast<CallInst>(I2)->getAttributes() &&
380            CI->hasIdenticalOperandBundleSchema(*cast<CallInst>(I2));
381   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
382     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
383            CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes() &&
384            CI->hasIdenticalOperandBundleSchema(*cast<InvokeInst>(I2));
385   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
386     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
387   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
388     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
389   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
390     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
391            FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
392   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
393     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
394            CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
395            CXI->getSuccessOrdering() ==
396                cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
397            CXI->getFailureOrdering() ==
398                cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
399            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
400   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
401     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
402            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
403            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
404            RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
405 
406   return true;
407 }
408 
409 bool Instruction::isIdenticalTo(const Instruction *I) const {
410   return isIdenticalToWhenDefined(I) &&
411          SubclassOptionalData == I->SubclassOptionalData;
412 }
413 
414 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
415   if (getOpcode() != I->getOpcode() ||
416       getNumOperands() != I->getNumOperands() ||
417       getType() != I->getType())
418     return false;
419 
420   // If both instructions have no operands, they are identical.
421   if (getNumOperands() == 0 && I->getNumOperands() == 0)
422     return haveSameSpecialState(this, I);
423 
424   // We have two instructions of identical opcode and #operands.  Check to see
425   // if all operands are the same.
426   if (!std::equal(op_begin(), op_end(), I->op_begin()))
427     return false;
428 
429   if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
430     const PHINode *otherPHI = cast<PHINode>(I);
431     return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
432                       otherPHI->block_begin());
433   }
434 
435   return haveSameSpecialState(this, I);
436 }
437 
438 // Keep this in sync with FunctionComparator::cmpOperations in
439 // lib/Transforms/IPO/MergeFunctions.cpp.
440 bool Instruction::isSameOperationAs(const Instruction *I,
441                                     unsigned flags) const {
442   bool IgnoreAlignment = flags & CompareIgnoringAlignment;
443   bool UseScalarTypes  = flags & CompareUsingScalarTypes;
444 
445   if (getOpcode() != I->getOpcode() ||
446       getNumOperands() != I->getNumOperands() ||
447       (UseScalarTypes ?
448        getType()->getScalarType() != I->getType()->getScalarType() :
449        getType() != I->getType()))
450     return false;
451 
452   // We have two instructions of identical opcode and #operands.  Check to see
453   // if all operands are the same type
454   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
455     if (UseScalarTypes ?
456         getOperand(i)->getType()->getScalarType() !=
457           I->getOperand(i)->getType()->getScalarType() :
458         getOperand(i)->getType() != I->getOperand(i)->getType())
459       return false;
460 
461   return haveSameSpecialState(this, I, IgnoreAlignment);
462 }
463 
464 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
465   for (const Use &U : uses()) {
466     // PHI nodes uses values in the corresponding predecessor block.  For other
467     // instructions, just check to see whether the parent of the use matches up.
468     const Instruction *I = cast<Instruction>(U.getUser());
469     const PHINode *PN = dyn_cast<PHINode>(I);
470     if (!PN) {
471       if (I->getParent() != BB)
472         return true;
473       continue;
474     }
475 
476     if (PN->getIncomingBlock(U) != BB)
477       return true;
478   }
479   return false;
480 }
481 
482 bool Instruction::mayReadFromMemory() const {
483   switch (getOpcode()) {
484   default: return false;
485   case Instruction::VAArg:
486   case Instruction::Load:
487   case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
488   case Instruction::AtomicCmpXchg:
489   case Instruction::AtomicRMW:
490   case Instruction::CatchPad:
491   case Instruction::CatchRet:
492     return true;
493   case Instruction::Call:
494     return !cast<CallInst>(this)->doesNotAccessMemory();
495   case Instruction::Invoke:
496     return !cast<InvokeInst>(this)->doesNotAccessMemory();
497   case Instruction::Store:
498     return !cast<StoreInst>(this)->isUnordered();
499   }
500 }
501 
502 bool Instruction::mayWriteToMemory() const {
503   switch (getOpcode()) {
504   default: return false;
505   case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
506   case Instruction::Store:
507   case Instruction::VAArg:
508   case Instruction::AtomicCmpXchg:
509   case Instruction::AtomicRMW:
510   case Instruction::CatchPad:
511   case Instruction::CatchRet:
512     return true;
513   case Instruction::Call:
514     return !cast<CallInst>(this)->onlyReadsMemory();
515   case Instruction::Invoke:
516     return !cast<InvokeInst>(this)->onlyReadsMemory();
517   case Instruction::Load:
518     return !cast<LoadInst>(this)->isUnordered();
519   }
520 }
521 
522 bool Instruction::isAtomic() const {
523   switch (getOpcode()) {
524   default:
525     return false;
526   case Instruction::AtomicCmpXchg:
527   case Instruction::AtomicRMW:
528   case Instruction::Fence:
529     return true;
530   case Instruction::Load:
531     return cast<LoadInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
532   case Instruction::Store:
533     return cast<StoreInst>(this)->getOrdering() != AtomicOrdering::NotAtomic;
534   }
535 }
536 
537 bool Instruction::mayThrow() const {
538   if (const CallInst *CI = dyn_cast<CallInst>(this))
539     return !CI->doesNotThrow();
540   if (const auto *CRI = dyn_cast<CleanupReturnInst>(this))
541     return CRI->unwindsToCaller();
542   if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(this))
543     return CatchSwitch->unwindsToCaller();
544   return isa<ResumeInst>(this);
545 }
546 
547 /// Return true if the instruction is associative:
548 ///
549 ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
550 ///
551 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
552 ///
553 bool Instruction::isAssociative(unsigned Opcode) {
554   return Opcode == And || Opcode == Or || Opcode == Xor ||
555          Opcode == Add || Opcode == Mul;
556 }
557 
558 bool Instruction::isAssociative() const {
559   unsigned Opcode = getOpcode();
560   if (isAssociative(Opcode))
561     return true;
562 
563   switch (Opcode) {
564   case FMul:
565   case FAdd:
566     return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
567   default:
568     return false;
569   }
570 }
571 
572 /// Return true if the instruction is commutative:
573 ///
574 ///   Commutative operators satisfy: (x op y) === (y op x)
575 ///
576 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
577 /// applied to any type.
578 ///
579 bool Instruction::isCommutative(unsigned op) {
580   switch (op) {
581   case Add:
582   case FAdd:
583   case Mul:
584   case FMul:
585   case And:
586   case Or:
587   case Xor:
588     return true;
589   default:
590     return false;
591   }
592 }
593 
594 /// Return true if the instruction is idempotent:
595 ///
596 ///   Idempotent operators satisfy:  x op x === x
597 ///
598 /// In LLVM, the And and Or operators are idempotent.
599 ///
600 bool Instruction::isIdempotent(unsigned Opcode) {
601   return Opcode == And || Opcode == Or;
602 }
603 
604 /// Return true if the instruction is nilpotent:
605 ///
606 ///   Nilpotent operators satisfy:  x op x === Id,
607 ///
608 ///   where Id is the identity for the operator, i.e. a constant such that
609 ///     x op Id === x and Id op x === x for all x.
610 ///
611 /// In LLVM, the Xor operator is nilpotent.
612 ///
613 bool Instruction::isNilpotent(unsigned Opcode) {
614   return Opcode == Xor;
615 }
616 
617 Instruction *Instruction::cloneImpl() const {
618   llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
619 }
620 
621 void Instruction::swapProfMetadata() {
622   MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
623   if (!ProfileData || ProfileData->getNumOperands() != 3 ||
624       !isa<MDString>(ProfileData->getOperand(0)))
625     return;
626 
627   MDString *MDName = cast<MDString>(ProfileData->getOperand(0));
628   if (MDName->getString() != "branch_weights")
629     return;
630 
631   // The first operand is the name. Fetch them backwards and build a new one.
632   Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
633                      ProfileData->getOperand(1)};
634   setMetadata(LLVMContext::MD_prof,
635               MDNode::get(ProfileData->getContext(), Ops));
636 }
637 
638 void Instruction::copyMetadata(const Instruction &SrcInst,
639                                ArrayRef<unsigned> WL) {
640   if (!SrcInst.hasMetadata())
641     return;
642 
643   DenseSet<unsigned> WLS;
644   for (unsigned M : WL)
645     WLS.insert(M);
646 
647   // Otherwise, enumerate and copy over metadata from the old instruction to the
648   // new one.
649   SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
650   SrcInst.getAllMetadataOtherThanDebugLoc(TheMDs);
651   for (const auto &MD : TheMDs) {
652     if (WL.empty() || WLS.count(MD.first))
653       setMetadata(MD.first, MD.second);
654   }
655   if (WL.empty() || WLS.count(LLVMContext::MD_dbg))
656     setDebugLoc(SrcInst.getDebugLoc());
657   return;
658 }
659 
660 Instruction *Instruction::clone() const {
661   Instruction *New = nullptr;
662   switch (getOpcode()) {
663   default:
664     llvm_unreachable("Unhandled Opcode.");
665 #define HANDLE_INST(num, opc, clas)                                            \
666   case Instruction::opc:                                                       \
667     New = cast<clas>(this)->cloneImpl();                                       \
668     break;
669 #include "llvm/IR/Instruction.def"
670 #undef HANDLE_INST
671   }
672 
673   New->SubclassOptionalData = SubclassOptionalData;
674   New->copyMetadata(*this);
675   return New;
676 }
677