1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/CodeGen/MachineModuleInfo.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/DenseMap.h"
12 #include "llvm/ADT/PostOrderIterator.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/TinyPtrVector.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/IR/BasicBlock.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/Value.h"
22 #include "llvm/IR/ValueHandle.h"
23 #include "llvm/InitializePasses.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCSymbolXCOFF.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <memory>
35 #include <utility>
36 #include <vector>
37
38 using namespace llvm;
39 using namespace llvm::dwarf;
40
41 // Out of line virtual method.
42 MachineModuleInfoImpl::~MachineModuleInfoImpl() = default;
43
44 namespace llvm {
45
46 class MMIAddrLabelMapCallbackPtr final : CallbackVH {
47 MMIAddrLabelMap *Map = nullptr;
48
49 public:
50 MMIAddrLabelMapCallbackPtr() = default;
MMIAddrLabelMapCallbackPtr(Value * V)51 MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
52
setPtr(BasicBlock * BB)53 void setPtr(BasicBlock *BB) {
54 ValueHandleBase::operator=(BB);
55 }
56
setMap(MMIAddrLabelMap * map)57 void setMap(MMIAddrLabelMap *map) { Map = map; }
58
59 void deleted() override;
60 void allUsesReplacedWith(Value *V2) override;
61 };
62
63 class MMIAddrLabelMap {
64 MCContext &Context;
65 struct AddrLabelSymEntry {
66 /// The symbols for the label.
67 TinyPtrVector<MCSymbol *> Symbols;
68
69 Function *Fn; // The containing function of the BasicBlock.
70 unsigned Index; // The index in BBCallbacks for the BasicBlock.
71 };
72
73 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
74
75 /// Callbacks for the BasicBlock's that we have entries for. We use this so
76 /// we get notified if a block is deleted or RAUWd.
77 std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
78
79 /// This is a per-function list of symbols whose corresponding BasicBlock got
80 /// deleted. These symbols need to be emitted at some point in the file, so
81 /// AsmPrinter emits them after the function body.
82 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>
83 DeletedAddrLabelsNeedingEmission;
84
85 public:
MMIAddrLabelMap(MCContext & context)86 MMIAddrLabelMap(MCContext &context) : Context(context) {}
87
~MMIAddrLabelMap()88 ~MMIAddrLabelMap() {
89 assert(DeletedAddrLabelsNeedingEmission.empty() &&
90 "Some labels for deleted blocks never got emitted");
91 }
92
93 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
94
95 void takeDeletedSymbolsForFunction(Function *F,
96 std::vector<MCSymbol*> &Result);
97
98 void UpdateForDeletedBlock(BasicBlock *BB);
99 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
100 };
101
102 } // end namespace llvm
103
getAddrLabelSymbolToEmit(BasicBlock * BB)104 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
105 assert(BB->hasAddressTaken() &&
106 "Shouldn't get label for block without address taken");
107 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
108
109 // If we already had an entry for this block, just return it.
110 if (!Entry.Symbols.empty()) {
111 assert(BB->getParent() == Entry.Fn && "Parent changed");
112 return Entry.Symbols;
113 }
114
115 // Otherwise, this is a new entry, create a new symbol for it and add an
116 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
117 BBCallbacks.emplace_back(BB);
118 BBCallbacks.back().setMap(this);
119 Entry.Index = BBCallbacks.size() - 1;
120 Entry.Fn = BB->getParent();
121 MCSymbol *Sym = Context.createTempSymbol(!BB->hasAddressTaken());
122 if (Context.getObjectFileInfo()->getTargetTriple().isOSBinFormatXCOFF()) {
123 MCSymbol *FnEntryPointSym =
124 Context.lookupSymbol("." + Entry.Fn->getName());
125 assert(FnEntryPointSym && "The function entry pointer symbol should have"
126 " already been initialized.");
127 MCSectionXCOFF *Csect =
128 cast<MCSymbolXCOFF>(FnEntryPointSym)->getContainingCsect();
129 cast<MCSymbolXCOFF>(Sym)->setContainingCsect(Csect);
130 }
131 Entry.Symbols.push_back(Sym);
132 return Entry.Symbols;
133 }
134
135 /// If we have any deleted symbols for F, return them.
136 void MMIAddrLabelMap::
takeDeletedSymbolsForFunction(Function * F,std::vector<MCSymbol * > & Result)137 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
138 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>::iterator I =
139 DeletedAddrLabelsNeedingEmission.find(F);
140
141 // If there are no entries for the function, just return.
142 if (I == DeletedAddrLabelsNeedingEmission.end()) return;
143
144 // Otherwise, take the list.
145 std::swap(Result, I->second);
146 DeletedAddrLabelsNeedingEmission.erase(I);
147 }
148
UpdateForDeletedBlock(BasicBlock * BB)149 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
150 // If the block got deleted, there is no need for the symbol. If the symbol
151 // was already emitted, we can just forget about it, otherwise we need to
152 // queue it up for later emission when the function is output.
153 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
154 AddrLabelSymbols.erase(BB);
155 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
156 BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
157
158 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
159 "Block/parent mismatch");
160
161 for (MCSymbol *Sym : Entry.Symbols) {
162 if (Sym->isDefined())
163 return;
164
165 // If the block is not yet defined, we need to emit it at the end of the
166 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
167 // for the containing Function. Since the block is being deleted, its
168 // parent may already be removed, we have to get the function from 'Entry'.
169 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
170 }
171 }
172
UpdateForRAUWBlock(BasicBlock * Old,BasicBlock * New)173 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
174 // Get the entry for the RAUW'd block and remove it from our map.
175 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
176 AddrLabelSymbols.erase(Old);
177 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
178
179 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
180
181 // If New is not address taken, just move our symbol over to it.
182 if (NewEntry.Symbols.empty()) {
183 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
184 NewEntry = std::move(OldEntry); // Set New's entry.
185 return;
186 }
187
188 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
189
190 // Otherwise, we need to add the old symbols to the new block's set.
191 NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
192 OldEntry.Symbols.end());
193 }
194
deleted()195 void MMIAddrLabelMapCallbackPtr::deleted() {
196 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
197 }
198
allUsesReplacedWith(Value * V2)199 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
200 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
201 }
202
initialize()203 void MachineModuleInfo::initialize() {
204 ObjFileMMI = nullptr;
205 CurCallSite = 0;
206 UsesMSVCFloatingPoint = UsesMorestackAddr = false;
207 HasSplitStack = HasNosplitStack = false;
208 AddrLabelSymbols = nullptr;
209 }
210
finalize()211 void MachineModuleInfo::finalize() {
212 Personalities.clear();
213
214 delete AddrLabelSymbols;
215 AddrLabelSymbols = nullptr;
216
217 Context.reset();
218
219 delete ObjFileMMI;
220 ObjFileMMI = nullptr;
221 }
222
MachineModuleInfo(MachineModuleInfo && MMI)223 MachineModuleInfo::MachineModuleInfo(MachineModuleInfo &&MMI)
224 : TM(std::move(MMI.TM)),
225 Context(MMI.TM.getMCAsmInfo(), MMI.TM.getMCRegisterInfo(),
226 MMI.TM.getObjFileLowering(), nullptr, nullptr, false) {
227 ObjFileMMI = MMI.ObjFileMMI;
228 CurCallSite = MMI.CurCallSite;
229 UsesMSVCFloatingPoint = MMI.UsesMSVCFloatingPoint;
230 UsesMorestackAddr = MMI.UsesMorestackAddr;
231 HasSplitStack = MMI.HasSplitStack;
232 HasNosplitStack = MMI.HasNosplitStack;
233 AddrLabelSymbols = MMI.AddrLabelSymbols;
234 TheModule = MMI.TheModule;
235 }
236
MachineModuleInfo(const LLVMTargetMachine * TM)237 MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM)
238 : TM(*TM), Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
239 TM->getObjFileLowering(), nullptr, nullptr, false) {
240 initialize();
241 }
242
~MachineModuleInfo()243 MachineModuleInfo::~MachineModuleInfo() { finalize(); }
244
245 //===- Address of Block Management ----------------------------------------===//
246
247 ArrayRef<MCSymbol *>
getAddrLabelSymbolToEmit(const BasicBlock * BB)248 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
249 // Lazily create AddrLabelSymbols.
250 if (!AddrLabelSymbols)
251 AddrLabelSymbols = new MMIAddrLabelMap(Context);
252 return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
253 }
254
255 void MachineModuleInfo::
takeDeletedSymbolsForFunction(const Function * F,std::vector<MCSymbol * > & Result)256 takeDeletedSymbolsForFunction(const Function *F,
257 std::vector<MCSymbol*> &Result) {
258 // If no blocks have had their addresses taken, we're done.
259 if (!AddrLabelSymbols) return;
260 return AddrLabelSymbols->
261 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
262 }
263
264 /// \name Exception Handling
265 /// \{
266
addPersonality(const Function * Personality)267 void MachineModuleInfo::addPersonality(const Function *Personality) {
268 for (unsigned i = 0; i < Personalities.size(); ++i)
269 if (Personalities[i] == Personality)
270 return;
271 Personalities.push_back(Personality);
272 }
273
274 /// \}
275
276 MachineFunction *
getMachineFunction(const Function & F) const277 MachineModuleInfo::getMachineFunction(const Function &F) const {
278 auto I = MachineFunctions.find(&F);
279 return I != MachineFunctions.end() ? I->second.get() : nullptr;
280 }
281
282 MachineFunction &
getOrCreateMachineFunction(const Function & F)283 MachineModuleInfo::getOrCreateMachineFunction(const Function &F) {
284 // Shortcut for the common case where a sequence of MachineFunctionPasses
285 // all query for the same Function.
286 if (LastRequest == &F)
287 return *LastResult;
288
289 auto I = MachineFunctions.insert(
290 std::make_pair(&F, std::unique_ptr<MachineFunction>()));
291 MachineFunction *MF;
292 if (I.second) {
293 // No pre-existing machine function, create a new one.
294 const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
295 MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
296 // Update the set entry.
297 I.first->second.reset(MF);
298 } else {
299 MF = I.first->second.get();
300 }
301
302 LastRequest = &F;
303 LastResult = MF;
304 return *MF;
305 }
306
deleteMachineFunctionFor(Function & F)307 void MachineModuleInfo::deleteMachineFunctionFor(Function &F) {
308 MachineFunctions.erase(&F);
309 LastRequest = nullptr;
310 LastResult = nullptr;
311 }
312
313 namespace {
314
315 /// This pass frees the MachineFunction object associated with a Function.
316 class FreeMachineFunction : public FunctionPass {
317 public:
318 static char ID;
319
FreeMachineFunction()320 FreeMachineFunction() : FunctionPass(ID) {}
321
getAnalysisUsage(AnalysisUsage & AU) const322 void getAnalysisUsage(AnalysisUsage &AU) const override {
323 AU.addRequired<MachineModuleInfoWrapperPass>();
324 AU.addPreserved<MachineModuleInfoWrapperPass>();
325 }
326
runOnFunction(Function & F)327 bool runOnFunction(Function &F) override {
328 MachineModuleInfo &MMI =
329 getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
330 MMI.deleteMachineFunctionFor(F);
331 return true;
332 }
333
getPassName() const334 StringRef getPassName() const override {
335 return "Free MachineFunction";
336 }
337 };
338
339 } // end anonymous namespace
340
341 char FreeMachineFunction::ID;
342
createFreeMachineFunctionPass()343 FunctionPass *llvm::createFreeMachineFunctionPass() {
344 return new FreeMachineFunction();
345 }
346
MachineModuleInfoWrapperPass(const LLVMTargetMachine * TM)347 MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
348 const LLVMTargetMachine *TM)
349 : ImmutablePass(ID), MMI(TM) {
350 initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
351 }
352
353 // Handle the Pass registration stuff necessary to use DataLayout's.
354 INITIALIZE_PASS(MachineModuleInfoWrapperPass, "machinemoduleinfo",
355 "Machine Module Information", false, false)
356 char MachineModuleInfoWrapperPass::ID = 0;
357
doInitialization(Module & M)358 bool MachineModuleInfoWrapperPass::doInitialization(Module &M) {
359 MMI.initialize();
360 MMI.TheModule = &M;
361 MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
362 return false;
363 }
364
doFinalization(Module & M)365 bool MachineModuleInfoWrapperPass::doFinalization(Module &M) {
366 MMI.finalize();
367 return false;
368 }
369
370 AnalysisKey MachineModuleAnalysis::Key;
371
run(Module & M,ModuleAnalysisManager &)372 MachineModuleInfo MachineModuleAnalysis::run(Module &M,
373 ModuleAnalysisManager &) {
374 MachineModuleInfo MMI(TM);
375 MMI.TheModule = &M;
376 MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
377 return MMI;
378 }
379