EHStreamer.cpp 34 KB

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