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