EHStreamer.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. //===- CodeGen/AsmPrinter/EHStreamer.cpp - Exception Directive Streamer ---===//
  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. // This file contains support for writing exception info into assembly files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "EHStreamer.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/ADT/Twine.h"
  15. #include "llvm/ADT/iterator_range.h"
  16. #include "llvm/BinaryFormat/Dwarf.h"
  17. #include "llvm/CodeGen/AsmPrinter.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineInstr.h"
  20. #include "llvm/CodeGen/MachineOperand.h"
  21. #include "llvm/IR/Function.h"
  22. #include "llvm/MC/MCAsmInfo.h"
  23. #include "llvm/MC/MCContext.h"
  24. #include "llvm/MC/MCStreamer.h"
  25. #include "llvm/MC/MCSymbol.h"
  26. #include "llvm/MC/MCTargetOptions.h"
  27. #include "llvm/Support/Casting.h"
  28. #include "llvm/Support/LEB128.h"
  29. #include "llvm/Target/TargetLoweringObjectFile.h"
  30. #include <algorithm>
  31. #include <cassert>
  32. #include <cstdint>
  33. #include <vector>
  34. using namespace llvm;
  35. EHStreamer::EHStreamer(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {}
  36. EHStreamer::~EHStreamer() = default;
  37. /// How many leading type ids two landing pads have in common.
  38. unsigned EHStreamer::sharedTypeIDs(const LandingPadInfo *L,
  39. const LandingPadInfo *R) {
  40. const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
  41. return std::mismatch(LIds.begin(), LIds.end(), RIds.begin(), RIds.end())
  42. .first -
  43. LIds.begin();
  44. }
  45. /// Compute the actions table and gather the first action index for each landing
  46. /// pad site.
  47. void EHStreamer::computeActionsTable(
  48. const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
  49. SmallVectorImpl<ActionEntry> &Actions,
  50. SmallVectorImpl<unsigned> &FirstActions) {
  51. // The action table follows the call-site table in the LSDA. The individual
  52. // records are of two types:
  53. //
  54. // * Catch clause
  55. // * Exception specification
  56. //
  57. // The two record kinds have the same format, with only small differences.
  58. // They are distinguished by the "switch value" field: Catch clauses
  59. // (TypeInfos) have strictly positive switch values, and exception
  60. // specifications (FilterIds) have strictly negative switch values. Value 0
  61. // indicates a catch-all clause.
  62. //
  63. // Negative type IDs index into FilterIds. Positive type IDs index into
  64. // TypeInfos. The value written for a positive type ID is just the type ID
  65. // itself. For a negative type ID, however, the value written is the
  66. // (negative) byte offset of the corresponding FilterIds entry. The byte
  67. // offset is usually equal to the type ID (because the FilterIds entries are
  68. // written using a variable width encoding, which outputs one byte per entry
  69. // as long as the value written is not too large) but can differ. This kind
  70. // of complication does not occur for positive type IDs because type infos are
  71. // output using a fixed width encoding. FilterOffsets[i] holds the byte
  72. // offset corresponding to FilterIds[i].
  73. const std::vector<unsigned> &FilterIds = Asm->MF->getFilterIds();
  74. SmallVector<int, 16> FilterOffsets;
  75. FilterOffsets.reserve(FilterIds.size());
  76. int Offset = -1;
  77. for (unsigned FilterId : FilterIds) {
  78. FilterOffsets.push_back(Offset);
  79. Offset -= getULEB128Size(FilterId);
  80. }
  81. FirstActions.reserve(LandingPads.size());
  82. int FirstAction = 0;
  83. unsigned SizeActions = 0; // Total size of all action entries for a function
  84. const LandingPadInfo *PrevLPI = nullptr;
  85. for (const LandingPadInfo *LPI : LandingPads) {
  86. const std::vector<int> &TypeIds = LPI->TypeIds;
  87. unsigned NumShared = PrevLPI ? sharedTypeIDs(LPI, PrevLPI) : 0;
  88. unsigned SizeSiteActions = 0; // Total size of all entries for a landingpad
  89. if (NumShared < TypeIds.size()) {
  90. // Size of one action entry (typeid + next action)
  91. unsigned SizeActionEntry = 0;
  92. unsigned PrevAction = (unsigned)-1;
  93. if (NumShared) {
  94. unsigned SizePrevIds = PrevLPI->TypeIds.size();
  95. assert(Actions.size());
  96. PrevAction = Actions.size() - 1;
  97. SizeActionEntry = getSLEB128Size(Actions[PrevAction].NextAction) +
  98. getSLEB128Size(Actions[PrevAction].ValueForTypeID);
  99. for (unsigned j = NumShared; j != SizePrevIds; ++j) {
  100. assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!");
  101. SizeActionEntry -= getSLEB128Size(Actions[PrevAction].ValueForTypeID);
  102. SizeActionEntry += -Actions[PrevAction].NextAction;
  103. PrevAction = Actions[PrevAction].Previous;
  104. }
  105. }
  106. // Compute the actions.
  107. for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) {
  108. int TypeID = TypeIds[J];
  109. assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
  110. int ValueForTypeID =
  111. isFilterEHSelector(TypeID) ? FilterOffsets[-1 - TypeID] : TypeID;
  112. unsigned SizeTypeID = getSLEB128Size(ValueForTypeID);
  113. int NextAction = SizeActionEntry ? -(SizeActionEntry + SizeTypeID) : 0;
  114. SizeActionEntry = SizeTypeID + getSLEB128Size(NextAction);
  115. SizeSiteActions += SizeActionEntry;
  116. ActionEntry Action = { ValueForTypeID, NextAction, PrevAction };
  117. Actions.push_back(Action);
  118. PrevAction = Actions.size() - 1;
  119. }
  120. // Record the first action of the landing pad site.
  121. FirstAction = SizeActions + SizeSiteActions - SizeActionEntry + 1;
  122. } // else identical - re-use previous FirstAction
  123. // Information used when creating the call-site table. The action record
  124. // field of the call site record is the offset of the first associated
  125. // action record, relative to the start of the actions table. This value is
  126. // biased by 1 (1 indicating the start of the actions table), and 0
  127. // indicates that there are no actions.
  128. FirstActions.push_back(FirstAction);
  129. // Compute this sites contribution to size.
  130. SizeActions += SizeSiteActions;
  131. PrevLPI = LPI;
  132. }
  133. }
  134. /// Return `true' if this is a call to a function marked `nounwind'. Return
  135. /// `false' otherwise.
  136. bool EHStreamer::callToNoUnwindFunction(const MachineInstr *MI) {
  137. assert(MI->isCall() && "This should be a call instruction!");
  138. bool MarkedNoUnwind = false;
  139. bool SawFunc = false;
  140. for (const MachineOperand &MO : MI->operands()) {
  141. if (!MO.isGlobal()) continue;
  142. const Function *F = dyn_cast<Function>(MO.getGlobal());
  143. if (!F) continue;
  144. if (SawFunc) {
  145. // Be conservative. If we have more than one function operand for this
  146. // call, then we can't make the assumption that it's the callee and
  147. // not a parameter to the call.
  148. //
  149. // FIXME: Determine if there's a way to say that `F' is the callee or
  150. // parameter.
  151. MarkedNoUnwind = false;
  152. break;
  153. }
  154. MarkedNoUnwind = F->doesNotThrow();
  155. SawFunc = true;
  156. }
  157. return MarkedNoUnwind;
  158. }
  159. void EHStreamer::computePadMap(
  160. const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
  161. RangeMapType &PadMap) {
  162. // Invokes and nounwind calls have entries in PadMap (due to being bracketed
  163. // by try-range labels when lowered). Ordinary calls do not, so appropriate
  164. // try-ranges for them need be deduced so we can put them in the LSDA.
  165. for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
  166. const LandingPadInfo *LandingPad = LandingPads[i];
  167. for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
  168. MCSymbol *BeginLabel = LandingPad->BeginLabels[j];
  169. MCSymbol *EndLabel = LandingPad->BeginLabels[j];
  170. // If we have deleted the code for a given invoke after registering it in
  171. // the LandingPad label list, the associated symbols will not have been
  172. // emitted. In that case, ignore this callsite entry.
  173. if (!BeginLabel->isDefined() || !EndLabel->isDefined())
  174. continue;
  175. assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
  176. PadRange P = { i, j };
  177. PadMap[BeginLabel] = P;
  178. }
  179. }
  180. }
  181. /// Compute the call-site table. The entry for an invoke has a try-range
  182. /// containing the call, a non-zero landing pad, and an appropriate action. The
  183. /// entry for an ordinary call has a try-range containing the call and zero for
  184. /// the landing pad and the action. Calls marked 'nounwind' have no entry and
  185. /// must not be contained in the try-range of any entry - they form gaps in the
  186. /// table. Entries must be ordered by try-range address.
  187. ///
  188. /// Call-sites are split into one or more call-site ranges associated with
  189. /// different sections of the function.
  190. ///
  191. /// - Without -basic-block-sections, all call-sites are grouped into one
  192. /// call-site-range corresponding to the function section.
  193. ///
  194. /// - With -basic-block-sections, one call-site range is created for each
  195. /// section, with its FragmentBeginLabel and FragmentEndLabel respectively
  196. // set to the beginning and ending of the corresponding section and its
  197. // ExceptionLabel set to the exception symbol dedicated for this section.
  198. // Later, one LSDA header will be emitted for each call-site range with its
  199. // call-sites following. The action table and type info table will be
  200. // shared across all ranges.
  201. void EHStreamer::computeCallSiteTable(
  202. SmallVectorImpl<CallSiteEntry> &CallSites,
  203. SmallVectorImpl<CallSiteRange> &CallSiteRanges,
  204. const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
  205. const SmallVectorImpl<unsigned> &FirstActions) {
  206. RangeMapType PadMap;
  207. computePadMap(LandingPads, PadMap);
  208. // The end label of the previous invoke or nounwind try-range.
  209. MCSymbol *LastLabel = Asm->getFunctionBegin();
  210. // Whether there is a potentially throwing instruction (currently this means
  211. // an ordinary call) between the end of the previous try-range and now.
  212. bool SawPotentiallyThrowing = false;
  213. // Whether the last CallSite entry was for an invoke.
  214. bool PreviousIsInvoke = false;
  215. bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
  216. // Visit all instructions in order of address.
  217. for (const auto &MBB : *Asm->MF) {
  218. if (&MBB == &Asm->MF->front() || MBB.isBeginSection()) {
  219. // We start a call-site range upon function entry and at the beginning of
  220. // every basic block section.
  221. CallSiteRanges.push_back(
  222. {Asm->MBBSectionRanges[MBB.getSectionIDNum()].BeginLabel,
  223. Asm->MBBSectionRanges[MBB.getSectionIDNum()].EndLabel,
  224. Asm->getMBBExceptionSym(MBB), CallSites.size()});
  225. PreviousIsInvoke = false;
  226. SawPotentiallyThrowing = false;
  227. LastLabel = nullptr;
  228. }
  229. if (MBB.isEHPad())
  230. CallSiteRanges.back().IsLPRange = true;
  231. for (const auto &MI : MBB) {
  232. if (!MI.isEHLabel()) {
  233. if (MI.isCall())
  234. SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
  235. continue;
  236. }
  237. // End of the previous try-range?
  238. MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
  239. if (BeginLabel == LastLabel)
  240. SawPotentiallyThrowing = false;
  241. // Beginning of a new try-range?
  242. RangeMapType::const_iterator L = PadMap.find(BeginLabel);
  243. if (L == PadMap.end())
  244. // Nope, it was just some random label.
  245. continue;
  246. const PadRange &P = L->second;
  247. const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
  248. assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
  249. "Inconsistent landing pad map!");
  250. // For Dwarf and AIX exception handling (SjLj handling doesn't use this).
  251. // If some instruction between the previous try-range and this one may
  252. // throw, create a call-site entry with no landing pad for the region
  253. // between the try-ranges.
  254. if (SawPotentiallyThrowing &&
  255. (Asm->MAI->usesCFIForEH() ||
  256. Asm->MAI->getExceptionHandlingType() == ExceptionHandling::AIX)) {
  257. CallSites.push_back({LastLabel, BeginLabel, nullptr, 0});
  258. PreviousIsInvoke = false;
  259. }
  260. LastLabel = LandingPad->EndLabels[P.RangeIndex];
  261. assert(BeginLabel && LastLabel && "Invalid landing pad!");
  262. if (!LandingPad->LandingPadLabel) {
  263. // Create a gap.
  264. PreviousIsInvoke = false;
  265. } else {
  266. // This try-range is for an invoke.
  267. CallSiteEntry Site = {
  268. BeginLabel,
  269. LastLabel,
  270. LandingPad,
  271. FirstActions[P.PadIndex]
  272. };
  273. // Try to merge with the previous call-site. SJLJ doesn't do this
  274. if (PreviousIsInvoke && !IsSJLJ) {
  275. CallSiteEntry &Prev = CallSites.back();
  276. if (Site.LPad == Prev.LPad && Site.Action == Prev.Action) {
  277. // Extend the range of the previous entry.
  278. Prev.EndLabel = Site.EndLabel;
  279. continue;
  280. }
  281. }
  282. // Otherwise, create a new call-site.
  283. if (!IsSJLJ)
  284. CallSites.push_back(Site);
  285. else {
  286. // SjLj EH must maintain the call sites in the order assigned
  287. // to them by the SjLjPrepare pass.
  288. unsigned SiteNo = Asm->MF->getCallSiteBeginLabel(BeginLabel);
  289. if (CallSites.size() < SiteNo)
  290. CallSites.resize(SiteNo);
  291. CallSites[SiteNo - 1] = Site;
  292. }
  293. PreviousIsInvoke = true;
  294. }
  295. }
  296. // We end the call-site range upon function exit and at the end of every
  297. // basic block section.
  298. if (&MBB == &Asm->MF->back() || MBB.isEndSection()) {
  299. // If some instruction between the previous try-range and the end of the
  300. // function may throw, create a call-site entry with no landing pad for
  301. // the region following the try-range.
  302. if (SawPotentiallyThrowing && !IsSJLJ) {
  303. CallSiteEntry Site = {LastLabel, CallSiteRanges.back().FragmentEndLabel,
  304. nullptr, 0};
  305. CallSites.push_back(Site);
  306. SawPotentiallyThrowing = false;
  307. }
  308. CallSiteRanges.back().CallSiteEndIdx = CallSites.size();
  309. }
  310. }
  311. }
  312. /// Emit landing pads and actions.
  313. ///
  314. /// The general organization of the table is complex, but the basic concepts are
  315. /// easy. First there is a header which describes the location and organization
  316. /// of the three components that follow.
  317. ///
  318. /// 1. The landing pad site information describes the range of code covered by
  319. /// the try. In our case it's an accumulation of the ranges covered by the
  320. /// invokes in the try. There is also a reference to the landing pad that
  321. /// handles the exception once processed. Finally an index into the actions
  322. /// table.
  323. /// 2. The action table, in our case, is composed of pairs of type IDs and next
  324. /// action offset. Starting with the action index from the landing pad
  325. /// site, each type ID is checked for a match to the current exception. If
  326. /// it matches then the exception and type id are passed on to the landing
  327. /// pad. Otherwise the next action is looked up. This chain is terminated
  328. /// with a next action of zero. If no type id is found then the frame is
  329. /// unwound and handling continues.
  330. /// 3. Type ID table contains references to all the C++ typeinfo for all
  331. /// catches in the function. This tables is reverse indexed base 1.
  332. ///
  333. /// Returns the starting symbol of an exception table.
  334. MCSymbol *EHStreamer::emitExceptionTable() {
  335. const MachineFunction *MF = Asm->MF;
  336. const std::vector<const GlobalValue *> &TypeInfos = MF->getTypeInfos();
  337. const std::vector<unsigned> &FilterIds = MF->getFilterIds();
  338. const std::vector<LandingPadInfo> &PadInfos = MF->getLandingPads();
  339. // Sort the landing pads in order of their type ids. This is used to fold
  340. // duplicate actions.
  341. SmallVector<const LandingPadInfo *, 64> LandingPads;
  342. LandingPads.reserve(PadInfos.size());
  343. for (const LandingPadInfo &LPI : PadInfos) {
  344. // If a landing-pad has an associated label, but the label wasn't ever
  345. // emitted, then skip it. (This can occur if the landingpad's MBB was
  346. // deleted).
  347. if (LPI.LandingPadLabel && !LPI.LandingPadLabel->isDefined())
  348. continue;
  349. LandingPads.push_back(&LPI);
  350. }
  351. // Order landing pads lexicographically by type id.
  352. llvm::sort(LandingPads, [](const LandingPadInfo *L, const LandingPadInfo *R) {
  353. return L->TypeIds < R->TypeIds;
  354. });
  355. // Compute the actions table and gather the first action index for each
  356. // landing pad site.
  357. SmallVector<ActionEntry, 32> Actions;
  358. SmallVector<unsigned, 64> FirstActions;
  359. computeActionsTable(LandingPads, Actions, FirstActions);
  360. // Compute the call-site table and call-site ranges. Normally, there is only
  361. // one call-site-range which covers the whole funciton. With
  362. // -basic-block-sections, there is one call-site-range per basic block
  363. // section.
  364. SmallVector<CallSiteEntry, 64> CallSites;
  365. SmallVector<CallSiteRange, 4> CallSiteRanges;
  366. computeCallSiteTable(CallSites, CallSiteRanges, LandingPads, FirstActions);
  367. bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj;
  368. bool IsWasm = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Wasm;
  369. bool HasLEB128Directives = Asm->MAI->hasLEB128Directives();
  370. unsigned CallSiteEncoding =
  371. IsSJLJ ? static_cast<unsigned>(dwarf::DW_EH_PE_udata4) :
  372. Asm->getObjFileLowering().getCallSiteEncoding();
  373. bool HaveTTData = !TypeInfos.empty() || !FilterIds.empty();
  374. // Type infos.
  375. MCSection *LSDASection = Asm->getObjFileLowering().getSectionForLSDA(
  376. MF->getFunction(), *Asm->CurrentFnSym, Asm->TM);
  377. unsigned TTypeEncoding;
  378. if (!HaveTTData) {
  379. // If there is no TypeInfo, then we just explicitly say that we're omitting
  380. // that bit.
  381. TTypeEncoding = dwarf::DW_EH_PE_omit;
  382. } else {
  383. // Okay, we have actual filters or typeinfos to emit. As such, we need to
  384. // pick a type encoding for them. We're about to emit a list of pointers to
  385. // typeinfo objects at the end of the LSDA. However, unless we're in static
  386. // mode, this reference will require a relocation by the dynamic linker.
  387. //
  388. // Because of this, we have a couple of options:
  389. //
  390. // 1) If we are in -static mode, we can always use an absolute reference
  391. // from the LSDA, because the static linker will resolve it.
  392. //
  393. // 2) Otherwise, if the LSDA section is writable, we can output the direct
  394. // reference to the typeinfo and allow the dynamic linker to relocate
  395. // it. Since it is in a writable section, the dynamic linker won't
  396. // have a problem.
  397. //
  398. // 3) Finally, if we're in PIC mode and the LDSA section isn't writable,
  399. // we need to use some form of indirection. For example, on Darwin,
  400. // we can output a statically-relocatable reference to a dyld stub. The
  401. // offset to the stub is constant, but the contents are in a section
  402. // that is updated by the dynamic linker. This is easy enough, but we
  403. // need to tell the personality function of the unwinder to indirect
  404. // through the dyld stub.
  405. //
  406. // FIXME: When (3) is actually implemented, we'll have to emit the stubs
  407. // somewhere. This predicate should be moved to a shared location that is
  408. // in target-independent code.
  409. //
  410. TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding();
  411. }
  412. // Begin the exception table.
  413. // Sometimes we want not to emit the data into separate section (e.g. ARM
  414. // EHABI). In this case LSDASection will be NULL.
  415. if (LSDASection)
  416. Asm->OutStreamer->switchSection(LSDASection);
  417. Asm->emitAlignment(Align(4));
  418. // Emit the LSDA.
  419. MCSymbol *GCCETSym =
  420. Asm->OutContext.getOrCreateSymbol(Twine("GCC_except_table")+
  421. Twine(Asm->getFunctionNumber()));
  422. Asm->OutStreamer->emitLabel(GCCETSym);
  423. MCSymbol *CstEndLabel = Asm->createTempSymbol(
  424. CallSiteRanges.size() > 1 ? "action_table_base" : "cst_end");
  425. MCSymbol *TTBaseLabel = nullptr;
  426. if (HaveTTData)
  427. TTBaseLabel = Asm->createTempSymbol("ttbase");
  428. const bool VerboseAsm = Asm->OutStreamer->isVerboseAsm();
  429. // Helper for emitting references (offsets) for type table and the end of the
  430. // call-site table (which marks the beginning of the action table).
  431. // * For Itanium, these references will be emitted for every callsite range.
  432. // * For SJLJ and Wasm, they will be emitted only once in the LSDA header.
  433. auto EmitTypeTableRefAndCallSiteTableEndRef = [&]() {
  434. Asm->emitEncodingByte(TTypeEncoding, "@TType");
  435. if (HaveTTData) {
  436. // N.B.: There is a dependency loop between the size of the TTBase uleb128
  437. // here and the amount of padding before the aligned type table. The
  438. // assembler must sometimes pad this uleb128 or insert extra padding
  439. // before the type table. See PR35809 or GNU as bug 4029.
  440. MCSymbol *TTBaseRefLabel = Asm->createTempSymbol("ttbaseref");
  441. Asm->emitLabelDifferenceAsULEB128(TTBaseLabel, TTBaseRefLabel);
  442. Asm->OutStreamer->emitLabel(TTBaseRefLabel);
  443. }
  444. // The Action table follows the call-site table. So we emit the
  445. // label difference from here (start of the call-site table for SJLJ and
  446. // Wasm, and start of a call-site range for Itanium) to the end of the
  447. // whole call-site table (end of the last call-site range for Itanium).
  448. MCSymbol *CstBeginLabel = Asm->createTempSymbol("cst_begin");
  449. Asm->emitEncodingByte(CallSiteEncoding, "Call site");
  450. Asm->emitLabelDifferenceAsULEB128(CstEndLabel, CstBeginLabel);
  451. Asm->OutStreamer->emitLabel(CstBeginLabel);
  452. };
  453. // An alternative path to EmitTypeTableRefAndCallSiteTableEndRef.
  454. // For some platforms, the system assembler does not accept the form of
  455. // `.uleb128 label2 - label1`. In those situations, we would need to calculate
  456. // the size between label1 and label2 manually.
  457. // In this case, we would need to calculate the LSDA size and the call
  458. // site table size.
  459. auto EmitTypeTableOffsetAndCallSiteTableOffset = [&]() {
  460. assert(CallSiteEncoding == dwarf::DW_EH_PE_udata4 && !HasLEB128Directives &&
  461. "Targets supporting .uleb128 do not need to take this path.");
  462. if (CallSiteRanges.size() > 1)
  463. report_fatal_error(
  464. "-fbasic-block-sections is not yet supported on "
  465. "platforms that do not have general LEB128 directive support.");
  466. uint64_t CallSiteTableSize = 0;
  467. const CallSiteRange &CSRange = CallSiteRanges.back();
  468. for (size_t CallSiteIdx = CSRange.CallSiteBeginIdx;
  469. CallSiteIdx < CSRange.CallSiteEndIdx; ++CallSiteIdx) {
  470. const CallSiteEntry &S = CallSites[CallSiteIdx];
  471. // Each call site entry consists of 3 udata4 fields (12 bytes) and
  472. // 1 ULEB128 field.
  473. CallSiteTableSize += 12 + getULEB128Size(S.Action);
  474. assert(isUInt<32>(CallSiteTableSize) && "CallSiteTableSize overflows.");
  475. }
  476. Asm->emitEncodingByte(TTypeEncoding, "@TType");
  477. if (HaveTTData) {
  478. const unsigned ByteSizeOfCallSiteOffset =
  479. getULEB128Size(CallSiteTableSize);
  480. uint64_t ActionTableSize = 0;
  481. for (const ActionEntry &Action : Actions) {
  482. // Each action entry consists of two SLEB128 fields.
  483. ActionTableSize += getSLEB128Size(Action.ValueForTypeID) +
  484. getSLEB128Size(Action.NextAction);
  485. assert(isUInt<32>(ActionTableSize) && "ActionTableSize overflows.");
  486. }
  487. const unsigned TypeInfoSize =
  488. Asm->GetSizeOfEncodedValue(TTypeEncoding) * MF->getTypeInfos().size();
  489. const uint64_t LSDASizeBeforeAlign =
  490. 1 // Call site encoding byte.
  491. + ByteSizeOfCallSiteOffset // ULEB128 encoding of CallSiteTableSize.
  492. + CallSiteTableSize // Call site table content.
  493. + ActionTableSize; // Action table content.
  494. const uint64_t LSDASizeWithoutAlign = LSDASizeBeforeAlign + TypeInfoSize;
  495. const unsigned ByteSizeOfLSDAWithoutAlign =
  496. getULEB128Size(LSDASizeWithoutAlign);
  497. const uint64_t DisplacementBeforeAlign =
  498. 2 // LPStartEncoding and TypeTableEncoding.
  499. + ByteSizeOfLSDAWithoutAlign + LSDASizeBeforeAlign;
  500. // The type info area starts with 4 byte alignment.
  501. const unsigned NeedAlignVal = (4 - DisplacementBeforeAlign % 4) % 4;
  502. uint64_t LSDASizeWithAlign = LSDASizeWithoutAlign + NeedAlignVal;
  503. const unsigned ByteSizeOfLSDAWithAlign =
  504. getULEB128Size(LSDASizeWithAlign);
  505. // The LSDASizeWithAlign could use 1 byte less padding for alignment
  506. // when the data we use to represent the LSDA Size "needs" to be 1 byte
  507. // larger than the one previously calculated without alignment.
  508. if (ByteSizeOfLSDAWithAlign > ByteSizeOfLSDAWithoutAlign)
  509. LSDASizeWithAlign -= 1;
  510. Asm->OutStreamer->emitULEB128IntValue(LSDASizeWithAlign,
  511. ByteSizeOfLSDAWithAlign);
  512. }
  513. Asm->emitEncodingByte(CallSiteEncoding, "Call site");
  514. Asm->OutStreamer->emitULEB128IntValue(CallSiteTableSize);
  515. };
  516. // SjLj / Wasm Exception handling
  517. if (IsSJLJ || IsWasm) {
  518. Asm->OutStreamer->emitLabel(Asm->getMBBExceptionSym(Asm->MF->front()));
  519. // emit the LSDA header.
  520. Asm->emitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
  521. EmitTypeTableRefAndCallSiteTableEndRef();
  522. unsigned idx = 0;
  523. for (SmallVectorImpl<CallSiteEntry>::const_iterator
  524. I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) {
  525. const CallSiteEntry &S = *I;
  526. // Index of the call site entry.
  527. if (VerboseAsm) {
  528. Asm->OutStreamer->AddComment(">> Call Site " + Twine(idx) + " <<");
  529. Asm->OutStreamer->AddComment(" On exception at call site "+Twine(idx));
  530. }
  531. Asm->emitULEB128(idx);
  532. // Offset of the first associated action record, relative to the start of
  533. // the action table. This value is biased by 1 (1 indicates the start of
  534. // the action table), and 0 indicates that there are no actions.
  535. if (VerboseAsm) {
  536. if (S.Action == 0)
  537. Asm->OutStreamer->AddComment(" Action: cleanup");
  538. else
  539. Asm->OutStreamer->AddComment(" Action: " +
  540. Twine((S.Action - 1) / 2 + 1));
  541. }
  542. Asm->emitULEB128(S.Action);
  543. }
  544. Asm->OutStreamer->emitLabel(CstEndLabel);
  545. } else {
  546. // Itanium LSDA exception handling
  547. // The call-site table is a list of all call sites that may throw an
  548. // exception (including C++ 'throw' statements) in the procedure
  549. // fragment. It immediately follows the LSDA header. Each entry indicates,
  550. // for a given call, the first corresponding action record and corresponding
  551. // landing pad.
  552. //
  553. // The table begins with the number of bytes, stored as an LEB128
  554. // compressed, unsigned integer. The records immediately follow the record
  555. // count. They are sorted in increasing call-site address. Each record
  556. // indicates:
  557. //
  558. // * The position of the call-site.
  559. // * The position of the landing pad.
  560. // * The first action record for that call site.
  561. //
  562. // A missing entry in the call-site table indicates that a call is not
  563. // supposed to throw.
  564. assert(CallSiteRanges.size() != 0 && "No call-site ranges!");
  565. // There should be only one call-site range which includes all the landing
  566. // pads. Find that call-site range here.
  567. const CallSiteRange *LandingPadRange = nullptr;
  568. for (const CallSiteRange &CSRange : CallSiteRanges) {
  569. if (CSRange.IsLPRange) {
  570. assert(LandingPadRange == nullptr &&
  571. "All landing pads must be in a single callsite range.");
  572. LandingPadRange = &CSRange;
  573. }
  574. }
  575. // The call-site table is split into its call-site ranges, each being
  576. // emitted as:
  577. // [ LPStartEncoding | LPStart ]
  578. // [ TypeTableEncoding | TypeTableOffset ]
  579. // [ CallSiteEncoding | CallSiteTableEndOffset ]
  580. // cst_begin -> { call-site entries contained in this range }
  581. //
  582. // and is followed by the next call-site range.
  583. //
  584. // For each call-site range, CallSiteTableEndOffset is computed as the
  585. // difference between cst_begin of that range and the last call-site-table's
  586. // end label. This offset is used to find the action table.
  587. unsigned Entry = 0;
  588. for (const CallSiteRange &CSRange : CallSiteRanges) {
  589. if (CSRange.CallSiteBeginIdx != 0) {
  590. // Align the call-site range for all ranges except the first. The
  591. // first range is already aligned due to the exception table alignment.
  592. Asm->emitAlignment(Align(4));
  593. }
  594. Asm->OutStreamer->emitLabel(CSRange.ExceptionLabel);
  595. // Emit the LSDA header.
  596. // LPStart is omitted if either we have a single call-site range (in which
  597. // case the function entry is treated as @LPStart) or if this function has
  598. // no landing pads (in which case @LPStart is undefined).
  599. if (CallSiteRanges.size() == 1 || LandingPadRange == nullptr) {
  600. Asm->emitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart");
  601. } else if (!Asm->isPositionIndependent()) {
  602. // For more than one call-site ranges, LPStart must be explicitly
  603. // specified.
  604. // For non-PIC we can simply use the absolute value.
  605. Asm->emitEncodingByte(dwarf::DW_EH_PE_absptr, "@LPStart");
  606. Asm->OutStreamer->emitSymbolValue(LandingPadRange->FragmentBeginLabel,
  607. Asm->MAI->getCodePointerSize());
  608. } else {
  609. // For PIC mode, we Emit a PC-relative address for LPStart.
  610. Asm->emitEncodingByte(dwarf::DW_EH_PE_pcrel, "@LPStart");
  611. MCContext &Context = Asm->OutStreamer->getContext();
  612. MCSymbol *Dot = Context.createTempSymbol();
  613. Asm->OutStreamer->emitLabel(Dot);
  614. Asm->OutStreamer->emitValue(
  615. MCBinaryExpr::createSub(
  616. MCSymbolRefExpr::create(LandingPadRange->FragmentBeginLabel,
  617. Context),
  618. MCSymbolRefExpr::create(Dot, Context), Context),
  619. Asm->MAI->getCodePointerSize());
  620. }
  621. if (HasLEB128Directives)
  622. EmitTypeTableRefAndCallSiteTableEndRef();
  623. else
  624. EmitTypeTableOffsetAndCallSiteTableOffset();
  625. for (size_t CallSiteIdx = CSRange.CallSiteBeginIdx;
  626. CallSiteIdx != CSRange.CallSiteEndIdx; ++CallSiteIdx) {
  627. const CallSiteEntry &S = CallSites[CallSiteIdx];
  628. MCSymbol *EHFuncBeginSym = CSRange.FragmentBeginLabel;
  629. MCSymbol *EHFuncEndSym = CSRange.FragmentEndLabel;
  630. MCSymbol *BeginLabel = S.BeginLabel;
  631. if (!BeginLabel)
  632. BeginLabel = EHFuncBeginSym;
  633. MCSymbol *EndLabel = S.EndLabel;
  634. if (!EndLabel)
  635. EndLabel = EHFuncEndSym;
  636. // Offset of the call site relative to the start of the procedure.
  637. if (VerboseAsm)
  638. Asm->OutStreamer->AddComment(">> Call Site " + Twine(++Entry) +
  639. " <<");
  640. Asm->emitCallSiteOffset(BeginLabel, EHFuncBeginSym, CallSiteEncoding);
  641. if (VerboseAsm)
  642. Asm->OutStreamer->AddComment(Twine(" Call between ") +
  643. BeginLabel->getName() + " and " +
  644. EndLabel->getName());
  645. Asm->emitCallSiteOffset(EndLabel, BeginLabel, CallSiteEncoding);
  646. // Offset of the landing pad relative to the start of the landing pad
  647. // fragment.
  648. if (!S.LPad) {
  649. if (VerboseAsm)
  650. Asm->OutStreamer->AddComment(" has no landing pad");
  651. Asm->emitCallSiteValue(0, CallSiteEncoding);
  652. } else {
  653. if (VerboseAsm)
  654. Asm->OutStreamer->AddComment(Twine(" jumps to ") +
  655. S.LPad->LandingPadLabel->getName());
  656. Asm->emitCallSiteOffset(S.LPad->LandingPadLabel,
  657. LandingPadRange->FragmentBeginLabel,
  658. CallSiteEncoding);
  659. }
  660. // Offset of the first associated action record, relative to the start
  661. // of the action table. This value is biased by 1 (1 indicates the start
  662. // of the action table), and 0 indicates that there are no actions.
  663. if (VerboseAsm) {
  664. if (S.Action == 0)
  665. Asm->OutStreamer->AddComment(" On action: cleanup");
  666. else
  667. Asm->OutStreamer->AddComment(" On action: " +
  668. Twine((S.Action - 1) / 2 + 1));
  669. }
  670. Asm->emitULEB128(S.Action);
  671. }
  672. }
  673. Asm->OutStreamer->emitLabel(CstEndLabel);
  674. }
  675. // Emit the Action Table.
  676. int Entry = 0;
  677. for (const ActionEntry &Action : Actions) {
  678. if (VerboseAsm) {
  679. // Emit comments that decode the action table.
  680. Asm->OutStreamer->AddComment(">> Action Record " + Twine(++Entry) + " <<");
  681. }
  682. // Type Filter
  683. //
  684. // Used by the runtime to match the type of the thrown exception to the
  685. // type of the catch clauses or the types in the exception specification.
  686. if (VerboseAsm) {
  687. if (Action.ValueForTypeID > 0)
  688. Asm->OutStreamer->AddComment(" Catch TypeInfo " +
  689. Twine(Action.ValueForTypeID));
  690. else if (Action.ValueForTypeID < 0)
  691. Asm->OutStreamer->AddComment(" Filter TypeInfo " +
  692. Twine(Action.ValueForTypeID));
  693. else
  694. Asm->OutStreamer->AddComment(" Cleanup");
  695. }
  696. Asm->emitSLEB128(Action.ValueForTypeID);
  697. // Action Record
  698. if (VerboseAsm) {
  699. if (Action.Previous == unsigned(-1)) {
  700. Asm->OutStreamer->AddComment(" No further actions");
  701. } else {
  702. Asm->OutStreamer->AddComment(" Continue to action " +
  703. Twine(Action.Previous + 1));
  704. }
  705. }
  706. Asm->emitSLEB128(Action.NextAction);
  707. }
  708. if (HaveTTData) {
  709. Asm->emitAlignment(Align(4));
  710. emitTypeInfos(TTypeEncoding, TTBaseLabel);
  711. }
  712. Asm->emitAlignment(Align(4));
  713. return GCCETSym;
  714. }
  715. void EHStreamer::emitTypeInfos(unsigned TTypeEncoding, MCSymbol *TTBaseLabel) {
  716. const MachineFunction *MF = Asm->MF;
  717. const std::vector<const GlobalValue *> &TypeInfos = MF->getTypeInfos();
  718. const std::vector<unsigned> &FilterIds = MF->getFilterIds();
  719. const bool VerboseAsm = Asm->OutStreamer->isVerboseAsm();
  720. int Entry = 0;
  721. // Emit the Catch TypeInfos.
  722. if (VerboseAsm && !TypeInfos.empty()) {
  723. Asm->OutStreamer->AddComment(">> Catch TypeInfos <<");
  724. Asm->OutStreamer->addBlankLine();
  725. Entry = TypeInfos.size();
  726. }
  727. for (const GlobalValue *GV : llvm::reverse(TypeInfos)) {
  728. if (VerboseAsm)
  729. Asm->OutStreamer->AddComment("TypeInfo " + Twine(Entry--));
  730. Asm->emitTTypeReference(GV, TTypeEncoding);
  731. }
  732. Asm->OutStreamer->emitLabel(TTBaseLabel);
  733. // Emit the Exception Specifications.
  734. if (VerboseAsm && !FilterIds.empty()) {
  735. Asm->OutStreamer->AddComment(">> Filter TypeInfos <<");
  736. Asm->OutStreamer->addBlankLine();
  737. Entry = 0;
  738. }
  739. for (std::vector<unsigned>::const_iterator
  740. I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) {
  741. unsigned TypeID = *I;
  742. if (VerboseAsm) {
  743. --Entry;
  744. if (isFilterEHSelector(TypeID))
  745. Asm->OutStreamer->AddComment("FilterInfo " + Twine(Entry));
  746. }
  747. Asm->emitULEB128(TypeID);
  748. }
  749. }