llvm.org GIT mirror llvm / 046e78c
Remove FreeInst. Remove LowerAllocations pass. Update some more passes to treate free calls just like they were treating FreeInst. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@85176 91177308-0d34-0410-b5e6-96231b3b80d8 Victor Hernandez 10 years ago
40 changed file(s) with 134 addition(s) and 404 deletion(s). Raw diff Collapse all Expand all
116116 //brainf.end:
117117 endbb = BasicBlock::Create(C, label, brainf_func);
118118
119 //free i8 *%arr
120 new FreeInst(ptr_arr, endbb);
119 //call free(i8 *%arr)
120 endbb->getInstList().push_back(CallInst::CreateFree(ptr_arr, endbb));
121121
122122 //ret void
123123 ReturnInst::Create(C, endbb);
2828 class AliasAnalysis;
2929 class LoadInst;
3030 class StoreInst;
31 class FreeInst;
3231 class VAArgInst;
3332 class AliasSetTracker;
3433 class AliasSet;
297296 bool add(Value *Ptr, unsigned Size); // Add a location
298297 bool add(LoadInst *LI);
299298 bool add(StoreInst *SI);
300 bool add(FreeInst *FI);
301299 bool add(VAArgInst *VAAI);
302300 bool add(CallSite CS); // Call/Invoke instructions
303301 bool add(CallInst *CI) { return add(CallSite(CI)); }
312310 bool remove(Value *Ptr, unsigned Size); // Remove a location
313311 bool remove(LoadInst *LI);
314312 bool remove(StoreInst *SI);
315 bool remove(FreeInst *FI);
316313 bool remove(VAArgInst *VAAI);
317314 bool remove(CallSite CS);
318315 bool remove(CallInst *CI) { return remove(CallSite(CI)); }
None //===- llvm/Analysis/MallocHelper.h ---- Identify malloc calls --*- C++ -*-===//
0 //===- llvm/Analysis/MallocFreeHelper.h - Identify malloc/free --*- C++ -*-===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This family of functions identifies calls to malloc, bitcasts of malloc
10 // calls, and the types and array sizes associated with them.
10 // calls, and the types and array sizes associated with them. It also
11 // identifies calls to the free builtin.
1112 //
1213 //===----------------------------------------------------------------------===//
1314
116116 static inline bool classof(const UnaryInstruction *) { return true; }
117117 static inline bool classof(const Instruction *I) {
118118 return I->getOpcode() == Instruction::Alloca ||
119 I->getOpcode() == Instruction::Free ||
120119 I->getOpcode() == Instruction::Load ||
121120 I->getOpcode() == Instruction::VAArg ||
122121 I->getOpcode() == Instruction::ExtractValue ||
127127
128128 // Memory operators...
129129 FIRST_MEMORY_INST(25)
130 HANDLE_MEMORY_INST(25, Free , FreeInst ) // Heap management instructions
131 HANDLE_MEMORY_INST(26, Alloca, AllocaInst) // Stack management
132 HANDLE_MEMORY_INST(27, Load , LoadInst ) // Memory manipulation instrs
133 HANDLE_MEMORY_INST(28, Store , StoreInst )
134 HANDLE_MEMORY_INST(29, GetElementPtr, GetElementPtrInst)
135 LAST_MEMORY_INST(29)
130 HANDLE_MEMORY_INST(25, Alloca, AllocaInst) // Stack management
131 HANDLE_MEMORY_INST(26, Load , LoadInst ) // Memory manipulation instrs
132 HANDLE_MEMORY_INST(27, Store , StoreInst )
133 HANDLE_MEMORY_INST(28, GetElementPtr, GetElementPtrInst)
134 LAST_MEMORY_INST(28)
136135
137136 // Cast operators ...
138137 // NOTE: The order matters here because CastInst::isEliminableCastPair
139138 // NOTE: (see Instructions.cpp) encodes a table based on this ordering.
140 FIRST_CAST_INST(30)
141 HANDLE_CAST_INST(30, Trunc , TruncInst ) // Truncate integers
142 HANDLE_CAST_INST(31, ZExt , ZExtInst ) // Zero extend integers
143 HANDLE_CAST_INST(32, SExt , SExtInst ) // Sign extend integers
144 HANDLE_CAST_INST(33, FPToUI , FPToUIInst ) // floating point -> UInt
145 HANDLE_CAST_INST(34, FPToSI , FPToSIInst ) // floating point -> SInt
146 HANDLE_CAST_INST(35, UIToFP , UIToFPInst ) // UInt -> floating point
147 HANDLE_CAST_INST(36, SIToFP , SIToFPInst ) // SInt -> floating point
148 HANDLE_CAST_INST(37, FPTrunc , FPTruncInst ) // Truncate floating point
149 HANDLE_CAST_INST(38, FPExt , FPExtInst ) // Extend floating point
150 HANDLE_CAST_INST(39, PtrToInt, PtrToIntInst) // Pointer -> Integer
151 HANDLE_CAST_INST(40, IntToPtr, IntToPtrInst) // Integer -> Pointer
152 HANDLE_CAST_INST(41, BitCast , BitCastInst ) // Type cast
153 LAST_CAST_INST(41)
139 FIRST_CAST_INST(29)
140 HANDLE_CAST_INST(29, Trunc , TruncInst ) // Truncate integers
141 HANDLE_CAST_INST(30, ZExt , ZExtInst ) // Zero extend integers
142 HANDLE_CAST_INST(31, SExt , SExtInst ) // Sign extend integers
143 HANDLE_CAST_INST(32, FPToUI , FPToUIInst ) // floating point -> UInt
144 HANDLE_CAST_INST(33, FPToSI , FPToSIInst ) // floating point -> SInt
145 HANDLE_CAST_INST(34, UIToFP , UIToFPInst ) // UInt -> floating point
146 HANDLE_CAST_INST(35, SIToFP , SIToFPInst ) // SInt -> floating point
147 HANDLE_CAST_INST(36, FPTrunc , FPTruncInst ) // Truncate floating point
148 HANDLE_CAST_INST(37, FPExt , FPExtInst ) // Extend floating point
149 HANDLE_CAST_INST(38, PtrToInt, PtrToIntInst) // Pointer -> Integer
150 HANDLE_CAST_INST(39, IntToPtr, IntToPtrInst) // Integer -> Pointer
151 HANDLE_CAST_INST(40, BitCast , BitCastInst ) // Type cast
152 LAST_CAST_INST(40)
154153
155154 // Other operators...
156 FIRST_OTHER_INST(42)
157 HANDLE_OTHER_INST(42, ICmp , ICmpInst ) // Integer comparison instruction
158 HANDLE_OTHER_INST(43, FCmp , FCmpInst ) // Floating point comparison instr.
159 HANDLE_OTHER_INST(44, PHI , PHINode ) // PHI node instruction
160 HANDLE_OTHER_INST(45, Call , CallInst ) // Call a function
161 HANDLE_OTHER_INST(46, Select , SelectInst ) // select instruction
162 HANDLE_OTHER_INST(47, UserOp1, Instruction) // May be used internally in a pass
163 HANDLE_OTHER_INST(48, UserOp2, Instruction) // Internal to passes only
164 HANDLE_OTHER_INST(49, VAArg , VAArgInst ) // vaarg instruction
165 HANDLE_OTHER_INST(50, ExtractElement, ExtractElementInst)// extract from vector
166 HANDLE_OTHER_INST(51, InsertElement, InsertElementInst) // insert into vector
167 HANDLE_OTHER_INST(52, ShuffleVector, ShuffleVectorInst) // shuffle two vectors.
168 HANDLE_OTHER_INST(53, ExtractValue, ExtractValueInst)// extract from aggregate
169 HANDLE_OTHER_INST(54, InsertValue, InsertValueInst) // insert into aggregate
155 FIRST_OTHER_INST(41)
156 HANDLE_OTHER_INST(41, ICmp , ICmpInst ) // Integer comparison instruction
157 HANDLE_OTHER_INST(42, FCmp , FCmpInst ) // Floating point comparison instr.
158 HANDLE_OTHER_INST(43, PHI , PHINode ) // PHI node instruction
159 HANDLE_OTHER_INST(44, Call , CallInst ) // Call a function
160 HANDLE_OTHER_INST(45, Select , SelectInst ) // select instruction
161 HANDLE_OTHER_INST(46, UserOp1, Instruction) // May be used internally in a pass
162 HANDLE_OTHER_INST(47, UserOp2, Instruction) // Internal to passes only
163 HANDLE_OTHER_INST(48, VAArg , VAArgInst ) // vaarg instruction
164 HANDLE_OTHER_INST(49, ExtractElement, ExtractElementInst)// extract from vector
165 HANDLE_OTHER_INST(50, InsertElement, InsertElementInst) // insert into vector
166 HANDLE_OTHER_INST(51, ShuffleVector, ShuffleVectorInst) // shuffle two vectors.
167 HANDLE_OTHER_INST(52, ExtractValue, ExtractValueInst)// extract from aggregate
168 HANDLE_OTHER_INST(53, InsertValue, InsertValueInst) // insert into aggregate
170169
171 LAST_OTHER_INST(54)
170 LAST_OTHER_INST(53)
172171
173172 #undef FIRST_TERM_INST
174173 #undef HANDLE_TERM_INST
9595 static inline bool classof(const AllocaInst *) { return true; }
9696 static inline bool classof(const Instruction *I) {
9797 return (I->getOpcode() == Instruction::Alloca);
98 }
99 static inline bool classof(const Value *V) {
100 return isa(V) && classof(cast(V));
101 }
102 };
103
104
105 //===----------------------------------------------------------------------===//
106 // FreeInst Class
107 //===----------------------------------------------------------------------===//
108
109 /// FreeInst - an instruction to deallocate memory
110 ///
111 class FreeInst : public UnaryInstruction {
112 void AssertOK();
113 public:
114 explicit FreeInst(Value *Ptr, Instruction *InsertBefore = 0);
115 FreeInst(Value *Ptr, BasicBlock *InsertAfter);
116
117 virtual FreeInst *clone() const;
118
119 // Accessor methods for consistency with other memory operations
120 Value *getPointerOperand() { return getOperand(0); }
121 const Value *getPointerOperand() const { return getOperand(0); }
122
123 // Methods for support type inquiry through isa, cast, and dyn_cast:
124 static inline bool classof(const FreeInst *) { return true; }
125 static inline bool classof(const Instruction *I) {
126 return (I->getOpcode() == Instruction::Free);
12798 }
12899 static inline bool classof(const Value *V) {
129100 return isa(V) && classof(cast(V));
9090 (void) llvm::createLoopUnswitchPass();
9191 (void) llvm::createLoopRotatePass();
9292 (void) llvm::createLoopIndexSplitPass();
93 (void) llvm::createLowerAllocationsPass();
9493 (void) llvm::createLowerInvokePass();
9594 (void) llvm::createLowerSetJmpPass();
9695 (void) llvm::createLowerSwitchPass();
432432 const Twine &Name = "") {
433433 return Insert(new AllocaInst(Ty, ArraySize), Name);
434434 }
435 FreeInst *CreateFree(Value *Ptr) {
436 return Insert(new FreeInst(Ptr));
437 }
438435 // Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
439436 // converting the string to 'bool' for the isVolatile parameter.
440437 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
165165 RetTy visitICmpInst(ICmpInst &I) { DELEGATE(CmpInst);}
166166 RetTy visitFCmpInst(FCmpInst &I) { DELEGATE(CmpInst);}
167167 RetTy visitAllocaInst(AllocaInst &I) { DELEGATE(Instruction); }
168 RetTy visitFreeInst(FreeInst &I) { DELEGATE(Instruction); }
169168 RetTy visitLoadInst(LoadInst &I) { DELEGATE(Instruction); }
170169 RetTy visitStoreInst(StoreInst &I) { DELEGATE(Instruction); }
171170 RetTy visitGetElementPtrInst(GetElementPtrInst &I){ DELEGATE(Instruction); }
221221 //
222222 Pass *createLoopSimplifyPass();
223223 extern const PassInfo *const LoopSimplifyID;
224
225 //===----------------------------------------------------------------------===//
226 //
227 // LowerAllocations - Turn free instructions into @free calls.
228 //
229 // AU.addRequiredID(LowerAllocationsID);
230 //
231 Pass *createLowerAllocationsPass();
232 extern const PassInfo *const LowerAllocationsID;
233224
234225 //===----------------------------------------------------------------------===//
235226 //
469469 macro(UIToFPInst) \
470470 macro(ZExtInst) \
471471 macro(ExtractValueInst) \
472 macro(FreeInst) \
473472 macro(LoadInst) \
474473 macro(VAArgInst)
475474
1212
1313 #include "llvm/Analysis/AliasSetTracker.h"
1414 #include "llvm/Analysis/AliasAnalysis.h"
15 #include "llvm/Analysis/MallocHelper.h"
1516 #include "llvm/Instructions.h"
1617 #include "llvm/IntrinsicInst.h"
1718 #include "llvm/Pass.h"
295296 return NewPtr;
296297 }
297298
298 bool AliasSetTracker::add(FreeInst *FI) {
299 bool NewPtr;
300 addPointer(FI->getOperand(0), ~0, AliasSet::Mods, NewPtr);
301 return NewPtr;
302 }
303
304299 bool AliasSetTracker::add(VAArgInst *VAAI) {
305300 bool NewPtr;
306301 addPointer(VAAI->getOperand(0), ~0, AliasSet::ModRef, NewPtr);
309304
310305
311306 bool AliasSetTracker::add(CallSite CS) {
307 Instruction* Inst = CS.getInstruction();
308 if (isFreeCall(Inst)) {
309 bool NewPtr;
310 addPointer(Inst->getOperand(1), ~0, AliasSet::Mods, NewPtr);
311 return NewPtr;
312 }
313
312314 if (isa(CS.getInstruction()))
313315 return true; // Ignore DbgInfo Intrinsics.
314316 if (AA.doesNotAccessMemory(CS))
336338 return add(CI);
337339 else if (InvokeInst *II = dyn_cast(I))
338340 return add(II);
339 else if (FreeInst *FI = dyn_cast(I))
340 return add(FI);
341341 else if (VAArgInst *VAAI = dyn_cast(I))
342342 return add(VAAI);
343343 return true;
426426 return true;
427427 }
428428
429 bool AliasSetTracker::remove(FreeInst *FI) {
430 AliasSet *AS = findAliasSetForPointer(FI->getOperand(0), ~0);
431 if (!AS) return false;
432 remove(*AS);
433 return true;
434 }
435
436429 bool AliasSetTracker::remove(VAArgInst *VAAI) {
437430 AliasSet *AS = findAliasSetForPointer(VAAI->getOperand(0), ~0);
438431 if (!AS) return false;
441434 }
442435
443436 bool AliasSetTracker::remove(CallSite CS) {
437 Instruction* Inst = CS.getInstruction();
438 if (isFreeCall(Inst)) {
439 AliasSet *AS = findAliasSetForPointer(Inst->getOperand(1), ~0);
440 if (!AS) return false;
441 remove(*AS);
442 return true;
443 }
444
444445 if (AA.doesNotAccessMemory(CS))
445446 return false; // doesn't alias anything
446447
458459 return remove(SI);
459460 else if (CallInst *CI = dyn_cast(I))
460461 return remove(CI);
461 else if (FreeInst *FI = dyn_cast(I))
462 return remove(FI);
463462 else if (VAArgInst *VAAI = dyn_cast(I))
464463 return remove(VAAI);
465464 return true;
1616 //===----------------------------------------------------------------------===//
1717
1818 #include "llvm/Analysis/CaptureTracking.h"
19 #include "llvm/Analysis/MallocHelper.h"
1920 #include "llvm/Instructions.h"
2021 #include "llvm/Value.h"
2122 #include "llvm/ADT/SmallSet.h"
4748
4849 switch (I->getOpcode()) {
4950 case Instruction::Call:
51 if (isFreeCall(I))
52 // Freeing a pointer does not cause it to be captured.
53 break;
5054 case Instruction::Invoke: {
5155 CallSite CS = CallSite::get(I);
5256 // Not captured if the callee is readonly, doesn't return a copy through
7276 // captured.
7377 break;
7478 }
75 case Instruction::Free:
76 // Freeing a pointer does not cause it to be captured.
77 break;
7879 case Instruction::Load:
7980 // Loading from a pointer does not cause it to be captured.
8081 break;
10151015 }
10161016 } else if (GetElementPtrInst *GEP = dyn_cast(*UI)) {
10171017 if (AnalyzeUsesOfFunction(GEP)) return true;
1018 } else if (isa(*UI) || isFreeCall(*UI)) {
1018 } else if (isFreeCall(*UI)) {
10191019 return false;
10201020 } else if (CallInst *CI = dyn_cast(*UI)) {
10211021 // Make sure that this is just the function being called, not that it is
11551155 case Instruction::Switch:
11561156 case Instruction::Unwind:
11571157 case Instruction::Unreachable:
1158 case Instruction::Free:
11591158 case Instruction::ICmp:
11601159 case Instruction::FCmp:
11611160 return;
237237 } else if (BitCastInst *BCI = dyn_cast(*UI)) {
238238 if (AnalyzeUsesOfPointer(BCI, Readers, Writers, OkayStoreDest))
239239 return true;
240 } else if (isa(*UI) || isFreeCall(*UI)) {
240 } else if (isFreeCall(*UI)) {
241241 Writers.push_back(cast(*UI)->getParent()->getParent());
242242 } else if (CallInst *CI = dyn_cast(*UI)) {
243243 // Make sure that this is just the function being called, not that it is
436436 if (cast(*II).isVolatile())
437437 // Treat volatile stores as reading memory somewhere.
438438 FunctionEffect |= Ref;
439 } else if (isMalloc(&cast(*II)) || isa(*II) ||
439 } else if (isMalloc(&cast(*II)) ||
440440 isFreeCall(&cast(*II))) {
441441 FunctionEffect |= ModRef;
442442 }
129129 NumInsts += InlineConstants::CallPenalty;
130130 }
131131
132 // These, too, are calls.
133 if (isa(II))
134 NumInsts += InlineConstants::CallPenalty;
135
136132 if (const AllocaInst *AI = dyn_cast(II)) {
137133 if (!AI->isStaticAlloca())
138134 this->usesDynamicAlloca = true;
7373 bool InstCount::runOnFunction(Function &F) {
7474 unsigned StartMemInsts =
7575 NumGetElementPtrInst + NumLoadInst + NumStoreInst + NumCallInst +
76 NumInvokeInst + NumAllocaInst + NumFreeInst;
76 NumInvokeInst + NumAllocaInst;
7777 visit(F);
7878 unsigned EndMemInsts =
7979 NumGetElementPtrInst + NumLoadInst + NumStoreInst + NumCallInst +
80 NumInvokeInst + NumAllocaInst + NumFreeInst;
80 NumInvokeInst + NumAllocaInst;
8181 TotalMemInst += EndMemInsts-StartMemInsts;
8282 return false;
8383 }
None //===-- MallocHelper.cpp - Functions to identify malloc calls -------------===//
0 //===-- MallocFreeHelper.cpp - Identify calls to malloc and free builtins -===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This family of functions identifies calls to malloc, bitcasts of malloc
10 // calls, and the types and array sizes associated with them.
10 // calls, and the types and array sizes associated with them. It also
11 // identifies calls to the free builtin.
1112 //
1213 //===----------------------------------------------------------------------===//
1314
263264 return BO->getOperand(0);
264265 }
265266
267 //===----------------------------------------------------------------------===//
268 // free Call Utility Functions.
269 //
270
266271 /// isFreeCall - Returns true if the the value is a call to the builtin free()
267272 bool llvm::isFreeCall(const Value* I) {
268273 const CallInst *CI = dyn_cast(I);
112112 } else if (VAArgInst *V = dyn_cast(Inst)) {
113113 Pointer = V->getOperand(0);
114114 PointerSize = AA->getTypeStoreSize(V->getType());
115 } else if (FreeInst *F = dyn_cast(Inst)) {
116 Pointer = F->getPointerOperand();
117
118 // FreeInsts erase the entire structure
115 } else if (isFreeCall(Inst)) {
116 Pointer = Inst->getOperand(1);
117 // calls to free() erase the entire structure
119118 PointerSize = ~0ULL;
120119 } else if (isFreeCall(Inst)) {
121120 Pointer = Inst->getOperand(0);
318317 MemSize = AA->getTypeStoreSize(LI->getType());
319318 }
320319 } else if (isFreeCall(QueryInst)) {
321 MemPtr = QueryInst->getOperand(0);
320 MemPtr = QueryInst->getOperand(1);
322321 // calls to free() erase the entire structure, not just a field.
323322 MemSize = ~0UL;
324323 } else if (isa(QueryInst) || isa(QueryInst)) {
326325 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
327326 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
328327 QueryParent);
329 } else if (FreeInst *FI = dyn_cast(QueryInst)) {
330 MemPtr = FI->getPointerOperand();
331 // FreeInsts erase the entire structure, not just a field.
332 MemSize = ~0UL;
333328 } else {
334329 // Non-memory instruction.
335330 LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
605605 // FIXME: Remove in LLVM 3.0.
606606 // Autoupgrade malloc instruction.
607607 return lltok::kw_malloc;
608 } else if (Len == 4 && !memcmp(StartChar, "free", 4)) {
609 // FIXME: Remove in LLVM 3.0.
610 // Autoupgrade malloc instruction.
611 return lltok::kw_free;
608612 }
609613
610614 // Keywords for instructions.
645649 INSTKEYWORD(unreachable, Unreachable);
646650
647651 INSTKEYWORD(alloca, Alloca);
648 INSTKEYWORD(free, Free);
649652 INSTKEYWORD(load, Load);
650653 INSTKEYWORD(store, Store);
651654 INSTKEYWORD(getelementptr, GetElementPtr);
10531053 Vals.push_back(VE.getValueID(I.getOperand(i)));
10541054 break;
10551055
1056 case Instruction::Free:
1057 Code = bitc::FUNC_CODE_INST_FREE;
1058 PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1059 break;
1060
10611056 case Instruction::Alloca:
10621057 Code = bitc::FUNC_CODE_INST_ALLOCA;
10631058 Vals.push_back(VE.getTypeID(I.getType()));
54855485 DAG.setRoot(Chain);
54865486 }
54875487
5488 void SelectionDAGLowering::visitFree(FreeInst &I) {
5489 TargetLowering::ArgListTy Args;
5490 TargetLowering::ArgListEntry Entry;
5491 Entry.Node = getValue(I.getOperand(0));
5492 Entry.Ty = TLI.getTargetData()->getIntPtrType(*DAG.getContext());
5493 Args.push_back(Entry);
5494 EVT IntPtr = TLI.getPointerTy();
5495 bool isTailCall = PerformTailCallOpt &&
5496 isInTailCallPosition(&I, Attribute::None, TLI);
5497 std::pair Result =
5498 TLI.LowerCallTo(getRoot(), Type::getVoidTy(*DAG.getContext()),
5499 false, false, false, false,
5500 0, CallingConv::C, isTailCall,
5501 /*isReturnValueUsed=*/true,
5502 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
5503 getCurDebugLoc());
5504 if (Result.second.getNode())
5505 DAG.setRoot(Result.second);
5506 }
5507
55085488 void SelectionDAGLowering::visitVAStart(CallInst &I) {
55095489 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
55105490 MVT::Other, getRoot(),
4343 class FPToSIInst;
4444 class FPToUIInst;
4545 class FPTruncInst;
46 class FreeInst;
4746 class Function;
4847 class GetElementPtrInst;
4948 class GCFunctionInfo;
527526 void visitGetElementPtr(User &I);
528527 void visitSelect(User &I);
529528
530 void visitFree(FreeInst &I);
531529 void visitAlloca(AllocaInst &I);
532530 void visitLoad(LoadInst &I);
533531 void visitStore(StoreInst &I);
746746
747747 if (I.getOpcode() == Instruction::Alloca)
748748 ECStack.back().Allocas.add(Memory);
749 }
750
751 void Interpreter::visitFreeInst(FreeInst &I) {
752 ExecutionContext &SF = ECStack.back();
753 assert(isa(I.getOperand(0)->getType()) && "Freeing nonptr?");
754 GenericValue Value = getOperandValue(I.getOperand(0), SF);
755 // TODO: Check to make sure memory is allocated
756 free(GVTOP(Value)); // Free memory
757749 }
758750
759751 // getElementOffset - The workhorse for getelementptr.
139139 void visitICmpInst(ICmpInst &I);
140140 void visitFCmpInst(FCmpInst &I);
141141 void visitAllocaInst(AllocaInst &I);
142 void visitFreeInst(FreeInst &I);
143142 void visitLoadInst(LoadInst &I);
144143 void visitStoreInst(StoreInst &I);
145144 void visitGetElementPtrInst(GetElementPtrInst &I);
302302 bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
303303
304304 void visitAllocaInst(AllocaInst &I);
305 void visitFreeInst (FreeInst &I);
306305 void visitLoadInst (LoadInst &I);
307306 void visitStoreInst (StoreInst &I);
308307 void visitGetElementPtrInst(GetElementPtrInst &I);
34163415 Out << ')';
34173416 }
34183417
3419 void CWriter::visitFreeInst(FreeInst &I) {
3420 llvm_unreachable("lowerallocations pass didn't work!");
3421 }
3422
34233418 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
34243419 gep_type_iterator E, bool Static) {
34253420
36843679 if (FileType != TargetMachine::AssemblyFile) return true;
36853680
36863681 PM.add(createGCLoweringPass());
3687 PM.add(createLowerAllocationsPass());
36883682 PM.add(createLowerInvokePass());
36893683 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
36903684 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
12571257 Out << "\");";
12581258 break;
12591259 }
1260 case Instruction::Free: {
1261 Out << "FreeInst* " << iName << " = new FreeInst("
1262 << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1263 break;
1264 }
12651260 case Instruction::Alloca: {
12661261 const AllocaInst* allocaI = cast(I);
12671262 Out << "AllocaInst* " << iName << " = new AllocaInst("
11901190 case Instruction::Alloca:
11911191 printAllocaInstruction(cast(Inst));
11921192 break;
1193 case Instruction::Free:
1194 llvm_unreachable("LowerAllocationsPass used");
1195 break;
11961193 case Instruction::Unreachable:
11971194 printSimpleInstruction("ldstr", "\"Unreachable instruction\"");
11981195 printSimpleInstruction("newobj",
16981695 if (FileType != TargetMachine::AssemblyFile) return true;
16991696 MSILWriter* Writer = new MSILWriter(o);
17001697 PM.add(createGCLoweringPass());
1701 PM.add(createLowerAllocationsPass());
17021698 // FIXME: Handle switch trougth native IL instruction "switch"
17031699 PM.add(createLowerSwitchPass());
17041700 PM.add(createCFGSimplificationPass());
8888 Instruction *Inst = BBI++;
8989
9090 // If we find a store or a free, get its memory dependence.
91 if (!isa(Inst) && !isa(Inst) && !isFreeCall(Inst))
91 if (!isa(Inst) && !isFreeCall(Inst))
9292 continue;
9393
9494 // Don't molest volatile stores or do queries that will return "clobber".
103103 if (InstDep.isNonLocal()) continue;
104104
105105 // Handle frees whose dependencies are non-trivial.
106 if (isa(Inst) || isFreeCall(Inst)) {
106 if (isFreeCall(Inst)) {
107107 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
108108 continue;
109109 }
175175 Value *DepPointer = Dependency->getPointerOperand()->getUnderlyingObject();
176176
177177 // Check for aliasing.
178 Value* FreeVal = isa(F) ? F->getOperand(0) : F->getOperand(1);
179 if (AA.alias(FreeVal, 1, DepPointer, 1) !=
178 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
180179 AliasAnalysis::MustAlias)
181180 return false;
182181
284284 Instruction *visitPHINode(PHINode &PN);
285285 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
286286 Instruction *visitAllocaInst(AllocaInst &AI);
287 Instruction *visitFreeInst(FreeInst &FI);
288287 Instruction *visitFree(Instruction &FI);
289288 Instruction *visitLoadInst(LoadInst &LI);
290289 Instruction *visitStoreInst(StoreInst &SI);
1132711326 return 0;
1132811327 }
1132911328
11330 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11331 Value *Op = FI.getOperand(0);
11329 Instruction *InstCombiner::visitFree(Instruction &FI) {
11330 Value *Op = FI.getOperand(1);
1133211331
1133311332 // free undef -> unreachable.
1133411333 if (isa(Op)) {
1134211341 // when lots of inlining happens.
1134311342 if (isa(Op))
1134411343 return EraseInstFromFunction(FI);
11345
11346 // Change free * (cast * X to *) into free * X
11347 if (BitCastInst *CI = dyn_cast(Op)) {
11348 FI.setOperand(0, CI->getOperand(0));
11349 return &FI;
11350 }
11351
11352 // Change free (gep X, 0,0,0,0) into free(X)
11353 if (GetElementPtrInst *GEPI = dyn_cast(Op)) {
11354 if (GEPI->hasAllZeroIndices()) {
11355 Worklist.Add(GEPI);
11356 FI.setOperand(0, GEPI->getOperand(0));
11357 return &FI;
11358 }
11359 }
11360
11361 if (isMalloc(Op)) {
11344
11345 // If we have a malloc call whose only use is a free call, delete both.
11346 if (isMalloc(Op))
1136211347 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
1136311348 if (Op->hasOneUse() && CI->hasOneUse()) {
1136411349 EraseInstFromFunction(FI);
1137211357 return EraseInstFromFunction(*cast(Op));
1137311358 }
1137411359 }
11375 }
11376
11377 return 0;
11378 }
11379
11380 Instruction *InstCombiner::visitFree(Instruction &FI) {
11381 Value *Op = FI.getOperand(1);
11382
11383 // free undef -> unreachable.
11384 if (isa(Op)) {
11385 // Insert a new store to null because we cannot modify the CFG here.
11386 new StoreInst(ConstantInt::getTrue(*Context),
11387 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11388 return EraseInstFromFunction(FI);
11389 }
11390
11391 // If we have 'free null' delete the instruction. This can happen in stl code
11392 // when lots of inlining happens.
11393 if (isa(Op))
11394 return EraseInstFromFunction(FI);
11395
11396 // FIXME: Bring back free (gep X, 0,0,0,0) into free(X) transform
11397
11398 if (isMalloc(Op)) {
11399 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11400 if (Op->hasOneUse() && CI->hasOneUse()) {
11401 EraseInstFromFunction(FI);
11402 EraseInstFromFunction(*CI);
11403 return EraseInstFromFunction(*cast(Op));
11404 }
11405 } else {
11406 // Op is a call to malloc
11407 if (Op->hasOneUse()) {
11408 EraseInstFromFunction(FI);
11409 return EraseInstFromFunction(*cast(Op));
11410 }
11411 }
11412 }
1141311360
1141411361 return 0;
1141511362 }
415415 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
416416 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
417417 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
418 void visitFreeInst (Instruction &I) { /*returns void*/ }
419418
420419 void visitInstruction(Instruction &I) {
421420 // If a new instruction is added to LLVM that we don't handle...
1212 LCSSA.cpp
1313 Local.cpp
1414 LoopSimplify.cpp
15 LowerAllocations.cpp
1615 LowerInvoke.cpp
1716 LowerSwitch.cpp
1817 Mem2Reg.cpp
5959
6060 // If we see a free or a call which may write to memory (i.e. which might do
6161 // a free) the pointer could be marked invalid.
62 if (isa(BBI) || isFreeCall(BBI) ||
63 (isa(BBI) && BBI->mayWriteToMemory() &&
64 !isa(BBI)))
62 if (isFreeCall(BBI) || (isa(BBI) && BBI->mayWriteToMemory() &&
63 !isa(BBI)))
6564 return false;
6665
6766 if (LoadInst *LI = dyn_cast(BBI)) {
+0
-116
lib/Transforms/Utils/LowerAllocations.cpp less more
None //===- LowerAllocations.cpp - Reduce free insts to calls ------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The LowerAllocations transformation is a target-dependent tranformation
10 // because it depends on the size of data types and alignment constraints.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "lowerallocs"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
17 #include "llvm/Module.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Constants.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Pass.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Target/TargetData.h"
25 using namespace llvm;
26
27 STATISTIC(NumLowered, "Number of allocations lowered");
28
29 namespace {
30 /// LowerAllocations - Turn free instructions into @free calls.
31 ///
32 class LowerAllocations : public BasicBlockPass {
33 Constant *FreeFunc; // Functions in the module we are processing
34 // Initialized by doInitialization
35 public:
36 static char ID; // Pass ID, replacement for typeid
37 explicit LowerAllocations()
38 : BasicBlockPass(&ID), FreeFunc(0) {}
39
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired();
42 AU.setPreservesCFG();
43
44 // This is a cluster of orthogonal Transforms:
45 AU.addPreserved();
46 AU.addPreservedID(PromoteMemoryToRegisterID);
47 AU.addPreservedID(LowerSwitchID);
48 AU.addPreservedID(LowerInvokePassID);
49 }
50
51 /// doPassInitialization - For the lower allocations pass, this ensures that
52 /// a module contains a declaration for a free function.
53 ///
54 bool doInitialization(Module &M);
55
56 virtual bool doInitialization(Function &F) {
57 return doInitialization(*F.getParent());
58 }
59
60 /// runOnBasicBlock - This method does the actual work of converting
61 /// instructions over, assuming that the pass has already been initialized.
62 ///
63 bool runOnBasicBlock(BasicBlock &BB);
64 };
65 }
66
67 char LowerAllocations::ID = 0;
68 static RegisterPass
69 X("lowerallocs", "Lower allocations from instructions to calls");
70
71 // Publically exposed interface to pass...
72 const PassInfo *const llvm::LowerAllocationsID = &X;
73 // createLowerAllocationsPass - Interface to this file...
74 Pass *llvm::createLowerAllocationsPass() {
75 return new LowerAllocations();
76 }
77
78
79 // doInitialization - For the lower allocations pass, this ensures that a
80 // module contains a declaration for a free function.
81 //
82 // This function is always successful.
83 //
84 bool LowerAllocations::doInitialization(Module &M) {
85 const Type *BPTy = Type::getInt8PtrTy(M.getContext());
86 FreeFunc = M.getOrInsertFunction("free" , Type::getVoidTy(M.getContext()),
87 BPTy, (Type *)0);
88 return true;
89 }
90
91 // runOnBasicBlock - This method does the actual work of converting
92 // instructions over, assuming that the pass has already been initialized.
93 //
94 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
95 bool Changed = false;
96 assert(FreeFunc && "Pass not initialized!");
97
98 BasicBlock::InstListType &BBIL = BB.getInstList();
99
100 // Loop over all of the instructions, looking for free instructions
101 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
102 if (FreeInst *FI = dyn_cast(I)) {
103 // Insert a call to the free function...
104 CallInst::CreateFree(FI->getOperand(0), I);
105
106 // Delete the old free instruction
107 I = --BBIL.erase(I);
108 Changed = true;
109 ++NumLowered;
110 }
111 }
112
113 return Changed;
114 }
115
8585 // This is a cluster of orthogonal Transforms
8686 AU.addPreservedID(PromoteMemoryToRegisterID);
8787 AU.addPreservedID(LowerSwitchID);
88 AU.addPreservedID(LowerAllocationsID);
8988 }
9089
9190 private:
4242 AU.addPreserved();
4343 AU.addPreservedID(PromoteMemoryToRegisterID);
4444 AU.addPreservedID(LowerInvokePassID);
45 AU.addPreservedID(LowerAllocationsID);
4645 }
4746
4847 struct CaseRange {
4343 AU.addPreserved();
4444 AU.addPreservedID(LowerSwitchID);
4545 AU.addPreservedID(LowerInvokePassID);
46 AU.addPreservedID(LowerAllocationsID);
4746 }
4847 };
4948 } // end of anonymous namespace
17231723 }
17241724
17251725 LLVMValueRef LLVMBuildFree(LLVMBuilderRef B, LLVMValueRef PointerVal) {
1726 return wrap(unwrap(B)->CreateFree(unwrap(PointerVal)));
1726 return wrap(unwrap(B)->Insert(
1727 CallInst::CreateFree(unwrap(PointerVal), unwrap(B)->GetInsertBlock())));
17271728 }
17281729
17291730
126126 case Xor: return "xor";
127127
128128 // Memory instructions...
129 case Free: return "free";
130129 case Alloca: return "alloca";
131130 case Load: return "load";
132131 case Store: return "store";
302301 return false;
303302 }
304303
304 // Code here matches isFreeCall from MallocHelper, which is not in VMCore.
305 static bool isFreeCall(const Value* I) {
306 const CallInst *CI = dyn_cast(I);
307 if (!CI)
308 return false;
309
310 const Module* M = CI->getParent()->getParent()->getParent();
311 Function *FreeFunc = M->getFunction("free");
312
313 if (CI->getOperand(0) != FreeFunc)
314 return false;
315
316 // Check free prototype.
317 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
318 // attribute will exist.
319 const FunctionType *FTy = FreeFunc->getFunctionType();
320 if (FTy->getReturnType() != Type::getVoidTy(M->getContext()))
321 return false;
322 if (FTy->getNumParams() != 1)
323 return false;
324 if (FTy->param_begin()->get() != Type::getInt8PtrTy(M->getContext()))
325 return false;
326
327 return true;
328 }
329
305330 /// mayReadFromMemory - Return true if this instruction may read memory.
306331 ///
307332 bool Instruction::mayReadFromMemory() const {
308333 switch (getOpcode()) {
309334 default: return false;
310 case Instruction::Free:
311335 case Instruction::VAArg:
312336 case Instruction::Load:
313337 return true;
314338 case Instruction::Call:
339 if (isFreeCall(this))
340 return true;
315341 return !cast(this)->doesNotAccessMemory();
316342 case Instruction::Invoke:
317343 return !cast(this)->doesNotAccessMemory();
325351 bool Instruction::mayWriteToMemory() const {
326352 switch (getOpcode()) {
327353 default: return false;
328 case Instruction::Free:
329354 case Instruction::Store:
330355 case Instruction::VAArg:
331356 return true;
332357 case Instruction::Call:
358 if (isFreeCall(this))
359 return true;
333360 return !cast(this)->onlyReadsMemory();
334361 case Instruction::Invoke:
335362 return !cast(this)->onlyReadsMemory();
397424 if (CI->getOperand(0) != MallocFunc)
398425 return false;
399426
400 return true;
427 // Check malloc prototype.
428 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
429 // attribute will exist.
430 const FunctionType *FTy = cast(MallocFunc)->getFunctionType();
431 if (FTy->getNumParams() != 1)
432 return false;
433 if (IntegerType *ITy = dyn_cast(FTy->param_begin()->get())) {
434 if (ITy->getBitWidth() != 32 && ITy->getBitWidth() != 64)
435 return false;
436 return true;
437 }
438
439 return false;
401440 }
402441
403442 bool Instruction::isSafeToSpeculativelyExecute() const {
443482 case Invoke:
444483 case PHI:
445484 case Store:
446 case Free:
447485 case Ret:
448486 case Br:
449487 case Switch:
982982 const BasicBlock *Parent = getParent();
983983 return Parent == &Parent->getParent()->front();
984984 }
985
986 //===----------------------------------------------------------------------===//
987 // FreeInst Implementation
988 //===----------------------------------------------------------------------===//
989
990 void FreeInst::AssertOK() {
991 assert(isa(getOperand(0)->getType()) &&
992 "Can not free something of nonpointer type!");
993 }
994
995 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
996 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
997 Free, Ptr, InsertBefore) {
998 AssertOK();
999 }
1000
1001 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
1002 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
1003 Free, Ptr, InsertAtEnd) {
1004 AssertOK();
1005 }
1006
1007985
1008986 //===----------------------------------------------------------------------===//
1009987 // LoadInst Implementation
31803158 return New;
31813159 }
31823160
3183 FreeInst *FreeInst::clone() const {
3184 FreeInst *New = new FreeInst(getOperand(0));
3185 New->SubclassOptionalData = SubclassOptionalData;
3186 if (hasMetadata()) {
3187 LLVMContext &Context = getContext();
3188 Context.pImpl->TheMetadata.ValueIsCloned(this, New);
3189 }
3190 return New;
3191 }
3192
31933161 LoadInst *LoadInst::clone() const {
31943162 LoadInst *New = new LoadInst(getOperand(0),
31953163 Twine(), isVolatile(),