Fast-math interfaces for Instructions
[oota-llvm.git] / lib / VMCore / Instruction.cpp
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 VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Instruction.h"
15 #include "llvm/Type.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Support/CallSite.h"
21 #include "llvm/Support/LeakDetector.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(0) {
27   // Make sure that we get added to a basicblock
28   LeakDetector::addGarbageObject(this);
29
30   // If requested, insert this instruction into a basic block...
31   if (InsertBefore) {
32     assert(InsertBefore->getParent() &&
33            "Instruction to insert before is not in a basic block!");
34     InsertBefore->getParent()->getInstList().insert(InsertBefore, this);
35   }
36 }
37
38 Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
39                          BasicBlock *InsertAtEnd)
40   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0) {
41   // Make sure that we get added to a basicblock
42   LeakDetector::addGarbageObject(this);
43
44   // append this instruction into the basic block
45   assert(InsertAtEnd && "Basic block to append to may not be NULL!");
46   InsertAtEnd->getInstList().push_back(this);
47 }
48
49
50 // Out of line virtual method, so the vtable, etc has a home.
51 Instruction::~Instruction() {
52   assert(Parent == 0 && "Instruction still linked in the program!");
53   if (hasMetadataHashEntry())
54     clearMetadataHashEntries();
55 }
56
57
58 void Instruction::setParent(BasicBlock *P) {
59   if (getParent()) {
60     if (!P) LeakDetector::addGarbageObject(this);
61   } else {
62     if (P) LeakDetector::removeGarbageObject(this);
63   }
64
65   Parent = P;
66 }
67
68 void Instruction::removeFromParent() {
69   getParent()->getInstList().remove(this);
70 }
71
72 void Instruction::eraseFromParent() {
73   getParent()->getInstList().erase(this);
74 }
75
76 /// insertBefore - Insert an unlinked instructions into a basic block
77 /// immediately before the specified instruction.
78 void Instruction::insertBefore(Instruction *InsertPos) {
79   InsertPos->getParent()->getInstList().insert(InsertPos, this);
80 }
81
82 /// insertAfter - Insert an unlinked instructions into a basic block
83 /// immediately after the specified instruction.
84 void Instruction::insertAfter(Instruction *InsertPos) {
85   InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
86 }
87
88 /// moveBefore - Unlink this instruction from its current basic block and
89 /// insert it into the basic block that MovePos lives in, right before
90 /// MovePos.
91 void Instruction::moveBefore(Instruction *MovePos) {
92   MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
93                                              this);
94 }
95
96 /// Set or clear the unsafe-algebra flag on this instruction, which must be an
97 /// operator which supports this flag. See LangRef.html for the meaning of this
98 /// flag.
99 void Instruction::setHasUnsafeAlgebra(bool B) {
100   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
101   cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
102 }
103
104 /// Set or clear the NoNaNs flag on this instruction, which must be an operator
105 /// which supports this flag. See LangRef.html for the meaning of this flag.
106 void Instruction::setHasNoNaNs(bool B) {
107   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
108   cast<FPMathOperator>(this)->setHasNoNaNs(B);
109 }
110
111 /// Set or clear the no-infs flag on this instruction, which must be an operator
112 /// which supports this flag. See LangRef.html for the meaning of this flag.
113 void Instruction::setHasNoInfs(bool B) {
114   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
115   cast<FPMathOperator>(this)->setHasNoInfs(B);
116 }
117
118 /// Set or clear the no-signed-zeros flag on this instruction, which must be an
119 /// operator which supports this flag. See LangRef.html for the meaning of this
120 /// flag.
121 void Instruction::setHasNoSignedZeros(bool B) {
122   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
123   cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
124 }
125
126 /// Set or clear the allow-reciprocal flag on this instruction, which must be an
127 /// operator which supports this flag. See LangRef.html for the meaning of this
128 /// flag.
129 void Instruction::setHasAllowReciprocal(bool B) {
130   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
131   cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
132 }
133
134 /// Convenience function for setting all the fast-math flags on this
135 /// instruction, which must be an operator which supports these flags. See
136 /// LangRef.html for the meaning of these flats.
137 void Instruction::setFastMathFlags(FastMathFlags FMF) {
138   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
139   cast<FPMathOperator>(this)->setFastMathFlags(FMF);
140 }
141
142 /// Determine whether the unsafe-algebra flag is set.
143 bool Instruction::hasUnsafeAlgebra() const {
144   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
145   return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
146 }
147
148 /// Determine whether the no-NaNs flag is set.
149 bool Instruction::hasNoNaNs() const {
150   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
151   return cast<FPMathOperator>(this)->hasNoNaNs();
152 }
153
154 /// Determine whether the no-infs flag is set.
155 bool Instruction::hasNoInfs() const {
156   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
157   return cast<FPMathOperator>(this)->hasNoInfs();
158 }
159
160 /// Determine whether the no-signed-zeros flag is set.
161 bool Instruction::hasNoSignedZeros() const {
162   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
163   return cast<FPMathOperator>(this)->hasNoSignedZeros();
164 }
165
166 /// Determine whether the allow-reciprocal flag is set.
167 bool Instruction::hasAllowReciprocal() const {
168   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
169   return cast<FPMathOperator>(this)->hasAllowReciprocal();
170 }
171
172 /// Convenience function for getting all the fast-math flags, which must be an
173 /// operator which supports these flags. See LangRef.html for the meaning of
174 /// these flats.
175 FastMathFlags Instruction::getFastMathFlags() const {
176   assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
177   return cast<FPMathOperator>(this)->getFastMathFlags();
178 }
179
180 const char *Instruction::getOpcodeName(unsigned OpCode) {
181   switch (OpCode) {
182   // Terminators
183   case Ret:    return "ret";
184   case Br:     return "br";
185   case Switch: return "switch";
186   case IndirectBr: return "indirectbr";
187   case Invoke: return "invoke";
188   case Resume: return "resume";
189   case Unreachable: return "unreachable";
190
191   // Standard binary operators...
192   case Add: return "add";
193   case FAdd: return "fadd";
194   case Sub: return "sub";
195   case FSub: return "fsub";
196   case Mul: return "mul";
197   case FMul: return "fmul";
198   case UDiv: return "udiv";
199   case SDiv: return "sdiv";
200   case FDiv: return "fdiv";
201   case URem: return "urem";
202   case SRem: return "srem";
203   case FRem: return "frem";
204
205   // Logical operators...
206   case And: return "and";
207   case Or : return "or";
208   case Xor: return "xor";
209
210   // Memory instructions...
211   case Alloca:        return "alloca";
212   case Load:          return "load";
213   case Store:         return "store";
214   case AtomicCmpXchg: return "cmpxchg";
215   case AtomicRMW:     return "atomicrmw";
216   case Fence:         return "fence";
217   case GetElementPtr: return "getelementptr";
218
219   // Convert instructions...
220   case Trunc:     return "trunc";
221   case ZExt:      return "zext";
222   case SExt:      return "sext";
223   case FPTrunc:   return "fptrunc";
224   case FPExt:     return "fpext";
225   case FPToUI:    return "fptoui";
226   case FPToSI:    return "fptosi";
227   case UIToFP:    return "uitofp";
228   case SIToFP:    return "sitofp";
229   case IntToPtr:  return "inttoptr";
230   case PtrToInt:  return "ptrtoint";
231   case BitCast:   return "bitcast";
232
233   // Other instructions...
234   case ICmp:           return "icmp";
235   case FCmp:           return "fcmp";
236   case PHI:            return "phi";
237   case Select:         return "select";
238   case Call:           return "call";
239   case Shl:            return "shl";
240   case LShr:           return "lshr";
241   case AShr:           return "ashr";
242   case VAArg:          return "va_arg";
243   case ExtractElement: return "extractelement";
244   case InsertElement:  return "insertelement";
245   case ShuffleVector:  return "shufflevector";
246   case ExtractValue:   return "extractvalue";
247   case InsertValue:    return "insertvalue";
248   case LandingPad:     return "landingpad";
249
250   default: return "<Invalid operator> ";
251   }
252 }
253
254 /// isIdenticalTo - Return true if the specified instruction is exactly
255 /// identical to the current one.  This means that all operands match and any
256 /// extra information (e.g. load is volatile) agree.
257 bool Instruction::isIdenticalTo(const Instruction *I) const {
258   return isIdenticalToWhenDefined(I) &&
259          SubclassOptionalData == I->SubclassOptionalData;
260 }
261
262 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
263 /// ignores the SubclassOptionalData flags, which specify conditions
264 /// under which the instruction's result is undefined.
265 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
266   if (getOpcode() != I->getOpcode() ||
267       getNumOperands() != I->getNumOperands() ||
268       getType() != I->getType())
269     return false;
270
271   // We have two instructions of identical opcode and #operands.  Check to see
272   // if all operands are the same.
273   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
274     if (getOperand(i) != I->getOperand(i))
275       return false;
276
277   // Check special state that is a part of some instructions.
278   if (const LoadInst *LI = dyn_cast<LoadInst>(this))
279     return LI->isVolatile() == cast<LoadInst>(I)->isVolatile() &&
280            LI->getAlignment() == cast<LoadInst>(I)->getAlignment() &&
281            LI->getOrdering() == cast<LoadInst>(I)->getOrdering() &&
282            LI->getSynchScope() == cast<LoadInst>(I)->getSynchScope();
283   if (const StoreInst *SI = dyn_cast<StoreInst>(this))
284     return SI->isVolatile() == cast<StoreInst>(I)->isVolatile() &&
285            SI->getAlignment() == cast<StoreInst>(I)->getAlignment() &&
286            SI->getOrdering() == cast<StoreInst>(I)->getOrdering() &&
287            SI->getSynchScope() == cast<StoreInst>(I)->getSynchScope();
288   if (const CmpInst *CI = dyn_cast<CmpInst>(this))
289     return CI->getPredicate() == cast<CmpInst>(I)->getPredicate();
290   if (const CallInst *CI = dyn_cast<CallInst>(this))
291     return CI->isTailCall() == cast<CallInst>(I)->isTailCall() &&
292            CI->getCallingConv() == cast<CallInst>(I)->getCallingConv() &&
293            CI->getAttributes() == cast<CallInst>(I)->getAttributes();
294   if (const InvokeInst *CI = dyn_cast<InvokeInst>(this))
295     return CI->getCallingConv() == cast<InvokeInst>(I)->getCallingConv() &&
296            CI->getAttributes() == cast<InvokeInst>(I)->getAttributes();
297   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(this))
298     return IVI->getIndices() == cast<InsertValueInst>(I)->getIndices();
299   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(this))
300     return EVI->getIndices() == cast<ExtractValueInst>(I)->getIndices();
301   if (const FenceInst *FI = dyn_cast<FenceInst>(this))
302     return FI->getOrdering() == cast<FenceInst>(FI)->getOrdering() &&
303            FI->getSynchScope() == cast<FenceInst>(FI)->getSynchScope();
304   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(this))
305     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I)->isVolatile() &&
306            CXI->getOrdering() == cast<AtomicCmpXchgInst>(I)->getOrdering() &&
307            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I)->getSynchScope();
308   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(this))
309     return RMWI->getOperation() == cast<AtomicRMWInst>(I)->getOperation() &&
310            RMWI->isVolatile() == cast<AtomicRMWInst>(I)->isVolatile() &&
311            RMWI->getOrdering() == cast<AtomicRMWInst>(I)->getOrdering() &&
312            RMWI->getSynchScope() == cast<AtomicRMWInst>(I)->getSynchScope();
313   if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
314     const PHINode *otherPHI = cast<PHINode>(I);
315     for (unsigned i = 0, e = thisPHI->getNumOperands(); i != e; ++i) {
316       if (thisPHI->getIncomingBlock(i) != otherPHI->getIncomingBlock(i))
317         return false;
318     }
319     return true;
320   }
321   return true;
322 }
323
324 // isSameOperationAs
325 // This should be kept in sync with isEquivalentOperation in
326 // lib/Transforms/IPO/MergeFunctions.cpp.
327 bool Instruction::isSameOperationAs(const Instruction *I,
328                                     unsigned flags) const {
329   bool IgnoreAlignment = flags & CompareIgnoringAlignment;
330   bool UseScalarTypes  = flags & CompareUsingScalarTypes;
331
332   if (getOpcode() != I->getOpcode() ||
333       getNumOperands() != I->getNumOperands() ||
334       (UseScalarTypes ?
335        getType()->getScalarType() != I->getType()->getScalarType() :
336        getType() != I->getType()))
337     return false;
338
339   // We have two instructions of identical opcode and #operands.  Check to see
340   // if all operands are the same type
341   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
342     if (UseScalarTypes ?
343         getOperand(i)->getType()->getScalarType() !=
344           I->getOperand(i)->getType()->getScalarType() :
345         getOperand(i)->getType() != I->getOperand(i)->getType())
346       return false;
347
348   // Check special state that is a part of some instructions.
349   if (const LoadInst *LI = dyn_cast<LoadInst>(this))
350     return LI->isVolatile() == cast<LoadInst>(I)->isVolatile() &&
351            (LI->getAlignment() == cast<LoadInst>(I)->getAlignment() ||
352             IgnoreAlignment) &&
353            LI->getOrdering() == cast<LoadInst>(I)->getOrdering() &&
354            LI->getSynchScope() == cast<LoadInst>(I)->getSynchScope();
355   if (const StoreInst *SI = dyn_cast<StoreInst>(this))
356     return SI->isVolatile() == cast<StoreInst>(I)->isVolatile() &&
357            (SI->getAlignment() == cast<StoreInst>(I)->getAlignment() ||
358             IgnoreAlignment) &&
359            SI->getOrdering() == cast<StoreInst>(I)->getOrdering() &&
360            SI->getSynchScope() == cast<StoreInst>(I)->getSynchScope();
361   if (const CmpInst *CI = dyn_cast<CmpInst>(this))
362     return CI->getPredicate() == cast<CmpInst>(I)->getPredicate();
363   if (const CallInst *CI = dyn_cast<CallInst>(this))
364     return CI->isTailCall() == cast<CallInst>(I)->isTailCall() &&
365            CI->getCallingConv() == cast<CallInst>(I)->getCallingConv() &&
366            CI->getAttributes() == cast<CallInst>(I)->getAttributes();
367   if (const InvokeInst *CI = dyn_cast<InvokeInst>(this))
368     return CI->getCallingConv() == cast<InvokeInst>(I)->getCallingConv() &&
369            CI->getAttributes() ==
370              cast<InvokeInst>(I)->getAttributes();
371   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(this))
372     return IVI->getIndices() == cast<InsertValueInst>(I)->getIndices();
373   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(this))
374     return EVI->getIndices() == cast<ExtractValueInst>(I)->getIndices();
375   if (const FenceInst *FI = dyn_cast<FenceInst>(this))
376     return FI->getOrdering() == cast<FenceInst>(I)->getOrdering() &&
377            FI->getSynchScope() == cast<FenceInst>(I)->getSynchScope();
378   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(this))
379     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I)->isVolatile() &&
380            CXI->getOrdering() == cast<AtomicCmpXchgInst>(I)->getOrdering() &&
381            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I)->getSynchScope();
382   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(this))
383     return RMWI->getOperation() == cast<AtomicRMWInst>(I)->getOperation() &&
384            RMWI->isVolatile() == cast<AtomicRMWInst>(I)->isVolatile() &&
385            RMWI->getOrdering() == cast<AtomicRMWInst>(I)->getOrdering() &&
386            RMWI->getSynchScope() == cast<AtomicRMWInst>(I)->getSynchScope();
387
388   return true;
389 }
390
391 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
392 /// specified block.  Note that PHI nodes are considered to evaluate their
393 /// operands in the corresponding predecessor block.
394 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
395   for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
396     // PHI nodes uses values in the corresponding predecessor block.  For other
397     // instructions, just check to see whether the parent of the use matches up.
398     const User *U = *UI;
399     const PHINode *PN = dyn_cast<PHINode>(U);
400     if (PN == 0) {
401       if (cast<Instruction>(U)->getParent() != BB)
402         return true;
403       continue;
404     }
405
406     if (PN->getIncomingBlock(UI) != BB)
407       return true;
408   }
409   return false;
410 }
411
412 /// mayReadFromMemory - Return true if this instruction may read memory.
413 ///
414 bool Instruction::mayReadFromMemory() const {
415   switch (getOpcode()) {
416   default: return false;
417   case Instruction::VAArg:
418   case Instruction::Load:
419   case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
420   case Instruction::AtomicCmpXchg:
421   case Instruction::AtomicRMW:
422     return true;
423   case Instruction::Call:
424     return !cast<CallInst>(this)->doesNotAccessMemory();
425   case Instruction::Invoke:
426     return !cast<InvokeInst>(this)->doesNotAccessMemory();
427   case Instruction::Store:
428     return !cast<StoreInst>(this)->isUnordered();
429   }
430 }
431
432 /// mayWriteToMemory - Return true if this instruction may modify memory.
433 ///
434 bool Instruction::mayWriteToMemory() const {
435   switch (getOpcode()) {
436   default: return false;
437   case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
438   case Instruction::Store:
439   case Instruction::VAArg:
440   case Instruction::AtomicCmpXchg:
441   case Instruction::AtomicRMW:
442     return true;
443   case Instruction::Call:
444     return !cast<CallInst>(this)->onlyReadsMemory();
445   case Instruction::Invoke:
446     return !cast<InvokeInst>(this)->onlyReadsMemory();
447   case Instruction::Load:
448     return !cast<LoadInst>(this)->isUnordered();
449   }
450 }
451
452 /// mayThrow - Return true if this instruction may throw an exception.
453 ///
454 bool Instruction::mayThrow() const {
455   if (const CallInst *CI = dyn_cast<CallInst>(this))
456     return !CI->doesNotThrow();
457   return isa<ResumeInst>(this);
458 }
459
460 /// isAssociative - Return true if the instruction is associative:
461 ///
462 ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
463 ///
464 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
465 ///
466 bool Instruction::isAssociative(unsigned Opcode) {
467   return Opcode == And || Opcode == Or || Opcode == Xor ||
468          Opcode == Add || Opcode == Mul;
469 }
470
471 /// isCommutative - Return true if the instruction is commutative:
472 ///
473 ///   Commutative operators satisfy: (x op y) === (y op x)
474 ///
475 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
476 /// applied to any type.
477 ///
478 bool Instruction::isCommutative(unsigned op) {
479   switch (op) {
480   case Add:
481   case FAdd:
482   case Mul:
483   case FMul:
484   case And:
485   case Or:
486   case Xor:
487     return true;
488   default:
489     return false;
490   }
491 }
492
493 /// isIdempotent - Return true if the instruction is idempotent:
494 ///
495 ///   Idempotent operators satisfy:  x op x === x
496 ///
497 /// In LLVM, the And and Or operators are idempotent.
498 ///
499 bool Instruction::isIdempotent(unsigned Opcode) {
500   return Opcode == And || Opcode == Or;
501 }
502
503 /// isNilpotent - Return true if the instruction is nilpotent:
504 ///
505 ///   Nilpotent operators satisfy:  x op x === Id,
506 ///
507 ///   where Id is the identity for the operator, i.e. a constant such that
508 ///     x op Id === x and Id op x === x for all x.
509 ///
510 /// In LLVM, the Xor operator is nilpotent.
511 ///
512 bool Instruction::isNilpotent(unsigned Opcode) {
513   return Opcode == Xor;
514 }
515
516 Instruction *Instruction::clone() const {
517   Instruction *New = clone_impl();
518   New->SubclassOptionalData = SubclassOptionalData;
519   if (!hasMetadata())
520     return New;
521
522   // Otherwise, enumerate and copy over metadata from the old instruction to the
523   // new one.
524   SmallVector<std::pair<unsigned, MDNode*>, 4> TheMDs;
525   getAllMetadataOtherThanDebugLoc(TheMDs);
526   for (unsigned i = 0, e = TheMDs.size(); i != e; ++i)
527     New->setMetadata(TheMDs[i].first, TheMDs[i].second);
528
529   New->setDebugLoc(getDebugLoc());
530   return New;
531 }