xref: /llvm-project/llvm/lib/CodeGen/MachineModuleInfo.cpp (revision c3b2e80b9d7615190bb5d50f17d6524c2fd8d66d)
1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/CodeGen/MachineModuleInfo.h"
11 #include "llvm/ADT/PointerUnion.h"
12 #include "llvm/ADT/TinyPtrVector.h"
13 #include "llvm/Analysis/EHPersonalities.h"
14 #include "llvm/Analysis/ValueTracking.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Target/TargetLoweringObjectFile.h"
27 #include "llvm/Target/TargetMachine.h"
28 using namespace llvm;
29 using namespace llvm::dwarf;
30 
31 // Handle the Pass registration stuff necessary to use DataLayout's.
32 INITIALIZE_TM_PASS(MachineModuleInfo, "machinemoduleinfo",
33                    "Machine Module Information", false, false)
34 char MachineModuleInfo::ID = 0;
35 
36 // Out of line virtual method.
37 MachineModuleInfoImpl::~MachineModuleInfoImpl() {}
38 
39 namespace llvm {
40 class MMIAddrLabelMapCallbackPtr final : CallbackVH {
41   MMIAddrLabelMap *Map;
42 public:
43   MMIAddrLabelMapCallbackPtr() : Map(nullptr) {}
44   MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {}
45 
46   void setPtr(BasicBlock *BB) {
47     ValueHandleBase::operator=(BB);
48   }
49 
50   void setMap(MMIAddrLabelMap *map) { Map = map; }
51 
52   void deleted() override;
53   void allUsesReplacedWith(Value *V2) override;
54 };
55 
56 class MMIAddrLabelMap {
57   MCContext &Context;
58   struct AddrLabelSymEntry {
59     /// Symbols - The symbols for the label.
60     TinyPtrVector<MCSymbol *> Symbols;
61 
62     Function *Fn;   // The containing function of the BasicBlock.
63     unsigned Index; // The index in BBCallbacks for the BasicBlock.
64   };
65 
66   DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
67 
68   /// BBCallbacks - Callbacks for the BasicBlock's that we have entries for.  We
69   /// use this so we get notified if a block is deleted or RAUWd.
70   std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
71 
72   /// DeletedAddrLabelsNeedingEmission - This is a per-function list of symbols
73   /// whose corresponding BasicBlock got deleted.  These symbols need to be
74   /// emitted at some point in the file, so AsmPrinter emits them after the
75   /// function body.
76   DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
77     DeletedAddrLabelsNeedingEmission;
78 public:
79 
80   MMIAddrLabelMap(MCContext &context) : Context(context) {}
81   ~MMIAddrLabelMap() {
82     assert(DeletedAddrLabelsNeedingEmission.empty() &&
83            "Some labels for deleted blocks never got emitted");
84   }
85 
86   ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
87 
88   void takeDeletedSymbolsForFunction(Function *F,
89                                      std::vector<MCSymbol*> &Result);
90 
91   void UpdateForDeletedBlock(BasicBlock *BB);
92   void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
93 };
94 }
95 
96 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
97   assert(BB->hasAddressTaken() &&
98          "Shouldn't get label for block without address taken");
99   AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
100 
101   // If we already had an entry for this block, just return it.
102   if (!Entry.Symbols.empty()) {
103     assert(BB->getParent() == Entry.Fn && "Parent changed");
104     return Entry.Symbols;
105   }
106 
107   // Otherwise, this is a new entry, create a new symbol for it and add an
108   // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
109   BBCallbacks.emplace_back(BB);
110   BBCallbacks.back().setMap(this);
111   Entry.Index = BBCallbacks.size() - 1;
112   Entry.Fn = BB->getParent();
113   Entry.Symbols.push_back(Context.createTempSymbol());
114   return Entry.Symbols;
115 }
116 
117 /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return
118 /// them.
119 void MMIAddrLabelMap::
120 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
121   DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
122     DeletedAddrLabelsNeedingEmission.find(F);
123 
124   // If there are no entries for the function, just return.
125   if (I == DeletedAddrLabelsNeedingEmission.end()) return;
126 
127   // Otherwise, take the list.
128   std::swap(Result, I->second);
129   DeletedAddrLabelsNeedingEmission.erase(I);
130 }
131 
132 
133 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
134   // If the block got deleted, there is no need for the symbol.  If the symbol
135   // was already emitted, we can just forget about it, otherwise we need to
136   // queue it up for later emission when the function is output.
137   AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
138   AddrLabelSymbols.erase(BB);
139   assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
140   BBCallbacks[Entry.Index] = nullptr;  // Clear the callback.
141 
142   assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
143          "Block/parent mismatch");
144 
145   for (MCSymbol *Sym : Entry.Symbols) {
146     if (Sym->isDefined())
147       return;
148 
149     // If the block is not yet defined, we need to emit it at the end of the
150     // function.  Add the symbol to the DeletedAddrLabelsNeedingEmission list
151     // for the containing Function.  Since the block is being deleted, its
152     // parent may already be removed, we have to get the function from 'Entry'.
153     DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
154   }
155 }
156 
157 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
158   // Get the entry for the RAUW'd block and remove it from our map.
159   AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
160   AddrLabelSymbols.erase(Old);
161   assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
162 
163   AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
164 
165   // If New is not address taken, just move our symbol over to it.
166   if (NewEntry.Symbols.empty()) {
167     BBCallbacks[OldEntry.Index].setPtr(New);    // Update the callback.
168     NewEntry = std::move(OldEntry);             // Set New's entry.
169     return;
170   }
171 
172   BBCallbacks[OldEntry.Index] = nullptr;    // Update the callback.
173 
174   // Otherwise, we need to add the old symbols to the new block's set.
175   NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
176                           OldEntry.Symbols.end());
177 }
178 
179 
180 void MMIAddrLabelMapCallbackPtr::deleted() {
181   Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
182 }
183 
184 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
185   Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
186 }
187 
188 
189 //===----------------------------------------------------------------------===//
190 
191 MachineModuleInfo::MachineModuleInfo(const TargetMachine *TM)
192   : ImmutablePass(ID), Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
193                                TM->getObjFileLowering(), nullptr, false) {
194   initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
195 }
196 
197 MachineModuleInfo::~MachineModuleInfo() {
198 }
199 
200 bool MachineModuleInfo::doInitialization(Module &M) {
201 
202   ObjFileMMI = nullptr;
203   CurCallSite = 0;
204   CallsEHReturn = false;
205   CallsUnwindInit = false;
206   HasEHFunclets = false;
207   DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false;
208   PersonalityTypeCache = EHPersonality::Unknown;
209   AddrLabelSymbols = nullptr;
210   TheModule = nullptr;
211 
212   return false;
213 }
214 
215 bool MachineModuleInfo::doFinalization(Module &M) {
216 
217   Personalities.clear();
218 
219   delete AddrLabelSymbols;
220   AddrLabelSymbols = nullptr;
221 
222   Context.reset();
223 
224   delete ObjFileMMI;
225   ObjFileMMI = nullptr;
226 
227   return false;
228 }
229 
230 /// EndFunction - Discard function meta information.
231 ///
232 void MachineModuleInfo::EndFunction() {
233   // Clean up frame info.
234   FrameInstructions.clear();
235 
236   // Clean up exception info.
237   LandingPads.clear();
238   PersonalityTypeCache = EHPersonality::Unknown;
239   CallSiteMap.clear();
240   TypeInfos.clear();
241   FilterIds.clear();
242   FilterEnds.clear();
243   CallsEHReturn = false;
244   CallsUnwindInit = false;
245   HasEHFunclets = false;
246   VariableDbgInfos.clear();
247 }
248 
249 //===- Address of Block Management ----------------------------------------===//
250 
251 /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified
252 /// basic block when its address is taken.  If other blocks were RAUW'd to
253 /// this one, we may have to emit them as well, return the whole set.
254 ArrayRef<MCSymbol *>
255 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
256   // Lazily create AddrLabelSymbols.
257   if (!AddrLabelSymbols)
258     AddrLabelSymbols = new MMIAddrLabelMap(Context);
259  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
260 }
261 
262 
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) return;
272   return AddrLabelSymbols->
273      takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
274 }
275 
276 //===- EH -----------------------------------------------------------------===//
277 
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)
286       return LP;
287   }
288 
289   LandingPads.push_back(LandingPadInfo(LandingPad));
290   return LandingPads[N];
291 }
292 
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);
300 }
301 
302 /// addLandingPad - Provide the label of a try LandingPad block.
303 ///
304 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
305   MCSymbol *LandingPadLabel = Context.createTempSymbol();
306   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
307   LP.LandingPadLabel = LandingPadLabel;
308   return LandingPadLabel;
309 }
310 
311 void MachineModuleInfo::addPersonality(const Function *Personality) {
312   for (unsigned i = 0; i < Personalities.size(); ++i)
313     if (Personalities[i] == Personality)
314       return;
315   Personalities.push_back(Personality);
316 }
317 
318 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
319 ///
320 void MachineModuleInfo::
321 addCatchTypeInfo(MachineBasicBlock *LandingPad,
322                  ArrayRef<const GlobalValue *> TyInfo) {
323   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
324   for (unsigned N = TyInfo.size(); N; --N)
325     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
326 }
327 
328 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
329 ///
330 void MachineModuleInfo::
331 addFilterTypeInfo(MachineBasicBlock *LandingPad,
332                   ArrayRef<const GlobalValue *> TyInfo) {
333   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
334   std::vector<unsigned> IdsInFilter(TyInfo.size());
335   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
336     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
337   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
338 }
339 
340 /// addCleanup - Add a cleanup action for a landing pad.
341 ///
342 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
343   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
344   LP.TypeIds.push_back(0);
345 }
346 
347 void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad,
348                                            const Function *Filter,
349                                            const BlockAddress *RecoverBA) {
350   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
351   SEHHandler Handler;
352   Handler.FilterOrFinally = Filter;
353   Handler.RecoverBA = RecoverBA;
354   LP.SEHHandlers.push_back(Handler);
355 }
356 
357 void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
358                                              const Function *Cleanup) {
359   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
360   SEHHandler Handler;
361   Handler.FilterOrFinally = Cleanup;
362   Handler.RecoverBA = nullptr;
363   LP.SEHHandlers.push_back(Handler);
364 }
365 
366 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
367 /// pads.
368 void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
369   for (unsigned i = 0; i != LandingPads.size(); ) {
370     LandingPadInfo &LandingPad = LandingPads[i];
371     if (LandingPad.LandingPadLabel &&
372         !LandingPad.LandingPadLabel->isDefined() &&
373         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
374       LandingPad.LandingPadLabel = nullptr;
375 
376     // Special case: we *should* emit LPs with null LP MBB. This indicates
377     // "nounwind" case.
378     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
379       LandingPads.erase(LandingPads.begin() + i);
380       continue;
381     }
382 
383     for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
384       MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
385       MCSymbol *EndLabel = LandingPad.EndLabels[j];
386       if ((BeginLabel->isDefined() ||
387            (LPMap && (*LPMap)[BeginLabel] != 0)) &&
388           (EndLabel->isDefined() ||
389            (LPMap && (*LPMap)[EndLabel] != 0))) continue;
390 
391       LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
392       LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
393       --j;
394       --e;
395     }
396 
397     // Remove landing pads with no try-ranges.
398     if (LandingPads[i].BeginLabels.empty()) {
399       LandingPads.erase(LandingPads.begin() + i);
400       continue;
401     }
402 
403     // If there is no landing pad, ensure that the list of typeids is empty.
404     // If the only typeid is a cleanup, this is the same as having no typeids.
405     if (!LandingPad.LandingPadBlock ||
406         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
407       LandingPad.TypeIds.clear();
408     ++i;
409   }
410 }
411 
412 /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call site
413 /// indexes.
414 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym,
415                                               ArrayRef<unsigned> Sites) {
416   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
417 }
418 
419 /// getTypeIDFor - Return the type id for the specified typeinfo.  This is
420 /// function wide.
421 unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) {
422   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
423     if (TypeInfos[i] == TI) return i + 1;
424 
425   TypeInfos.push_back(TI);
426   return TypeInfos.size();
427 }
428 
429 /// getFilterIDFor - Return the filter id for the specified typeinfos.  This is
430 /// function wide.
431 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
432   // If the new filter coincides with the tail of an existing filter, then
433   // re-use the existing filter.  Folding filters more than this requires
434   // re-ordering filters and/or their elements - probably not worth it.
435   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
436        E = FilterEnds.end(); I != E; ++I) {
437     unsigned i = *I, j = TyIds.size();
438 
439     while (i && j)
440       if (FilterIds[--i] != TyIds[--j])
441         goto try_next;
442 
443     if (!j)
444       // The new filter coincides with range [i, end) of the existing filter.
445       return -(1 + i);
446 
447 try_next:;
448   }
449 
450   // Add the new filter.
451   int FilterID = -(1 + FilterIds.size());
452   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
453   FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
454   FilterEnds.push_back(FilterIds.size());
455   FilterIds.push_back(0); // terminator
456   return FilterID;
457 }
458