MachineModuleInfo.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. #include "llvm/CodeGen/MachineModuleInfo.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/DenseMap.h"
  11. #include "llvm/ADT/PostOrderIterator.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/DerivedTypes.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/IR/Module.h"
  20. #include "llvm/IR/Value.h"
  21. #include "llvm/IR/ValueHandle.h"
  22. #include "llvm/MC/MCContext.h"
  23. #include "llvm/MC/MCSymbol.h"
  24. #include "llvm/Pass.h"
  25. #include "llvm/Support/Casting.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Target/TargetLoweringObjectFile.h"
  28. #include "llvm/Target/TargetMachine.h"
  29. #include <algorithm>
  30. #include <cassert>
  31. #include <memory>
  32. #include <utility>
  33. #include <vector>
  34. using namespace llvm;
  35. using namespace llvm::dwarf;
  36. // Handle the Pass registration stuff necessary to use DataLayout's.
  37. INITIALIZE_PASS(MachineModuleInfo, "machinemoduleinfo",
  38. "Machine Module Information", false, false)
  39. char MachineModuleInfo::ID = 0;
  40. // Out of line virtual method.
  41. MachineModuleInfoImpl::~MachineModuleInfoImpl() = default;
  42. namespace llvm {
  43. class MMIAddrLabelMapCallbackPtr final : CallbackVH {
  44. MMIAddrLabelMap *Map = nullptr;
  45. public:
  46. MMIAddrLabelMapCallbackPtr() = default;
  47. MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V) {}
  48. void setPtr(BasicBlock *BB) {
  49. ValueHandleBase::operator=(BB);
  50. }
  51. void setMap(MMIAddrLabelMap *map) { Map = map; }
  52. void deleted() override;
  53. void allUsesReplacedWith(Value *V2) override;
  54. };
  55. class MMIAddrLabelMap {
  56. MCContext &Context;
  57. struct AddrLabelSymEntry {
  58. /// The symbols for the label.
  59. TinyPtrVector<MCSymbol *> Symbols;
  60. Function *Fn; // The containing function of the BasicBlock.
  61. unsigned Index; // The index in BBCallbacks for the BasicBlock.
  62. };
  63. DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
  64. /// Callbacks for the BasicBlock's that we have entries for. We use this so
  65. /// we get notified if a block is deleted or RAUWd.
  66. std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
  67. /// This is a per-function list of symbols whose corresponding BasicBlock got
  68. /// deleted. These symbols need to be emitted at some point in the file, so
  69. /// AsmPrinter emits them after the function body.
  70. DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>
  71. DeletedAddrLabelsNeedingEmission;
  72. public:
  73. MMIAddrLabelMap(MCContext &context) : Context(context) {}
  74. ~MMIAddrLabelMap() {
  75. assert(DeletedAddrLabelsNeedingEmission.empty() &&
  76. "Some labels for deleted blocks never got emitted");
  77. }
  78. ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
  79. void takeDeletedSymbolsForFunction(Function *F,
  80. std::vector<MCSymbol*> &Result);
  81. void UpdateForDeletedBlock(BasicBlock *BB);
  82. void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
  83. };
  84. } // end namespace llvm
  85. ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
  86. assert(BB->hasAddressTaken() &&
  87. "Shouldn't get label for block without address taken");
  88. AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
  89. // If we already had an entry for this block, just return it.
  90. if (!Entry.Symbols.empty()) {
  91. assert(BB->getParent() == Entry.Fn && "Parent changed");
  92. return Entry.Symbols;
  93. }
  94. // Otherwise, this is a new entry, create a new symbol for it and add an
  95. // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
  96. BBCallbacks.emplace_back(BB);
  97. BBCallbacks.back().setMap(this);
  98. Entry.Index = BBCallbacks.size() - 1;
  99. Entry.Fn = BB->getParent();
  100. Entry.Symbols.push_back(Context.createTempSymbol(!BB->hasAddressTaken()));
  101. return Entry.Symbols;
  102. }
  103. /// If we have any deleted symbols for F, return them.
  104. void MMIAddrLabelMap::
  105. takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
  106. DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>::iterator I =
  107. DeletedAddrLabelsNeedingEmission.find(F);
  108. // If there are no entries for the function, just return.
  109. if (I == DeletedAddrLabelsNeedingEmission.end()) return;
  110. // Otherwise, take the list.
  111. std::swap(Result, I->second);
  112. DeletedAddrLabelsNeedingEmission.erase(I);
  113. }
  114. void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
  115. // If the block got deleted, there is no need for the symbol. If the symbol
  116. // was already emitted, we can just forget about it, otherwise we need to
  117. // queue it up for later emission when the function is output.
  118. AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
  119. AddrLabelSymbols.erase(BB);
  120. assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  121. BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
  122. assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
  123. "Block/parent mismatch");
  124. for (MCSymbol *Sym : Entry.Symbols) {
  125. if (Sym->isDefined())
  126. return;
  127. // If the block is not yet defined, we need to emit it at the end of the
  128. // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
  129. // for the containing Function. Since the block is being deleted, its
  130. // parent may already be removed, we have to get the function from 'Entry'.
  131. DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
  132. }
  133. }
  134. void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
  135. // Get the entry for the RAUW'd block and remove it from our map.
  136. AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
  137. AddrLabelSymbols.erase(Old);
  138. assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
  139. AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
  140. // If New is not address taken, just move our symbol over to it.
  141. if (NewEntry.Symbols.empty()) {
  142. BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
  143. NewEntry = std::move(OldEntry); // Set New's entry.
  144. return;
  145. }
  146. BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
  147. // Otherwise, we need to add the old symbols to the new block's set.
  148. NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
  149. OldEntry.Symbols.end());
  150. }
  151. void MMIAddrLabelMapCallbackPtr::deleted() {
  152. Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
  153. }
  154. void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
  155. Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
  156. }
  157. MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM)
  158. : ImmutablePass(ID), TM(*TM),
  159. Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
  160. TM->getObjFileLowering(), nullptr, nullptr, false) {
  161. initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
  162. }
  163. MachineModuleInfo::~MachineModuleInfo() = default;
  164. bool MachineModuleInfo::doInitialization(Module &M) {
  165. ObjFileMMI = nullptr;
  166. CurCallSite = 0;
  167. UsesMSVCFloatingPoint = UsesMorestackAddr = false;
  168. HasSplitStack = HasNosplitStack = false;
  169. AddrLabelSymbols = nullptr;
  170. TheModule = &M;
  171. DbgInfoAvailable = !llvm::empty(M.debug_compile_units());
  172. return false;
  173. }
  174. bool MachineModuleInfo::doFinalization(Module &M) {
  175. Personalities.clear();
  176. delete AddrLabelSymbols;
  177. AddrLabelSymbols = nullptr;
  178. Context.reset();
  179. delete ObjFileMMI;
  180. ObjFileMMI = nullptr;
  181. return false;
  182. }
  183. //===- Address of Block Management ----------------------------------------===//
  184. ArrayRef<MCSymbol *>
  185. MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
  186. // Lazily create AddrLabelSymbols.
  187. if (!AddrLabelSymbols)
  188. AddrLabelSymbols = new MMIAddrLabelMap(Context);
  189. return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
  190. }
  191. void MachineModuleInfo::
  192. takeDeletedSymbolsForFunction(const Function *F,
  193. std::vector<MCSymbol*> &Result) {
  194. // If no blocks have had their addresses taken, we're done.
  195. if (!AddrLabelSymbols) return;
  196. return AddrLabelSymbols->
  197. takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
  198. }
  199. /// \name Exception Handling
  200. /// \{
  201. void MachineModuleInfo::addPersonality(const Function *Personality) {
  202. for (unsigned i = 0; i < Personalities.size(); ++i)
  203. if (Personalities[i] == Personality)
  204. return;
  205. Personalities.push_back(Personality);
  206. }
  207. /// \}
  208. MachineFunction *
  209. MachineModuleInfo::getMachineFunction(const Function &F) const {
  210. auto I = MachineFunctions.find(&F);
  211. return I != MachineFunctions.end() ? I->second.get() : nullptr;
  212. }
  213. MachineFunction &
  214. MachineModuleInfo::getOrCreateMachineFunction(const Function &F) {
  215. // Shortcut for the common case where a sequence of MachineFunctionPasses
  216. // all query for the same Function.
  217. if (LastRequest == &F)
  218. return *LastResult;
  219. auto I = MachineFunctions.insert(
  220. std::make_pair(&F, std::unique_ptr<MachineFunction>()));
  221. MachineFunction *MF;
  222. if (I.second) {
  223. // No pre-existing machine function, create a new one.
  224. const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
  225. MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
  226. // Update the set entry.
  227. I.first->second.reset(MF);
  228. } else {
  229. MF = I.first->second.get();
  230. }
  231. LastRequest = &F;
  232. LastResult = MF;
  233. return *MF;
  234. }
  235. void MachineModuleInfo::deleteMachineFunctionFor(Function &F) {
  236. MachineFunctions.erase(&F);
  237. LastRequest = nullptr;
  238. LastResult = nullptr;
  239. }
  240. namespace {
  241. /// This pass frees the MachineFunction object associated with a Function.
  242. class FreeMachineFunction : public FunctionPass {
  243. public:
  244. static char ID;
  245. FreeMachineFunction() : FunctionPass(ID) {}
  246. void getAnalysisUsage(AnalysisUsage &AU) const override {
  247. AU.addRequired<MachineModuleInfo>();
  248. AU.addPreserved<MachineModuleInfo>();
  249. }
  250. bool runOnFunction(Function &F) override {
  251. MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
  252. MMI.deleteMachineFunctionFor(F);
  253. return true;
  254. }
  255. StringRef getPassName() const override {
  256. return "Free MachineFunction";
  257. }
  258. };
  259. } // end anonymous namespace
  260. char FreeMachineFunction::ID;
  261. FunctionPass *llvm::createFreeMachineFunctionPass() {
  262. return new FreeMachineFunction();
  263. }