1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/MachineModuleInfo.h"
12 #include "llvm/Constants.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/GlobalVariable.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Module.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/ErrorHandling.h"
29 using namespace llvm::dwarf;
31 // Handle the Pass registration stuff necessary to use TargetData's.
32 static RegisterPass<MachineModuleInfo>
33 X("machinemoduleinfo", "Machine Module Information");
34 char MachineModuleInfo::ID = 0;
36 // Out of line virtual method.
37 MachineModuleInfoImpl::~MachineModuleInfoImpl() {}
40 class MMIAddrLabelMapCallbackPtr : CallbackVH {
43 MMIAddrLabelMapCallbackPtr() : Map(0) {}
44 MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(0) {}
46 void setMap(MMIAddrLabelMap *map) { Map = map; }
48 virtual void deleted();
49 virtual void allUsesReplacedWith(Value *V2);
52 class MMIAddrLabelMap {
54 struct AddrLabelSymEntry {
55 MCSymbol *Sym; // The symbol for the label.
56 Function *Fn; // The containing function of the BasicBlock.
57 unsigned Index; // The index in BBCallbacks for the BasicBlock.
60 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
62 /// BBCallbacks - Callbacks for the BasicBlock's that we have entries for. We
63 /// use this so we get notified if a block is deleted or RAUWd.
64 std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
66 /// DeletedAddrLabelsNeedingEmission - This is a per-function list of symbols
67 /// whose corresponding BasicBlock got deleted. These symbols need to be
68 /// emitted at some point in the file, so AsmPrinter emits them after the
70 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
71 DeletedAddrLabelsNeedingEmission;
74 MMIAddrLabelMap(MCContext &context) : Context(context) {}
76 assert(DeletedAddrLabelsNeedingEmission.empty() &&
77 "Some labels for deleted blocks never got emitted");
80 MCSymbol *getAddrLabelSymbol(BasicBlock *BB);
81 void takeDeletedSymbolsForFunction(Function *F,
82 std::vector<MCSymbol*> &Result);
84 void UpdateForDeletedBlock(BasicBlock *BB);
85 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
89 MCSymbol *MMIAddrLabelMap::getAddrLabelSymbol(BasicBlock *BB) {
90 assert(BB->hasAddressTaken() &&
91 "Shouldn't get label for block without address taken");
92 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
94 // If we already had an entry for this block, just return it.
96 assert(BB->getParent() == Entry.Fn && "Parent changed");
100 // Otherwise, this is a new entry, create a new symbol for it and add an
101 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
102 BBCallbacks.push_back(BB);
103 BBCallbacks.back().setMap(this);
104 Entry.Index = BBCallbacks.size()-1;
105 Entry.Fn = BB->getParent();
106 return Entry.Sym = Context.CreateTempSymbol();
109 /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return
111 void MMIAddrLabelMap::
112 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
113 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
114 DeletedAddrLabelsNeedingEmission.find(F);
116 // If there are no entries for the function, just return.
117 if (I == DeletedAddrLabelsNeedingEmission.end()) return;
119 // Otherwise, take the list.
120 std::swap(Result, I->second);
121 DeletedAddrLabelsNeedingEmission.erase(I);
125 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
126 // If the block got deleted, there is no need for the symbol. If the symbol
127 // was already emitted, we can just forget about it, otherwise we need to
128 // queue it up for later emission when the function is output.
129 AddrLabelSymEntry Entry = AddrLabelSymbols[BB];
130 AddrLabelSymbols.erase(BB);
131 assert(Entry.Sym && "Didn't have a symbol, why a callback?");
132 BBCallbacks[Entry.Index] = 0; // Clear the callback.
134 if (Entry.Sym->isDefined())
137 // If the block is not yet defined, we need to emit it at the end of the
138 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list for
139 // the containing Function. Since the block is being deleted, its parent may
140 // already be removed, we have to get the function from 'Entry'.
141 assert((BB->getParent() == 0 || BB->getParent() == Entry.Fn) &&
142 "Block/parent mismatch");
144 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Entry.Sym);
147 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
148 // Get the entry for the RAUW'd block and remove it from our map.
149 AddrLabelSymEntry OldEntry = AddrLabelSymbols[Old];
150 AddrLabelSymbols.erase(Old);
151 assert(OldEntry.Sym && "Didn't have a symbol, why a callback?");
153 // If New is not address taken, just move our symbol over to it.
154 if (!AddrLabelSymbols.count(New)) {
155 BBCallbacks[OldEntry.Index] = New; // Update the callback.
156 AddrLabelSymbols[New] = OldEntry; // Set New's entry.
158 assert(0 && "Case not handled yet!");
164 void MMIAddrLabelMapCallbackPtr::deleted() {
165 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
168 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
169 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
173 //===----------------------------------------------------------------------===//
175 MachineModuleInfo::MachineModuleInfo(const MCAsmInfo &MAI)
176 : ImmutablePass(&ID), Context(MAI),
178 CurCallSite(0), CallsEHReturn(0), CallsUnwindInit(0), DbgInfoAvailable(false){
179 // Always emit some info, by default "no personality" info.
180 Personalities.push_back(NULL);
181 AddrLabelSymbols = 0;
184 MachineModuleInfo::MachineModuleInfo()
185 : ImmutablePass(&ID), Context(*(MCAsmInfo*)0) {
186 assert(0 && "This MachineModuleInfo constructor should never be called, MMI "
187 "should always be explicitly constructed by LLVMTargetMachine");
191 MachineModuleInfo::~MachineModuleInfo() {
194 // FIXME: Why isn't doFinalization being called??
195 //assert(AddrLabelSymbols == 0 && "doFinalization not called");
196 delete AddrLabelSymbols;
197 AddrLabelSymbols = 0;
200 /// doInitialization - Initialize the state for a new module.
202 bool MachineModuleInfo::doInitialization() {
203 assert(AddrLabelSymbols == 0 && "Improperly initialized");
207 /// doFinalization - Tear down the state after completion of a module.
209 bool MachineModuleInfo::doFinalization() {
210 delete AddrLabelSymbols;
211 AddrLabelSymbols = 0;
215 /// EndFunction - Discard function meta information.
217 void MachineModuleInfo::EndFunction() {
218 // Clean up frame info.
221 // Clean up exception info.
229 VariableDbgInfo.clear();
232 /// AnalyzeModule - Scan the module for global debug information.
234 void MachineModuleInfo::AnalyzeModule(Module &M) {
235 // Insert functions in the llvm.used array (but not llvm.compiler.used) into
237 GlobalVariable *GV = M.getGlobalVariable("llvm.used");
238 if (!GV || !GV->hasInitializer()) return;
240 // Should be an array of 'i8*'.
241 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
242 if (InitList == 0) return;
244 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
246 dyn_cast<Function>(InitList->getOperand(i)->stripPointerCasts()))
247 UsedFunctions.insert(F);
250 //===- Address of Block Management ----------------------------------------===//
253 /// getAddrLabelSymbol - Return the symbol to be used for the specified basic
254 /// block when its address is taken. This cannot be its normal LBB label
255 /// because the block may be accessed outside its containing function.
256 MCSymbol *MachineModuleInfo::getAddrLabelSymbol(const BasicBlock *BB) {
257 // Lazily create AddrLabelSymbols.
258 if (AddrLabelSymbols == 0)
259 AddrLabelSymbols = new MMIAddrLabelMap(Context);
260 return AddrLabelSymbols->getAddrLabelSymbol(const_cast<BasicBlock*>(BB));
263 /// takeDeletedSymbolsForFunction - If the specified function has had any
264 /// references to address-taken blocks generated, but the block got deleted,
265 /// return the symbol now so we can emit it. This prevents emitting a
266 /// reference to a symbol that has no definition.
267 void MachineModuleInfo::
268 takeDeletedSymbolsForFunction(const Function *F,
269 std::vector<MCSymbol*> &Result) {
270 // If no blocks have had their addresses taken, we're done.
271 if (AddrLabelSymbols == 0) return;
272 return AddrLabelSymbols->
273 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
276 //===- EH -----------------------------------------------------------------===//
278 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
279 /// specified MachineBasicBlock.
280 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
281 (MachineBasicBlock *LandingPad) {
282 unsigned N = LandingPads.size();
283 for (unsigned i = 0; i < N; ++i) {
284 LandingPadInfo &LP = LandingPads[i];
285 if (LP.LandingPadBlock == LandingPad)
289 LandingPads.push_back(LandingPadInfo(LandingPad));
290 return LandingPads[N];
293 /// addInvoke - Provide the begin and end labels of an invoke style call and
294 /// associate it with a try landing pad block.
295 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
296 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
297 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
298 LP.BeginLabels.push_back(BeginLabel);
299 LP.EndLabels.push_back(EndLabel);
302 /// addLandingPad - Provide the label of a try LandingPad block.
304 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
305 MCSymbol *LandingPadLabel = Context.CreateTempSymbol();
306 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
307 LP.LandingPadLabel = LandingPadLabel;
308 return LandingPadLabel;
311 /// addPersonality - Provide the personality function for the exception
313 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
314 Function *Personality) {
315 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
316 LP.Personality = Personality;
318 for (unsigned i = 0; i < Personalities.size(); ++i)
319 if (Personalities[i] == Personality)
322 // If this is the first personality we're adding go
323 // ahead and add it at the beginning.
324 if (Personalities[0] == NULL)
325 Personalities[0] = Personality;
327 Personalities.push_back(Personality);
330 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
332 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
333 std::vector<GlobalVariable *> &TyInfo) {
334 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
335 for (unsigned N = TyInfo.size(); N; --N)
336 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
339 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
341 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
342 std::vector<GlobalVariable *> &TyInfo) {
343 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
344 std::vector<unsigned> IdsInFilter(TyInfo.size());
345 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
346 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
347 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
350 /// addCleanup - Add a cleanup action for a landing pad.
352 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
353 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
354 LP.TypeIds.push_back(0);
357 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
359 void MachineModuleInfo::TidyLandingPads() {
360 for (unsigned i = 0; i != LandingPads.size(); ) {
361 LandingPadInfo &LandingPad = LandingPads[i];
362 if (LandingPad.LandingPadLabel && !LandingPad.LandingPadLabel->isDefined())
363 LandingPad.LandingPadLabel = 0;
365 // Special case: we *should* emit LPs with null LP MBB. This indicates
367 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
368 LandingPads.erase(LandingPads.begin() + i);
372 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
373 MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
374 MCSymbol *EndLabel = LandingPad.EndLabels[j];
375 if (BeginLabel->isDefined() && EndLabel->isDefined()) continue;
377 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
378 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
382 // Remove landing pads with no try-ranges.
383 if (LandingPads[i].BeginLabels.empty()) {
384 LandingPads.erase(LandingPads.begin() + i);
388 // If there is no landing pad, ensure that the list of typeids is empty.
389 // If the only typeid is a cleanup, this is the same as having no typeids.
390 if (!LandingPad.LandingPadBlock ||
391 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
392 LandingPad.TypeIds.clear();
397 /// getTypeIDFor - Return the type id for the specified typeinfo. This is
399 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
400 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
401 if (TypeInfos[i] == TI) return i + 1;
403 TypeInfos.push_back(TI);
404 return TypeInfos.size();
407 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is
409 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
410 // If the new filter coincides with the tail of an existing filter, then
411 // re-use the existing filter. Folding filters more than this requires
412 // re-ordering filters and/or their elements - probably not worth it.
413 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
414 E = FilterEnds.end(); I != E; ++I) {
415 unsigned i = *I, j = TyIds.size();
418 if (FilterIds[--i] != TyIds[--j])
422 // The new filter coincides with range [i, end) of the existing filter.
428 // Add the new filter.
429 int FilterID = -(1 + FilterIds.size());
430 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
431 for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
432 FilterIds.push_back(TyIds[I]);
433 FilterEnds.push_back(FilterIds.size());
434 FilterIds.push_back(0); // terminator
438 /// getPersonality - Return the personality function for the current function.
439 Function *MachineModuleInfo::getPersonality() const {
440 // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
442 return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
445 /// getPersonalityIndex - Return unique index for current personality
446 /// function. NULL/first personality function should always get zero index.
447 unsigned MachineModuleInfo::getPersonalityIndex() const {
448 const Function* Personality = NULL;
450 // Scan landing pads. If there is at least one non-NULL personality - use it.
451 for (unsigned i = 0; i != LandingPads.size(); ++i)
452 if (LandingPads[i].Personality) {
453 Personality = LandingPads[i].Personality;
457 for (unsigned i = 0; i < Personalities.size(); ++i) {
458 if (Personalities[i] == Personality)
462 // This will happen if the current personality function is
463 // in the zero index.