MachineModuleInfo.cpp 11 KB

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