Rename MallocHelper as MallocFreeHelper, since it now also identifies calls to free()
[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 "LLVMContextImpl.h"
15 #include "llvm/Type.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Function.h"
18 #include "llvm/Constants.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Module.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/LeakDetector.h"
23 using namespace llvm;
24
25 Instruction::Instruction(const Type *ty, unsigned it, Use *Ops, unsigned NumOps,
26                          Instruction *InsertBefore)
27   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0) {
28   // Make sure that we get added to a basicblock
29   LeakDetector::addGarbageObject(this);
30
31   // If requested, insert this instruction into a basic block...
32   if (InsertBefore) {
33     assert(InsertBefore->getParent() &&
34            "Instruction to insert before is not in a basic block!");
35     InsertBefore->getParent()->getInstList().insert(InsertBefore, this);
36   }
37 }
38
39 Instruction::Instruction(const Type *ty, unsigned it, Use *Ops, unsigned NumOps,
40                          BasicBlock *InsertAtEnd)
41   : User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(0) {
42   // Make sure that we get added to a basicblock
43   LeakDetector::addGarbageObject(this);
44
45   // append this instruction into the basic block
46   assert(InsertAtEnd && "Basic block to append to may not be NULL!");
47   InsertAtEnd->getInstList().push_back(this);
48 }
49
50
51 // Out of line virtual method, so the vtable, etc has a home.
52 Instruction::~Instruction() {
53   assert(Parent == 0 && "Instruction still linked in the program!");
54   if (hasMetadata()) {
55     LLVMContext &Context = getContext();
56     Context.pImpl->TheMetadata.ValueIsDeleted(this);
57   }
58 }
59
60
61 void Instruction::setParent(BasicBlock *P) {
62   if (getParent()) {
63     if (!P) LeakDetector::addGarbageObject(this);
64   } else {
65     if (P) LeakDetector::removeGarbageObject(this);
66   }
67
68   Parent = P;
69 }
70
71 void Instruction::removeFromParent() {
72   getParent()->getInstList().remove(this);
73 }
74
75 void Instruction::eraseFromParent() {
76   getParent()->getInstList().erase(this);
77 }
78
79 /// insertBefore - Insert an unlinked instructions into a basic block
80 /// immediately before the specified instruction.
81 void Instruction::insertBefore(Instruction *InsertPos) {
82   InsertPos->getParent()->getInstList().insert(InsertPos, this);
83 }
84
85 /// insertAfter - Insert an unlinked instructions into a basic block
86 /// immediately after the specified instruction.
87 void Instruction::insertAfter(Instruction *InsertPos) {
88   InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
89 }
90
91 /// moveBefore - Unlink this instruction from its current basic block and
92 /// insert it into the basic block that MovePos lives in, right before
93 /// MovePos.
94 void Instruction::moveBefore(Instruction *MovePos) {
95   MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
96                                              this);
97 }
98
99
100 const char *Instruction::getOpcodeName(unsigned OpCode) {
101   switch (OpCode) {
102   // Terminators
103   case Ret:    return "ret";
104   case Br:     return "br";
105   case Switch: return "switch";
106   case Invoke: return "invoke";
107   case Unwind: return "unwind";
108   case Unreachable: return "unreachable";
109
110   // Standard binary operators...
111   case Add: return "add";
112   case FAdd: return "fadd";
113   case Sub: return "sub";
114   case FSub: return "fsub";
115   case Mul: return "mul";
116   case FMul: return "fmul";
117   case UDiv: return "udiv";
118   case SDiv: return "sdiv";
119   case FDiv: return "fdiv";
120   case URem: return "urem";
121   case SRem: return "srem";
122   case FRem: return "frem";
123
124   // Logical operators...
125   case And: return "and";
126   case Or : return "or";
127   case Xor: return "xor";
128
129   // Memory instructions...
130   case Alloca:        return "alloca";
131   case Load:          return "load";
132   case Store:         return "store";
133   case GetElementPtr: return "getelementptr";
134
135   // Convert instructions...
136   case Trunc:     return "trunc";
137   case ZExt:      return "zext";
138   case SExt:      return "sext";
139   case FPTrunc:   return "fptrunc";
140   case FPExt:     return "fpext";
141   case FPToUI:    return "fptoui";
142   case FPToSI:    return "fptosi";
143   case UIToFP:    return "uitofp";
144   case SIToFP:    return "sitofp";
145   case IntToPtr:  return "inttoptr";
146   case PtrToInt:  return "ptrtoint";
147   case BitCast:   return "bitcast";
148
149   // Other instructions...
150   case ICmp:           return "icmp";
151   case FCmp:           return "fcmp";
152   case PHI:            return "phi";
153   case Select:         return "select";
154   case Call:           return "call";
155   case Shl:            return "shl";
156   case LShr:           return "lshr";
157   case AShr:           return "ashr";
158   case VAArg:          return "va_arg";
159   case ExtractElement: return "extractelement";
160   case InsertElement:  return "insertelement";
161   case ShuffleVector:  return "shufflevector";
162   case ExtractValue:   return "extractvalue";
163   case InsertValue:    return "insertvalue";
164
165   default: return "<Invalid operator> ";
166   }
167
168   return 0;
169 }
170
171 /// isIdenticalTo - Return true if the specified instruction is exactly
172 /// identical to the current one.  This means that all operands match and any
173 /// extra information (e.g. load is volatile) agree.
174 bool Instruction::isIdenticalTo(const Instruction *I) const {
175   return isIdenticalToWhenDefined(I) &&
176          SubclassOptionalData == I->SubclassOptionalData;
177 }
178
179 /// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
180 /// ignores the SubclassOptionalData flags, which specify conditions
181 /// under which the instruction's result is undefined.
182 bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
183   if (getOpcode() != I->getOpcode() ||
184       getNumOperands() != I->getNumOperands() ||
185       getType() != I->getType())
186     return false;
187
188   // We have two instructions of identical opcode and #operands.  Check to see
189   // if all operands are the same.
190   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
191     if (getOperand(i) != I->getOperand(i))
192       return false;
193
194   // Check special state that is a part of some instructions.
195   if (const LoadInst *LI = dyn_cast<LoadInst>(this))
196     return LI->isVolatile() == cast<LoadInst>(I)->isVolatile() &&
197            LI->getAlignment() == cast<LoadInst>(I)->getAlignment();
198   if (const StoreInst *SI = dyn_cast<StoreInst>(this))
199     return SI->isVolatile() == cast<StoreInst>(I)->isVolatile() &&
200            SI->getAlignment() == cast<StoreInst>(I)->getAlignment();
201   if (const CmpInst *CI = dyn_cast<CmpInst>(this))
202     return CI->getPredicate() == cast<CmpInst>(I)->getPredicate();
203   if (const CallInst *CI = dyn_cast<CallInst>(this))
204     return CI->isTailCall() == cast<CallInst>(I)->isTailCall() &&
205            CI->getCallingConv() == cast<CallInst>(I)->getCallingConv() &&
206            CI->getAttributes().getRawPointer() ==
207              cast<CallInst>(I)->getAttributes().getRawPointer();
208   if (const InvokeInst *CI = dyn_cast<InvokeInst>(this))
209     return CI->getCallingConv() == cast<InvokeInst>(I)->getCallingConv() &&
210            CI->getAttributes().getRawPointer() ==
211              cast<InvokeInst>(I)->getAttributes().getRawPointer();
212   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(this)) {
213     if (IVI->getNumIndices() != cast<InsertValueInst>(I)->getNumIndices())
214       return false;
215     for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
216       if (IVI->idx_begin()[i] != cast<InsertValueInst>(I)->idx_begin()[i])
217         return false;
218     return true;
219   }
220   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(this)) {
221     if (EVI->getNumIndices() != cast<ExtractValueInst>(I)->getNumIndices())
222       return false;
223     for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
224       if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I)->idx_begin()[i])
225         return false;
226     return true;
227   }
228
229   return true;
230 }
231
232 // isSameOperationAs
233 // This should be kept in sync with isEquivalentOperation in
234 // lib/Transforms/IPO/MergeFunctions.cpp.
235 bool Instruction::isSameOperationAs(const Instruction *I) const {
236   if (getOpcode() != I->getOpcode() ||
237       getNumOperands() != I->getNumOperands() ||
238       getType() != I->getType())
239     return false;
240
241   // We have two instructions of identical opcode and #operands.  Check to see
242   // if all operands are the same type
243   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
244     if (getOperand(i)->getType() != I->getOperand(i)->getType())
245       return false;
246
247   // Check special state that is a part of some instructions.
248   if (const LoadInst *LI = dyn_cast<LoadInst>(this))
249     return LI->isVolatile() == cast<LoadInst>(I)->isVolatile() &&
250            LI->getAlignment() == cast<LoadInst>(I)->getAlignment();
251   if (const StoreInst *SI = dyn_cast<StoreInst>(this))
252     return SI->isVolatile() == cast<StoreInst>(I)->isVolatile() &&
253            SI->getAlignment() == cast<StoreInst>(I)->getAlignment();
254   if (const CmpInst *CI = dyn_cast<CmpInst>(this))
255     return CI->getPredicate() == cast<CmpInst>(I)->getPredicate();
256   if (const CallInst *CI = dyn_cast<CallInst>(this))
257     return CI->isTailCall() == cast<CallInst>(I)->isTailCall() &&
258            CI->getCallingConv() == cast<CallInst>(I)->getCallingConv() &&
259            CI->getAttributes().getRawPointer() ==
260              cast<CallInst>(I)->getAttributes().getRawPointer();
261   if (const InvokeInst *CI = dyn_cast<InvokeInst>(this))
262     return CI->getCallingConv() == cast<InvokeInst>(I)->getCallingConv() &&
263            CI->getAttributes().getRawPointer() ==
264              cast<InvokeInst>(I)->getAttributes().getRawPointer();
265   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(this)) {
266     if (IVI->getNumIndices() != cast<InsertValueInst>(I)->getNumIndices())
267       return false;
268     for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
269       if (IVI->idx_begin()[i] != cast<InsertValueInst>(I)->idx_begin()[i])
270         return false;
271     return true;
272   }
273   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(this)) {
274     if (EVI->getNumIndices() != cast<ExtractValueInst>(I)->getNumIndices())
275       return false;
276     for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
277       if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I)->idx_begin()[i])
278         return false;
279     return true;
280   }
281
282   return true;
283 }
284
285 /// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
286 /// specified block.  Note that PHI nodes are considered to evaluate their
287 /// operands in the corresponding predecessor block.
288 bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
289   for (use_const_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
290     // PHI nodes uses values in the corresponding predecessor block.  For other
291     // instructions, just check to see whether the parent of the use matches up.
292     const PHINode *PN = dyn_cast<PHINode>(*UI);
293     if (PN == 0) {
294       if (cast<Instruction>(*UI)->getParent() != BB)
295         return true;
296       continue;
297     }
298
299     if (PN->getIncomingBlock(UI) != BB)
300       return true;
301   }
302   return false;
303 }
304
305 // Code here matches isFreeCall from MallocFreeHelper, which is not in VMCore.
306 static bool isFreeCall(const Value* I) {
307   const CallInst *CI = dyn_cast<CallInst>(I);
308   if (!CI)
309     return false;
310
311   const Module* M = CI->getParent()->getParent()->getParent();
312   Function *FreeFunc = M->getFunction("free");
313
314   if (CI->getOperand(0) != FreeFunc)
315     return false;
316
317   // Check free prototype.
318   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin 
319   // attribute will exist.
320   const FunctionType *FTy = FreeFunc->getFunctionType();
321   if (FTy->getReturnType() != Type::getVoidTy(M->getContext()))
322     return false;
323   if (FTy->getNumParams() != 1)
324     return false;
325   if (FTy->param_begin()->get() != Type::getInt8PtrTy(M->getContext()))
326     return false;
327
328   return true;
329 }
330
331 /// mayReadFromMemory - Return true if this instruction may read memory.
332 ///
333 bool Instruction::mayReadFromMemory() const {
334   switch (getOpcode()) {
335   default: return false;
336   case Instruction::VAArg:
337   case Instruction::Load:
338     return true;
339   case Instruction::Call:
340     if (isFreeCall(this))
341       return true;
342     return !cast<CallInst>(this)->doesNotAccessMemory();
343   case Instruction::Invoke:
344     return !cast<InvokeInst>(this)->doesNotAccessMemory();
345   case Instruction::Store:
346     return cast<StoreInst>(this)->isVolatile();
347   }
348 }
349
350 /// mayWriteToMemory - Return true if this instruction may modify memory.
351 ///
352 bool Instruction::mayWriteToMemory() const {
353   switch (getOpcode()) {
354   default: return false;
355   case Instruction::Store:
356   case Instruction::VAArg:
357     return true;
358   case Instruction::Call:
359     if (isFreeCall(this))
360       return true;
361     return !cast<CallInst>(this)->onlyReadsMemory();
362   case Instruction::Invoke:
363     return !cast<InvokeInst>(this)->onlyReadsMemory();
364   case Instruction::Load:
365     return cast<LoadInst>(this)->isVolatile();
366   }
367 }
368
369 /// mayThrow - Return true if this instruction may throw an exception.
370 ///
371 bool Instruction::mayThrow() const {
372   if (const CallInst *CI = dyn_cast<CallInst>(this))
373     return !CI->doesNotThrow();
374   return false;
375 }
376
377 /// isAssociative - Return true if the instruction is associative:
378 ///
379 ///   Associative operators satisfy:  x op (y op z) === (x op y) op z
380 ///
381 /// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
382 ///
383 bool Instruction::isAssociative(unsigned Opcode, const Type *Ty) {
384   return Opcode == And || Opcode == Or || Opcode == Xor ||
385          Opcode == Add || Opcode == Mul;
386 }
387
388 /// isCommutative - Return true if the instruction is commutative:
389 ///
390 ///   Commutative operators satisfy: (x op y) === (y op x)
391 ///
392 /// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
393 /// applied to any type.
394 ///
395 bool Instruction::isCommutative(unsigned op) {
396   switch (op) {
397   case Add:
398   case FAdd:
399   case Mul:
400   case FMul:
401   case And:
402   case Or:
403   case Xor:
404     return true;
405   default:
406     return false;
407   }
408 }
409
410 // Code here matches isMalloc from MallocFreeHelper, which is not in VMCore.
411 static bool isMalloc(const Value* I) {
412   const CallInst *CI = dyn_cast<CallInst>(I);
413   if (!CI) {
414     const BitCastInst *BCI = dyn_cast<BitCastInst>(I);
415     if (!BCI) return false;
416
417     CI = dyn_cast<CallInst>(BCI->getOperand(0));
418   }
419
420   if (!CI) return false;
421
422   const Module* M = CI->getParent()->getParent()->getParent();
423   Constant *MallocFunc = M->getFunction("malloc");
424
425   if (CI->getOperand(0) != MallocFunc)
426     return false;
427
428   // Check malloc prototype.
429   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin 
430   // attribute will exist.
431   const FunctionType *FTy = cast<Function>(MallocFunc)->getFunctionType();
432   if (FTy->getNumParams() != 1)
433     return false;
434   if (IntegerType *ITy = dyn_cast<IntegerType>(FTy->param_begin()->get())) {
435     if (ITy->getBitWidth() != 32 && ITy->getBitWidth() != 64)
436       return false;
437     return true;
438   }
439
440   return false;
441 }
442
443 bool Instruction::isSafeToSpeculativelyExecute() const {
444   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
445     if (Constant *C = dyn_cast<Constant>(getOperand(i)))
446       if (C->canTrap())
447         return false;
448
449   switch (getOpcode()) {
450   default:
451     return true;
452   case UDiv:
453   case URem: {
454     // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
455     ConstantInt *Op = dyn_cast<ConstantInt>(getOperand(1));
456     return Op && !Op->isNullValue();
457   }
458   case SDiv:
459   case SRem: {
460     // x / y is undefined if y == 0, and might be undefined if y == -1,
461     // but calcuations like x / 3 are safe.
462     ConstantInt *Op = dyn_cast<ConstantInt>(getOperand(1));
463     return Op && !Op->isNullValue() && !Op->isAllOnesValue();
464   }
465   case Load: {
466     if (cast<LoadInst>(this)->isVolatile())
467       return false;
468     if (isa<AllocaInst>(getOperand(0)) || isMalloc(getOperand(0)))
469       return true;
470     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(getOperand(0)))
471       return !GV->hasExternalWeakLinkage();
472     // FIXME: Handle cases involving GEPs.  We have to be careful because
473     // a load of a out-of-bounds GEP has undefined behavior.
474     return false;
475   }
476   case Call:
477     return false; // The called function could have undefined behavior or
478                   // side-effects.
479                   // FIXME: We should special-case some intrinsics (bswap,
480                   // overflow-checking arithmetic, etc.)
481   case VAArg:
482   case Alloca:
483   case Invoke:
484   case PHI:
485   case Store:
486   case Ret:
487   case Br:
488   case Switch:
489   case Unwind:
490   case Unreachable:
491     return false; // Misc instructions which have effects
492   }
493 }