xref: /llvm-project/llvm/lib/CodeGen/MachineModuleInfo.cpp (revision 3659780d58722ea38adf25f7116151f2ecf2d521)
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/StringRef.h"
13 #include "llvm/ADT/TinyPtrVector.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DiagnosticInfo.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/ValueHandle.h"
22 #include "llvm/InitializePasses.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/CommandLine.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 static cl::opt<bool>
42     DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
43                              cl::desc("Disable debug info printing"));
44 
45 // Out of line virtual method.
46 MachineModuleInfoImpl::~MachineModuleInfoImpl() = default;
47 
48 namespace llvm {
49 
50 class MMIAddrLabelMapCallbackPtr final : CallbackVH {
51   MMIAddrLabelMap *Map = nullptr;
52 
53 public:
54   MMIAddrLabelMapCallbackPtr() = default;
55   MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
56 
57   void setPtr(BasicBlock *BB) {
58     ValueHandleBase::operator=(BB);
59   }
60 
61   void setMap(MMIAddrLabelMap *map) { Map = map; }
62 
63   void deleted() override;
64   void allUsesReplacedWith(Value *V2) override;
65 };
66 
67 class MMIAddrLabelMap {
68   MCContext &Context;
69   struct AddrLabelSymEntry {
70     /// The symbols for the label.
71     TinyPtrVector<MCSymbol *> Symbols;
72 
73     Function *Fn;   // The containing function of the BasicBlock.
74     unsigned Index; // The index in BBCallbacks for the BasicBlock.
75   };
76 
77   DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
78 
79   /// Callbacks for the BasicBlock's that we have entries for.  We use this so
80   /// we get notified if a block is deleted or RAUWd.
81   std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
82 
83   /// This is a per-function list of symbols whose corresponding BasicBlock got
84   /// deleted.  These symbols need to be emitted at some point in the file, so
85   /// AsmPrinter emits them after the function body.
86   DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>
87     DeletedAddrLabelsNeedingEmission;
88 
89 public:
90   MMIAddrLabelMap(MCContext &context) : Context(context) {}
91 
92   ~MMIAddrLabelMap() {
93     assert(DeletedAddrLabelsNeedingEmission.empty() &&
94            "Some labels for deleted blocks never got emitted");
95   }
96 
97   ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
98 
99   void takeDeletedSymbolsForFunction(Function *F,
100                                      std::vector<MCSymbol*> &Result);
101 
102   void UpdateForDeletedBlock(BasicBlock *BB);
103   void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
104 };
105 
106 } // end namespace llvm
107 
108 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
109   assert(BB->hasAddressTaken() &&
110          "Shouldn't get label for block without address taken");
111   AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
112 
113   // If we already had an entry for this block, just return it.
114   if (!Entry.Symbols.empty()) {
115     assert(BB->getParent() == Entry.Fn && "Parent changed");
116     return Entry.Symbols;
117   }
118 
119   // Otherwise, this is a new entry, create a new symbol for it and add an
120   // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
121   BBCallbacks.emplace_back(BB);
122   BBCallbacks.back().setMap(this);
123   Entry.Index = BBCallbacks.size() - 1;
124   Entry.Fn = BB->getParent();
125   MCSymbol *Sym = BB->hasAddressTaken() ? Context.createNamedTempSymbol()
126                                         : Context.createTempSymbol();
127   Entry.Symbols.push_back(Sym);
128   return Entry.Symbols;
129 }
130 
131 /// If we have any deleted symbols for F, return them.
132 void MMIAddrLabelMap::
133 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
134   DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>::iterator I =
135     DeletedAddrLabelsNeedingEmission.find(F);
136 
137   // If there are no entries for the function, just return.
138   if (I == DeletedAddrLabelsNeedingEmission.end()) return;
139 
140   // Otherwise, take the list.
141   std::swap(Result, I->second);
142   DeletedAddrLabelsNeedingEmission.erase(I);
143 }
144 
145 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
146   // If the block got deleted, there is no need for the symbol.  If the symbol
147   // was already emitted, we can just forget about it, otherwise we need to
148   // queue it up for later emission when the function is output.
149   AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
150   AddrLabelSymbols.erase(BB);
151   assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
152   BBCallbacks[Entry.Index] = nullptr;  // Clear the callback.
153 
154 #if !LLVM_MEMORY_SANITIZER_BUILD
155   // BasicBlock is destroyed already, so this access is UB detectable by msan.
156   assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
157          "Block/parent mismatch");
158 #endif
159 
160   for (MCSymbol *Sym : Entry.Symbols) {
161     if (Sym->isDefined())
162       return;
163 
164     // If the block is not yet defined, we need to emit it at the end of the
165     // function.  Add the symbol to the DeletedAddrLabelsNeedingEmission list
166     // for the containing Function.  Since the block is being deleted, its
167     // parent may already be removed, we have to get the function from 'Entry'.
168     DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
169   }
170 }
171 
172 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
173   // Get the entry for the RAUW'd block and remove it from our map.
174   AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
175   AddrLabelSymbols.erase(Old);
176   assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
177 
178   AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
179 
180   // If New is not address taken, just move our symbol over to it.
181   if (NewEntry.Symbols.empty()) {
182     BBCallbacks[OldEntry.Index].setPtr(New);    // Update the callback.
183     NewEntry = std::move(OldEntry);             // Set New's entry.
184     return;
185   }
186 
187   BBCallbacks[OldEntry.Index] = nullptr;    // Update the callback.
188 
189   // Otherwise, we need to add the old symbols to the new block's set.
190   llvm::append_range(NewEntry.Symbols, OldEntry.Symbols);
191 }
192 
193 void MMIAddrLabelMapCallbackPtr::deleted() {
194   Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
195 }
196 
197 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
198   Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
199 }
200 
201 void MachineModuleInfo::initialize() {
202   ObjFileMMI = nullptr;
203   CurCallSite = 0;
204   NextFnNum = 0;
205   UsesMSVCFloatingPoint = false;
206   AddrLabelSymbols = nullptr;
207   DbgInfoAvailable = false;
208 }
209 
210 void MachineModuleInfo::finalize() {
211   Personalities.clear();
212 
213   delete AddrLabelSymbols;
214   AddrLabelSymbols = nullptr;
215 
216   Context.reset();
217   // We don't clear the ExternalContext.
218 
219   delete ObjFileMMI;
220   ObjFileMMI = nullptr;
221 }
222 
223 MachineModuleInfo::MachineModuleInfo(MachineModuleInfo &&MMI)
224     : TM(std::move(MMI.TM)),
225       Context(MMI.TM.getTargetTriple(), MMI.TM.getMCAsmInfo(),
226               MMI.TM.getMCRegisterInfo(), MMI.TM.getMCSubtargetInfo(), nullptr,
227               nullptr, false),
228       MachineFunctions(std::move(MMI.MachineFunctions)) {
229   Context.setObjectFileInfo(MMI.TM.getObjFileLowering());
230   ObjFileMMI = MMI.ObjFileMMI;
231   CurCallSite = MMI.CurCallSite;
232   UsesMSVCFloatingPoint = MMI.UsesMSVCFloatingPoint;
233   AddrLabelSymbols = MMI.AddrLabelSymbols;
234   ExternalContext = MMI.ExternalContext;
235   TheModule = MMI.TheModule;
236 }
237 
238 MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM)
239     : TM(*TM), Context(TM->getTargetTriple(), TM->getMCAsmInfo(),
240                        TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(),
241                        nullptr, nullptr, false) {
242   Context.setObjectFileInfo(TM->getObjFileLowering());
243   initialize();
244 }
245 
246 MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM,
247                                      MCContext *ExtContext)
248     : TM(*TM), Context(TM->getTargetTriple(), TM->getMCAsmInfo(),
249                        TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(),
250                        nullptr, nullptr, false),
251       ExternalContext(ExtContext) {
252   Context.setObjectFileInfo(TM->getObjFileLowering());
253   initialize();
254 }
255 
256 MachineModuleInfo::~MachineModuleInfo() { finalize(); }
257 
258 //===- Address of Block Management ----------------------------------------===//
259 
260 ArrayRef<MCSymbol *>
261 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
262   // Lazily create AddrLabelSymbols.
263   if (!AddrLabelSymbols)
264     AddrLabelSymbols = new MMIAddrLabelMap(getContext());
265  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
266 }
267 
268 void MachineModuleInfo::
269 takeDeletedSymbolsForFunction(const Function *F,
270                               std::vector<MCSymbol*> &Result) {
271   // If no blocks have had their addresses taken, we're done.
272   if (!AddrLabelSymbols) return;
273   return AddrLabelSymbols->
274      takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
275 }
276 
277 /// \name Exception Handling
278 /// \{
279 
280 void MachineModuleInfo::addPersonality(const Function *Personality) {
281   if (!llvm::is_contained(Personalities, Personality))
282     Personalities.push_back(Personality);
283 }
284 
285 /// \}
286 
287 MachineFunction *
288 MachineModuleInfo::getMachineFunction(const Function &F) const {
289   auto I = MachineFunctions.find(&F);
290   return I != MachineFunctions.end() ? I->second.get() : nullptr;
291 }
292 
293 MachineFunction &MachineModuleInfo::getOrCreateMachineFunction(Function &F) {
294   // Shortcut for the common case where a sequence of MachineFunctionPasses
295   // all query for the same Function.
296   if (LastRequest == &F)
297     return *LastResult;
298 
299   auto I = MachineFunctions.insert(
300       std::make_pair(&F, std::unique_ptr<MachineFunction>()));
301   MachineFunction *MF;
302   if (I.second) {
303     // No pre-existing machine function, create a new one.
304     const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
305     MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
306     // Update the set entry.
307     I.first->second.reset(MF);
308   } else {
309     MF = I.first->second.get();
310   }
311 
312   LastRequest = &F;
313   LastResult = MF;
314   return *MF;
315 }
316 
317 void MachineModuleInfo::deleteMachineFunctionFor(Function &F) {
318   MachineFunctions.erase(&F);
319   LastRequest = nullptr;
320   LastResult = nullptr;
321 }
322 
323 namespace {
324 
325 /// This pass frees the MachineFunction object associated with a Function.
326 class FreeMachineFunction : public FunctionPass {
327 public:
328   static char ID;
329 
330   FreeMachineFunction() : FunctionPass(ID) {}
331 
332   void getAnalysisUsage(AnalysisUsage &AU) const override {
333     AU.addRequired<MachineModuleInfoWrapperPass>();
334     AU.addPreserved<MachineModuleInfoWrapperPass>();
335   }
336 
337   bool runOnFunction(Function &F) override {
338     MachineModuleInfo &MMI =
339         getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
340     MMI.deleteMachineFunctionFor(F);
341     return true;
342   }
343 
344   StringRef getPassName() const override {
345     return "Free MachineFunction";
346   }
347 };
348 
349 } // end anonymous namespace
350 
351 char FreeMachineFunction::ID;
352 
353 FunctionPass *llvm::createFreeMachineFunctionPass() {
354   return new FreeMachineFunction();
355 }
356 
357 MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
358     const LLVMTargetMachine *TM)
359     : ImmutablePass(ID), MMI(TM) {
360   initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
361 }
362 
363 MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
364     const LLVMTargetMachine *TM, MCContext *ExtContext)
365     : ImmutablePass(ID), MMI(TM, ExtContext) {
366   initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
367 }
368 
369 // Handle the Pass registration stuff necessary to use DataLayout's.
370 INITIALIZE_PASS(MachineModuleInfoWrapperPass, "machinemoduleinfo",
371                 "Machine Module Information", false, false)
372 char MachineModuleInfoWrapperPass::ID = 0;
373 
374 static unsigned getLocCookie(const SMDiagnostic &SMD, const SourceMgr &SrcMgr,
375                              std::vector<const MDNode *> &LocInfos) {
376   // Look up a LocInfo for the buffer this diagnostic is coming from.
377   unsigned BufNum = SrcMgr.FindBufferContainingLoc(SMD.getLoc());
378   const MDNode *LocInfo = nullptr;
379   if (BufNum > 0 && BufNum <= LocInfos.size())
380     LocInfo = LocInfos[BufNum - 1];
381 
382   // If the inline asm had metadata associated with it, pull out a location
383   // cookie corresponding to which line the error occurred on.
384   unsigned LocCookie = 0;
385   if (LocInfo) {
386     unsigned ErrorLine = SMD.getLineNo() - 1;
387     if (ErrorLine >= LocInfo->getNumOperands())
388       ErrorLine = 0;
389 
390     if (LocInfo->getNumOperands() != 0)
391       if (const ConstantInt *CI =
392               mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
393         LocCookie = CI->getZExtValue();
394   }
395 
396   return LocCookie;
397 }
398 
399 bool MachineModuleInfoWrapperPass::doInitialization(Module &M) {
400   MMI.initialize();
401   MMI.TheModule = &M;
402   // FIXME: Do this for new pass manager.
403   LLVMContext &Ctx = M.getContext();
404   MMI.getContext().setDiagnosticHandler(
405       [&Ctx, &M](const SMDiagnostic &SMD, bool IsInlineAsm,
406                  const SourceMgr &SrcMgr,
407                  std::vector<const MDNode *> &LocInfos) {
408         unsigned LocCookie = 0;
409         if (IsInlineAsm)
410           LocCookie = getLocCookie(SMD, SrcMgr, LocInfos);
411         Ctx.diagnose(
412             DiagnosticInfoSrcMgr(SMD, M.getName(), IsInlineAsm, LocCookie));
413       });
414   MMI.DbgInfoAvailable = !DisableDebugInfoPrinting &&
415                          !M.debug_compile_units().empty();
416   return false;
417 }
418 
419 bool MachineModuleInfoWrapperPass::doFinalization(Module &M) {
420   MMI.finalize();
421   return false;
422 }
423 
424 AnalysisKey MachineModuleAnalysis::Key;
425 
426 MachineModuleInfo MachineModuleAnalysis::run(Module &M,
427                                              ModuleAnalysisManager &) {
428   MachineModuleInfo MMI(TM);
429   MMI.TheModule = &M;
430   MMI.DbgInfoAvailable = !DisableDebugInfoPrinting &&
431                          !M.debug_compile_units().empty();
432   return MMI;
433 }
434