xref: /llvm-project/llvm/lib/CodeGen/MachineModuleInfo.cpp (revision 9583a3f2625818b78c0cf6d473cdedb9f23ad82c)
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;
51   MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
52 
53   void setPtr(BasicBlock *BB) {
54     ValueHandleBase::operator=(BB);
55   }
56 
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 public:
80   MMIAddrLabelMap(MCContext &context) : Context(context) {}
81 
82   ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
83 
84   void UpdateForDeletedBlock(BasicBlock *BB);
85   void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
86 };
87 
88 } // end namespace llvm
89 
90 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
91   assert(BB->hasAddressTaken() &&
92          "Shouldn't get label for block without address taken");
93   AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
94 
95   // If we already had an entry for this block, just return it.
96   if (!Entry.Symbols.empty()) {
97     assert(BB->getParent() == Entry.Fn && "Parent changed");
98     return Entry.Symbols;
99   }
100 
101   // Otherwise, this is a new entry, create a new symbol for it and add an
102   // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
103   BBCallbacks.emplace_back(BB);
104   BBCallbacks.back().setMap(this);
105   Entry.Index = BBCallbacks.size() - 1;
106   Entry.Fn = BB->getParent();
107   MCSymbol *Sym = Context.createTempSymbol(!BB->hasAddressTaken());
108   if (Context.getObjectFileInfo()->getTargetTriple().isOSBinFormatXCOFF()) {
109     MCSymbol *FnEntryPointSym =
110         Context.lookupSymbol("." + Entry.Fn->getName());
111     assert(FnEntryPointSym && "The function entry pointer symbol should have"
112 		              " already been initialized.");
113     MCSectionXCOFF *Csect =
114         cast<MCSymbolXCOFF>(FnEntryPointSym)->getContainingCsect();
115     cast<MCSymbolXCOFF>(Sym)->setContainingCsect(Csect);
116   }
117   Entry.Symbols.push_back(Sym);
118   return Entry.Symbols;
119 }
120 
121 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
122   // If the block got deleted, there is no need for the symbol.  If the symbol
123   // was already emitted, we can just forget about it, otherwise we need to
124   // queue it up for later emission when the function is output.
125   AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
126   AddrLabelSymbols.erase(BB);
127   assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
128   BBCallbacks[Entry.Index] = nullptr;  // Clear the callback.
129 
130   assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
131          "Block/parent mismatch");
132 
133   assert(llvm::all_of(Entry.Symbols, [](MCSymbol *Sym) {
134     return Sym->isDefined(); }));
135 }
136 
137 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
138   // Get the entry for the RAUW'd block and remove it from our map.
139   AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
140   AddrLabelSymbols.erase(Old);
141   assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
142 
143   AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
144 
145   // If New is not address taken, just move our symbol over to it.
146   if (NewEntry.Symbols.empty()) {
147     BBCallbacks[OldEntry.Index].setPtr(New);    // Update the callback.
148     NewEntry = std::move(OldEntry);             // Set New's entry.
149     return;
150   }
151 
152   BBCallbacks[OldEntry.Index] = nullptr;    // Update the callback.
153 
154   // Otherwise, we need to add the old symbols to the new block's set.
155   NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
156                           OldEntry.Symbols.end());
157 }
158 
159 void MMIAddrLabelMapCallbackPtr::deleted() {
160   Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
161 }
162 
163 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
164   Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
165 }
166 
167 void MachineModuleInfo::initialize() {
168   ObjFileMMI = nullptr;
169   CurCallSite = 0;
170   UsesMSVCFloatingPoint = UsesMorestackAddr = false;
171   HasSplitStack = HasNosplitStack = false;
172   AddrLabelSymbols = nullptr;
173 }
174 
175 void MachineModuleInfo::finalize() {
176   Personalities.clear();
177 
178   delete AddrLabelSymbols;
179   AddrLabelSymbols = nullptr;
180 
181   Context.reset();
182 
183   delete ObjFileMMI;
184   ObjFileMMI = nullptr;
185 }
186 
187 MachineModuleInfo::MachineModuleInfo(MachineModuleInfo &&MMI)
188     : TM(std::move(MMI.TM)),
189       Context(MMI.TM.getMCAsmInfo(), MMI.TM.getMCRegisterInfo(),
190               MMI.TM.getObjFileLowering(), nullptr, nullptr, false) {
191   ObjFileMMI = MMI.ObjFileMMI;
192   CurCallSite = MMI.CurCallSite;
193   UsesMSVCFloatingPoint = MMI.UsesMSVCFloatingPoint;
194   UsesMorestackAddr = MMI.UsesMorestackAddr;
195   HasSplitStack = MMI.HasSplitStack;
196   HasNosplitStack = MMI.HasNosplitStack;
197   AddrLabelSymbols = MMI.AddrLabelSymbols;
198   TheModule = MMI.TheModule;
199 }
200 
201 MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM)
202     : TM(*TM), Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
203                        TM->getObjFileLowering(), nullptr, nullptr, false) {
204   initialize();
205 }
206 
207 MachineModuleInfo::~MachineModuleInfo() { finalize(); }
208 
209 //===- Address of Block Management ----------------------------------------===//
210 
211 ArrayRef<MCSymbol *>
212 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
213   // Lazily create AddrLabelSymbols.
214   if (!AddrLabelSymbols)
215     AddrLabelSymbols = new MMIAddrLabelMap(Context);
216  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
217 }
218 
219 /// \name Exception Handling
220 /// \{
221 
222 void MachineModuleInfo::addPersonality(const Function *Personality) {
223   for (unsigned i = 0; i < Personalities.size(); ++i)
224     if (Personalities[i] == Personality)
225       return;
226   Personalities.push_back(Personality);
227 }
228 
229 /// \}
230 
231 MachineFunction *
232 MachineModuleInfo::getMachineFunction(const Function &F) const {
233   auto I = MachineFunctions.find(&F);
234   return I != MachineFunctions.end() ? I->second.get() : nullptr;
235 }
236 
237 MachineFunction &
238 MachineModuleInfo::getOrCreateMachineFunction(const Function &F) {
239   // Shortcut for the common case where a sequence of MachineFunctionPasses
240   // all query for the same Function.
241   if (LastRequest == &F)
242     return *LastResult;
243 
244   auto I = MachineFunctions.insert(
245       std::make_pair(&F, std::unique_ptr<MachineFunction>()));
246   MachineFunction *MF;
247   if (I.second) {
248     // No pre-existing machine function, create a new one.
249     const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
250     MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
251     // Update the set entry.
252     I.first->second.reset(MF);
253   } else {
254     MF = I.first->second.get();
255   }
256 
257   LastRequest = &F;
258   LastResult = MF;
259   return *MF;
260 }
261 
262 void MachineModuleInfo::deleteMachineFunctionFor(Function &F) {
263   MachineFunctions.erase(&F);
264   LastRequest = nullptr;
265   LastResult = nullptr;
266 }
267 
268 namespace {
269 
270 /// This pass frees the MachineFunction object associated with a Function.
271 class FreeMachineFunction : public FunctionPass {
272 public:
273   static char ID;
274 
275   FreeMachineFunction() : FunctionPass(ID) {}
276 
277   void getAnalysisUsage(AnalysisUsage &AU) const override {
278     AU.addRequired<MachineModuleInfoWrapperPass>();
279     AU.addPreserved<MachineModuleInfoWrapperPass>();
280   }
281 
282   bool runOnFunction(Function &F) override {
283     MachineModuleInfo &MMI =
284         getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
285     MMI.deleteMachineFunctionFor(F);
286     return true;
287   }
288 
289   StringRef getPassName() const override {
290     return "Free MachineFunction";
291   }
292 };
293 
294 } // end anonymous namespace
295 
296 char FreeMachineFunction::ID;
297 
298 FunctionPass *llvm::createFreeMachineFunctionPass() {
299   return new FreeMachineFunction();
300 }
301 
302 MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
303     const LLVMTargetMachine *TM)
304     : ImmutablePass(ID), MMI(TM) {
305   initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
306 }
307 
308 // Handle the Pass registration stuff necessary to use DataLayout's.
309 INITIALIZE_PASS(MachineModuleInfoWrapperPass, "machinemoduleinfo",
310                 "Machine Module Information", false, false)
311 char MachineModuleInfoWrapperPass::ID = 0;
312 
313 bool MachineModuleInfoWrapperPass::doInitialization(Module &M) {
314   MMI.initialize();
315   MMI.TheModule = &M;
316   MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
317   return false;
318 }
319 
320 bool MachineModuleInfoWrapperPass::doFinalization(Module &M) {
321   MMI.finalize();
322   return false;
323 }
324 
325 AnalysisKey MachineModuleAnalysis::Key;
326 
327 MachineModuleInfo MachineModuleAnalysis::run(Module &M,
328                                              ModuleAnalysisManager &) {
329   MachineModuleInfo MMI(TM);
330   MMI.TheModule = &M;
331   MMI.DbgInfoAvailable = !M.debug_compile_units().empty();
332   return MMI;
333 }
334