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