WinException.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains support for writing Win64 exception info into asm files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "WinException.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/ADT/Twine.h"
  16. #include "llvm/CodeGen/AsmPrinter.h"
  17. #include "llvm/CodeGen/MachineFrameInfo.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineModuleInfo.h"
  20. #include "llvm/CodeGen/WinEHFuncInfo.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/Mangler.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/MC/MCAsmInfo.h"
  25. #include "llvm/MC/MCContext.h"
  26. #include "llvm/MC/MCExpr.h"
  27. #include "llvm/MC/MCSection.h"
  28. #include "llvm/MC/MCStreamer.h"
  29. #include "llvm/MC/MCSymbol.h"
  30. #include "llvm/MC/MCWin64EH.h"
  31. #include "llvm/Support/COFF.h"
  32. #include "llvm/Support/Dwarf.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/FormattedStream.h"
  35. #include "llvm/Target/TargetFrameLowering.h"
  36. #include "llvm/Target/TargetLowering.h"
  37. #include "llvm/Target/TargetLoweringObjectFile.h"
  38. #include "llvm/Target/TargetOptions.h"
  39. #include "llvm/Target/TargetRegisterInfo.h"
  40. #include "llvm/Target/TargetSubtargetInfo.h"
  41. using namespace llvm;
  42. WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
  43. // MSVC's EH tables are always composed of 32-bit words. All known 64-bit
  44. // platforms use an imagerel32 relocation to refer to symbols.
  45. useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
  46. }
  47. WinException::~WinException() {}
  48. /// endModule - Emit all exception information that should come after the
  49. /// content.
  50. void WinException::endModule() {
  51. auto &OS = *Asm->OutStreamer;
  52. const Module *M = MMI->getModule();
  53. for (const Function &F : *M)
  54. if (F.hasFnAttribute("safeseh"))
  55. OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
  56. }
  57. void WinException::beginFunction(const MachineFunction *MF) {
  58. shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
  59. // If any landing pads survive, we need an EH table.
  60. bool hasLandingPads = !MMI->getLandingPads().empty();
  61. bool hasEHFunclets = MMI->hasEHFunclets();
  62. const Function *F = MF->getFunction();
  63. shouldEmitMoves = Asm->needsSEHMoves();
  64. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  65. unsigned PerEncoding = TLOF.getPersonalityEncoding();
  66. EHPersonality Per = EHPersonality::Unknown;
  67. const Function *PerFn = nullptr;
  68. if (F->hasPersonalityFn()) {
  69. PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
  70. Per = classifyEHPersonality(PerFn);
  71. }
  72. bool forceEmitPersonality = F->hasPersonalityFn() &&
  73. !isNoOpWithoutInvoke(Per) &&
  74. F->needsUnwindTableEntry();
  75. shouldEmitPersonality =
  76. forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
  77. PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
  78. unsigned LSDAEncoding = TLOF.getLSDAEncoding();
  79. shouldEmitLSDA = shouldEmitPersonality &&
  80. LSDAEncoding != dwarf::DW_EH_PE_omit;
  81. // If we're not using CFI, we don't want the CFI or the personality, but we
  82. // might want EH tables if we had EH pads.
  83. if (!Asm->MAI->usesWindowsCFI() || (!MF->hasWinCFI() && !PerFn)) {
  84. if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
  85. // If this is 32-bit SEH and we don't have any funclets (really invokes),
  86. // make sure we emit the parent offset label. Some unreferenced filter
  87. // functions may still refer to it.
  88. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  89. StringRef FLinkageName =
  90. GlobalValue::getRealLinkageName(MF->getFunction()->getName());
  91. emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
  92. }
  93. shouldEmitLSDA = hasEHFunclets;
  94. shouldEmitPersonality = false;
  95. return;
  96. }
  97. beginFunclet(MF->front(), Asm->CurrentFnSym);
  98. }
  99. /// endFunction - Gather and emit post-function exception information.
  100. ///
  101. void WinException::endFunction(const MachineFunction *MF) {
  102. if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
  103. return;
  104. const Function *F = MF->getFunction();
  105. EHPersonality Per = EHPersonality::Unknown;
  106. if (F->hasPersonalityFn())
  107. Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
  108. // Get rid of any dead landing pads if we're not using funclets. In funclet
  109. // schemes, the landing pad is not actually reachable. It only exists so
  110. // that we can emit the right table data.
  111. if (!isFuncletEHPersonality(Per))
  112. MMI->TidyLandingPads();
  113. endFunclet();
  114. // endFunclet will emit the necessary .xdata tables for x64 SEH.
  115. if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
  116. return;
  117. if (shouldEmitPersonality || shouldEmitLSDA) {
  118. Asm->OutStreamer->PushSection();
  119. // Just switch sections to the right xdata section.
  120. MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
  121. Asm->OutStreamer->getCurrentSectionOnly());
  122. Asm->OutStreamer->SwitchSection(XData);
  123. // Emit the tables appropriate to the personality function in use. If we
  124. // don't recognize the personality, assume it uses an Itanium-style LSDA.
  125. if (Per == EHPersonality::MSVC_Win64SEH)
  126. emitCSpecificHandlerTable(MF);
  127. else if (Per == EHPersonality::MSVC_X86SEH)
  128. emitExceptHandlerTable(MF);
  129. else if (Per == EHPersonality::MSVC_CXX)
  130. emitCXXFrameHandler3Table(MF);
  131. else if (Per == EHPersonality::CoreCLR)
  132. emitCLRExceptionTable(MF);
  133. else
  134. emitExceptionTable();
  135. Asm->OutStreamer->PopSection();
  136. }
  137. }
  138. /// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
  139. static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
  140. const MachineBasicBlock *MBB) {
  141. if (!MBB)
  142. return nullptr;
  143. assert(MBB->isEHFuncletEntry());
  144. // Give catches and cleanups a name based off of their parent function and
  145. // their funclet entry block's number.
  146. const MachineFunction *MF = MBB->getParent();
  147. const Function *F = MF->getFunction();
  148. StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
  149. MCContext &Ctx = MF->getContext();
  150. StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
  151. return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
  152. Twine(MBB->getNumber()) + "@?0?" +
  153. FuncLinkageName + "@4HA");
  154. }
  155. void WinException::beginFunclet(const MachineBasicBlock &MBB,
  156. MCSymbol *Sym) {
  157. CurrentFuncletEntry = &MBB;
  158. const Function *F = Asm->MF->getFunction();
  159. // If a symbol was not provided for the funclet, invent one.
  160. if (!Sym) {
  161. Sym = getMCSymbolForMBB(Asm, &MBB);
  162. // Describe our funclet symbol as a function with internal linkage.
  163. Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
  164. Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
  165. Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
  166. << COFF::SCT_COMPLEX_TYPE_SHIFT);
  167. Asm->OutStreamer->EndCOFFSymbolDef();
  168. // We want our funclet's entry point to be aligned such that no nops will be
  169. // present after the label.
  170. Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
  171. F);
  172. // Now that we've emitted the alignment directive, point at our funclet.
  173. Asm->OutStreamer->EmitLabel(Sym);
  174. }
  175. // Mark 'Sym' as starting our funclet.
  176. if (shouldEmitMoves || shouldEmitPersonality)
  177. Asm->OutStreamer->EmitWinCFIStartProc(Sym);
  178. if (shouldEmitPersonality) {
  179. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
  180. const Function *PerFn = nullptr;
  181. // Determine which personality routine we are using for this funclet.
  182. if (F->hasPersonalityFn())
  183. PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
  184. const MCSymbol *PersHandlerSym =
  185. TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
  186. // Classify the personality routine so that we may reason about it.
  187. EHPersonality Per = classifyEHPersonality(PerFn);
  188. // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
  189. if (Per != EHPersonality::MSVC_CXX ||
  190. !CurrentFuncletEntry->isCleanupFuncletEntry())
  191. Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
  192. }
  193. }
  194. void WinException::endFunclet() {
  195. // No funclet to process? Great, we have nothing to do.
  196. if (!CurrentFuncletEntry)
  197. return;
  198. if (shouldEmitMoves || shouldEmitPersonality) {
  199. const Function *F = Asm->MF->getFunction();
  200. EHPersonality Per = EHPersonality::Unknown;
  201. if (F->hasPersonalityFn())
  202. Per = classifyEHPersonality(F->getPersonalityFn()->stripPointerCasts());
  203. // The .seh_handlerdata directive implicitly switches section, push the
  204. // current section so that we may return to it.
  205. Asm->OutStreamer->PushSection();
  206. // Emit an UNWIND_INFO struct describing the prologue.
  207. Asm->OutStreamer->EmitWinEHHandlerData();
  208. if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
  209. !CurrentFuncletEntry->isCleanupFuncletEntry()) {
  210. // If this is a C++ catch funclet (or the parent function),
  211. // emit a reference to the LSDA for the parent function.
  212. StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
  213. MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
  214. Twine("$cppxdata$", FuncLinkageName));
  215. Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
  216. } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
  217. !CurrentFuncletEntry->isEHFuncletEntry()) {
  218. // If this is the parent function in Win64 SEH, emit the LSDA immediately
  219. // following .seh_handlerdata.
  220. emitCSpecificHandlerTable(Asm->MF);
  221. }
  222. // Switch back to the previous section now that we are done writing to
  223. // .xdata.
  224. Asm->OutStreamer->PopSection();
  225. // Emit a .seh_endproc directive to mark the end of the function.
  226. Asm->OutStreamer->EmitWinCFIEndProc();
  227. }
  228. // Let's make sure we don't try to end the same funclet twice.
  229. CurrentFuncletEntry = nullptr;
  230. }
  231. const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
  232. if (!Value)
  233. return MCConstantExpr::create(0, Asm->OutContext);
  234. return MCSymbolRefExpr::create(Value, useImageRel32
  235. ? MCSymbolRefExpr::VK_COFF_IMGREL32
  236. : MCSymbolRefExpr::VK_None,
  237. Asm->OutContext);
  238. }
  239. const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
  240. if (!GV)
  241. return MCConstantExpr::create(0, Asm->OutContext);
  242. return create32bitRef(Asm->getSymbol(GV));
  243. }
  244. const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
  245. return MCBinaryExpr::createAdd(create32bitRef(Label),
  246. MCConstantExpr::create(1, Asm->OutContext),
  247. Asm->OutContext);
  248. }
  249. const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
  250. const MCSymbol *OffsetFrom) {
  251. return MCBinaryExpr::createSub(
  252. MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
  253. MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
  254. }
  255. const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
  256. const MCSymbol *OffsetFrom) {
  257. return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
  258. MCConstantExpr::create(1, Asm->OutContext),
  259. Asm->OutContext);
  260. }
  261. int WinException::getFrameIndexOffset(int FrameIndex,
  262. const WinEHFuncInfo &FuncInfo) {
  263. const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
  264. unsigned UnusedReg;
  265. if (Asm->MAI->usesWindowsCFI()) {
  266. int Offset =
  267. TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
  268. /*IgnoreSPUpdates*/ true);
  269. assert(UnusedReg ==
  270. Asm->MF->getSubtarget()
  271. .getTargetLowering()
  272. ->getStackPointerRegisterToSaveRestore());
  273. return Offset;
  274. }
  275. // For 32-bit, offsets should be relative to the end of the EH registration
  276. // node. For 64-bit, it's relative to SP at the end of the prologue.
  277. assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
  278. int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
  279. Offset += FuncInfo.EHRegNodeEndOffset;
  280. return Offset;
  281. }
  282. namespace {
  283. /// Top-level state used to represent unwind to caller
  284. const int NullState = -1;
  285. struct InvokeStateChange {
  286. /// EH Label immediately after the last invoke in the previous state, or
  287. /// nullptr if the previous state was the null state.
  288. const MCSymbol *PreviousEndLabel;
  289. /// EH label immediately before the first invoke in the new state, or nullptr
  290. /// if the new state is the null state.
  291. const MCSymbol *NewStartLabel;
  292. /// State of the invoke following NewStartLabel, or NullState to indicate
  293. /// the presence of calls which may unwind to caller.
  294. int NewState;
  295. };
  296. /// Iterator that reports all the invoke state changes in a range of machine
  297. /// basic blocks. Changes to the null state are reported whenever a call that
  298. /// may unwind to caller is encountered. The MBB range is expected to be an
  299. /// entire function or funclet, and the start and end of the range are treated
  300. /// as being in the NullState even if there's not an unwind-to-caller call
  301. /// before the first invoke or after the last one (i.e., the first state change
  302. /// reported is the first change to something other than NullState, and a
  303. /// change back to NullState is always reported at the end of iteration).
  304. class InvokeStateChangeIterator {
  305. InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
  306. MachineFunction::const_iterator MFI,
  307. MachineFunction::const_iterator MFE,
  308. MachineBasicBlock::const_iterator MBBI,
  309. int BaseState)
  310. : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
  311. LastStateChange.PreviousEndLabel = nullptr;
  312. LastStateChange.NewStartLabel = nullptr;
  313. LastStateChange.NewState = BaseState;
  314. scan();
  315. }
  316. public:
  317. static iterator_range<InvokeStateChangeIterator>
  318. range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
  319. MachineFunction::const_iterator End, int BaseState = NullState) {
  320. // Reject empty ranges to simplify bookkeeping by ensuring that we can get
  321. // the end of the last block.
  322. assert(Begin != End);
  323. auto BlockBegin = Begin->begin();
  324. auto BlockEnd = std::prev(End)->end();
  325. return make_range(
  326. InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
  327. InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
  328. }
  329. // Iterator methods.
  330. bool operator==(const InvokeStateChangeIterator &O) const {
  331. assert(BaseState == O.BaseState);
  332. // Must be visiting same block.
  333. if (MFI != O.MFI)
  334. return false;
  335. // Must be visiting same isntr.
  336. if (MBBI != O.MBBI)
  337. return false;
  338. // At end of block/instr iteration, we can still have two distinct states:
  339. // one to report the final EndLabel, and another indicating the end of the
  340. // state change iteration. Check for CurrentEndLabel equality to
  341. // distinguish these.
  342. return CurrentEndLabel == O.CurrentEndLabel;
  343. }
  344. bool operator!=(const InvokeStateChangeIterator &O) const {
  345. return !operator==(O);
  346. }
  347. InvokeStateChange &operator*() { return LastStateChange; }
  348. InvokeStateChange *operator->() { return &LastStateChange; }
  349. InvokeStateChangeIterator &operator++() { return scan(); }
  350. private:
  351. InvokeStateChangeIterator &scan();
  352. const WinEHFuncInfo &EHInfo;
  353. const MCSymbol *CurrentEndLabel = nullptr;
  354. MachineFunction::const_iterator MFI;
  355. MachineFunction::const_iterator MFE;
  356. MachineBasicBlock::const_iterator MBBI;
  357. InvokeStateChange LastStateChange;
  358. bool VisitingInvoke = false;
  359. int BaseState;
  360. };
  361. } // end anonymous namespace
  362. InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
  363. bool IsNewBlock = false;
  364. for (; MFI != MFE; ++MFI, IsNewBlock = true) {
  365. if (IsNewBlock)
  366. MBBI = MFI->begin();
  367. for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
  368. const MachineInstr &MI = *MBBI;
  369. if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
  370. MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
  371. // Indicate a change of state to the null state. We don't have
  372. // start/end EH labels handy but the caller won't expect them for
  373. // null state regions.
  374. LastStateChange.PreviousEndLabel = CurrentEndLabel;
  375. LastStateChange.NewStartLabel = nullptr;
  376. LastStateChange.NewState = BaseState;
  377. CurrentEndLabel = nullptr;
  378. // Don't re-visit this instr on the next scan
  379. ++MBBI;
  380. return *this;
  381. }
  382. // All other state changes are at EH labels before/after invokes.
  383. if (!MI.isEHLabel())
  384. continue;
  385. MCSymbol *Label = MI.getOperand(0).getMCSymbol();
  386. if (Label == CurrentEndLabel) {
  387. VisitingInvoke = false;
  388. continue;
  389. }
  390. auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
  391. // Ignore EH labels that aren't the ones inserted before an invoke
  392. if (InvokeMapIter == EHInfo.LabelToStateMap.end())
  393. continue;
  394. auto &StateAndEnd = InvokeMapIter->second;
  395. int NewState = StateAndEnd.first;
  396. // Keep track of the fact that we're between EH start/end labels so
  397. // we know not to treat the inoke we'll see as unwinding to caller.
  398. VisitingInvoke = true;
  399. if (NewState == LastStateChange.NewState) {
  400. // The state isn't actually changing here. Record the new end and
  401. // keep going.
  402. CurrentEndLabel = StateAndEnd.second;
  403. continue;
  404. }
  405. // Found a state change to report
  406. LastStateChange.PreviousEndLabel = CurrentEndLabel;
  407. LastStateChange.NewStartLabel = Label;
  408. LastStateChange.NewState = NewState;
  409. // Start keeping track of the new current end
  410. CurrentEndLabel = StateAndEnd.second;
  411. // Don't re-visit this instr on the next scan
  412. ++MBBI;
  413. return *this;
  414. }
  415. }
  416. // Iteration hit the end of the block range.
  417. if (LastStateChange.NewState != BaseState) {
  418. // Report the end of the last new state
  419. LastStateChange.PreviousEndLabel = CurrentEndLabel;
  420. LastStateChange.NewStartLabel = nullptr;
  421. LastStateChange.NewState = BaseState;
  422. // Leave CurrentEndLabel non-null to distinguish this state from end.
  423. assert(CurrentEndLabel != nullptr);
  424. return *this;
  425. }
  426. // We've reported all state changes and hit the end state.
  427. CurrentEndLabel = nullptr;
  428. return *this;
  429. }
  430. /// Emit the language-specific data that __C_specific_handler expects. This
  431. /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
  432. /// up after faults with __try, __except, and __finally. The typeinfo values
  433. /// are not really RTTI data, but pointers to filter functions that return an
  434. /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
  435. /// blocks and other cleanups, the landing pad label is zero, and the filter
  436. /// function is actually a cleanup handler with the same prototype. A catch-all
  437. /// entry is modeled with a null filter function field and a non-zero landing
  438. /// pad label.
  439. ///
  440. /// Possible filter function return values:
  441. /// EXCEPTION_EXECUTE_HANDLER (1):
  442. /// Jump to the landing pad label after cleanups.
  443. /// EXCEPTION_CONTINUE_SEARCH (0):
  444. /// Continue searching this table or continue unwinding.
  445. /// EXCEPTION_CONTINUE_EXECUTION (-1):
  446. /// Resume execution at the trapping PC.
  447. ///
  448. /// Inferred table structure:
  449. /// struct Table {
  450. /// int NumEntries;
  451. /// struct Entry {
  452. /// imagerel32 LabelStart;
  453. /// imagerel32 LabelEnd;
  454. /// imagerel32 FilterOrFinally; // One means catch-all.
  455. /// imagerel32 LabelLPad; // Zero means __finally.
  456. /// } Entries[NumEntries];
  457. /// };
  458. void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
  459. auto &OS = *Asm->OutStreamer;
  460. MCContext &Ctx = Asm->OutContext;
  461. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  462. bool VerboseAsm = OS.isVerboseAsm();
  463. auto AddComment = [&](const Twine &Comment) {
  464. if (VerboseAsm)
  465. OS.AddComment(Comment);
  466. };
  467. // Emit a label assignment with the SEH frame offset so we can use it for
  468. // llvm.x86.seh.recoverfp.
  469. StringRef FLinkageName =
  470. GlobalValue::getRealLinkageName(MF->getFunction()->getName());
  471. MCSymbol *ParentFrameOffset =
  472. Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
  473. const MCExpr *MCOffset =
  474. MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
  475. Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
  476. // Use the assembler to compute the number of table entries through label
  477. // difference and division.
  478. MCSymbol *TableBegin =
  479. Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
  480. MCSymbol *TableEnd =
  481. Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
  482. const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
  483. const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
  484. const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
  485. AddComment("Number of call sites");
  486. OS.EmitValue(EntryCount, 4);
  487. OS.EmitLabel(TableBegin);
  488. // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
  489. // models exceptions from invokes. LLVM also allows arbitrary reordering of
  490. // the code, so our tables end up looking a bit different. Rather than
  491. // trying to match MSVC's tables exactly, we emit a denormalized table. For
  492. // each range of invokes in the same state, we emit table entries for all
  493. // the actions that would be taken in that state. This means our tables are
  494. // slightly bigger, which is OK.
  495. const MCSymbol *LastStartLabel = nullptr;
  496. int LastEHState = -1;
  497. // Break out before we enter into a finally funclet.
  498. // FIXME: We need to emit separate EH tables for cleanups.
  499. MachineFunction::const_iterator End = MF->end();
  500. MachineFunction::const_iterator Stop = std::next(MF->begin());
  501. while (Stop != End && !Stop->isEHFuncletEntry())
  502. ++Stop;
  503. for (const auto &StateChange :
  504. InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
  505. // Emit all the actions for the state we just transitioned out of
  506. // if it was not the null state
  507. if (LastEHState != -1)
  508. emitSEHActionsForRange(FuncInfo, LastStartLabel,
  509. StateChange.PreviousEndLabel, LastEHState);
  510. LastStartLabel = StateChange.NewStartLabel;
  511. LastEHState = StateChange.NewState;
  512. }
  513. OS.EmitLabel(TableEnd);
  514. }
  515. void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
  516. const MCSymbol *BeginLabel,
  517. const MCSymbol *EndLabel, int State) {
  518. auto &OS = *Asm->OutStreamer;
  519. MCContext &Ctx = Asm->OutContext;
  520. bool VerboseAsm = OS.isVerboseAsm();
  521. auto AddComment = [&](const Twine &Comment) {
  522. if (VerboseAsm)
  523. OS.AddComment(Comment);
  524. };
  525. assert(BeginLabel && EndLabel);
  526. while (State != -1) {
  527. const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
  528. const MCExpr *FilterOrFinally;
  529. const MCExpr *ExceptOrNull;
  530. auto *Handler = UME.Handler.get<MachineBasicBlock *>();
  531. if (UME.IsFinally) {
  532. FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
  533. ExceptOrNull = MCConstantExpr::create(0, Ctx);
  534. } else {
  535. // For an except, the filter can be 1 (catch-all) or a function
  536. // label.
  537. FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
  538. : MCConstantExpr::create(1, Ctx);
  539. ExceptOrNull = create32bitRef(Handler->getSymbol());
  540. }
  541. AddComment("LabelStart");
  542. OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
  543. AddComment("LabelEnd");
  544. OS.EmitValue(getLabelPlusOne(EndLabel), 4);
  545. AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
  546. : "CatchAll");
  547. OS.EmitValue(FilterOrFinally, 4);
  548. AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
  549. OS.EmitValue(ExceptOrNull, 4);
  550. assert(UME.ToState < State && "states should decrease");
  551. State = UME.ToState;
  552. }
  553. }
  554. void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
  555. const Function *F = MF->getFunction();
  556. auto &OS = *Asm->OutStreamer;
  557. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  558. StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
  559. SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
  560. MCSymbol *FuncInfoXData = nullptr;
  561. if (shouldEmitPersonality) {
  562. // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
  563. // IPs to state numbers.
  564. FuncInfoXData =
  565. Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
  566. computeIP2StateTable(MF, FuncInfo, IPToStateTable);
  567. } else {
  568. FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
  569. }
  570. int UnwindHelpOffset = 0;
  571. if (Asm->MAI->usesWindowsCFI())
  572. UnwindHelpOffset =
  573. getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
  574. MCSymbol *UnwindMapXData = nullptr;
  575. MCSymbol *TryBlockMapXData = nullptr;
  576. MCSymbol *IPToStateXData = nullptr;
  577. if (!FuncInfo.CxxUnwindMap.empty())
  578. UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
  579. Twine("$stateUnwindMap$", FuncLinkageName));
  580. if (!FuncInfo.TryBlockMap.empty())
  581. TryBlockMapXData =
  582. Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
  583. if (!IPToStateTable.empty())
  584. IPToStateXData =
  585. Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
  586. bool VerboseAsm = OS.isVerboseAsm();
  587. auto AddComment = [&](const Twine &Comment) {
  588. if (VerboseAsm)
  589. OS.AddComment(Comment);
  590. };
  591. // FuncInfo {
  592. // uint32_t MagicNumber
  593. // int32_t MaxState;
  594. // UnwindMapEntry *UnwindMap;
  595. // uint32_t NumTryBlocks;
  596. // TryBlockMapEntry *TryBlockMap;
  597. // uint32_t IPMapEntries; // always 0 for x86
  598. // IPToStateMapEntry *IPToStateMap; // always 0 for x86
  599. // uint32_t UnwindHelp; // non-x86 only
  600. // ESTypeList *ESTypeList;
  601. // int32_t EHFlags;
  602. // }
  603. // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
  604. // EHFlags & 2 -> ???
  605. // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
  606. OS.EmitValueToAlignment(4);
  607. OS.EmitLabel(FuncInfoXData);
  608. AddComment("MagicNumber");
  609. OS.EmitIntValue(0x19930522, 4);
  610. AddComment("MaxState");
  611. OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
  612. AddComment("UnwindMap");
  613. OS.EmitValue(create32bitRef(UnwindMapXData), 4);
  614. AddComment("NumTryBlocks");
  615. OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
  616. AddComment("TryBlockMap");
  617. OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
  618. AddComment("IPMapEntries");
  619. OS.EmitIntValue(IPToStateTable.size(), 4);
  620. AddComment("IPToStateXData");
  621. OS.EmitValue(create32bitRef(IPToStateXData), 4);
  622. if (Asm->MAI->usesWindowsCFI()) {
  623. AddComment("UnwindHelp");
  624. OS.EmitIntValue(UnwindHelpOffset, 4);
  625. }
  626. AddComment("ESTypeList");
  627. OS.EmitIntValue(0, 4);
  628. AddComment("EHFlags");
  629. OS.EmitIntValue(1, 4);
  630. // UnwindMapEntry {
  631. // int32_t ToState;
  632. // void (*Action)();
  633. // };
  634. if (UnwindMapXData) {
  635. OS.EmitLabel(UnwindMapXData);
  636. for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
  637. MCSymbol *CleanupSym =
  638. getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
  639. AddComment("ToState");
  640. OS.EmitIntValue(UME.ToState, 4);
  641. AddComment("Action");
  642. OS.EmitValue(create32bitRef(CleanupSym), 4);
  643. }
  644. }
  645. // TryBlockMap {
  646. // int32_t TryLow;
  647. // int32_t TryHigh;
  648. // int32_t CatchHigh;
  649. // int32_t NumCatches;
  650. // HandlerType *HandlerArray;
  651. // };
  652. if (TryBlockMapXData) {
  653. OS.EmitLabel(TryBlockMapXData);
  654. SmallVector<MCSymbol *, 1> HandlerMaps;
  655. for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
  656. const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
  657. MCSymbol *HandlerMapXData = nullptr;
  658. if (!TBME.HandlerArray.empty())
  659. HandlerMapXData =
  660. Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
  661. .concat(Twine(I))
  662. .concat("$")
  663. .concat(FuncLinkageName));
  664. HandlerMaps.push_back(HandlerMapXData);
  665. // TBMEs should form intervals.
  666. assert(0 <= TBME.TryLow && "bad trymap interval");
  667. assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
  668. assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
  669. assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
  670. "bad trymap interval");
  671. AddComment("TryLow");
  672. OS.EmitIntValue(TBME.TryLow, 4);
  673. AddComment("TryHigh");
  674. OS.EmitIntValue(TBME.TryHigh, 4);
  675. AddComment("CatchHigh");
  676. OS.EmitIntValue(TBME.CatchHigh, 4);
  677. AddComment("NumCatches");
  678. OS.EmitIntValue(TBME.HandlerArray.size(), 4);
  679. AddComment("HandlerArray");
  680. OS.EmitValue(create32bitRef(HandlerMapXData), 4);
  681. }
  682. // All funclets use the same parent frame offset currently.
  683. unsigned ParentFrameOffset = 0;
  684. if (shouldEmitPersonality) {
  685. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  686. ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
  687. }
  688. for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
  689. const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
  690. MCSymbol *HandlerMapXData = HandlerMaps[I];
  691. if (!HandlerMapXData)
  692. continue;
  693. // HandlerType {
  694. // int32_t Adjectives;
  695. // TypeDescriptor *Type;
  696. // int32_t CatchObjOffset;
  697. // void (*Handler)();
  698. // int32_t ParentFrameOffset; // x64 only
  699. // };
  700. OS.EmitLabel(HandlerMapXData);
  701. for (const WinEHHandlerType &HT : TBME.HandlerArray) {
  702. // Get the frame escape label with the offset of the catch object. If
  703. // the index is INT_MAX, then there is no catch object, and we should
  704. // emit an offset of zero, indicating that no copy will occur.
  705. const MCExpr *FrameAllocOffsetRef = nullptr;
  706. if (HT.CatchObj.FrameIndex != INT_MAX) {
  707. int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
  708. assert(Offset != 0 && "Illegal offset for catch object!");
  709. FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
  710. } else {
  711. FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
  712. }
  713. MCSymbol *HandlerSym =
  714. getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
  715. AddComment("Adjectives");
  716. OS.EmitIntValue(HT.Adjectives, 4);
  717. AddComment("Type");
  718. OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
  719. AddComment("CatchObjOffset");
  720. OS.EmitValue(FrameAllocOffsetRef, 4);
  721. AddComment("Handler");
  722. OS.EmitValue(create32bitRef(HandlerSym), 4);
  723. if (shouldEmitPersonality) {
  724. AddComment("ParentFrameOffset");
  725. OS.EmitIntValue(ParentFrameOffset, 4);
  726. }
  727. }
  728. }
  729. }
  730. // IPToStateMapEntry {
  731. // void *IP;
  732. // int32_t State;
  733. // };
  734. if (IPToStateXData) {
  735. OS.EmitLabel(IPToStateXData);
  736. for (auto &IPStatePair : IPToStateTable) {
  737. AddComment("IP");
  738. OS.EmitValue(IPStatePair.first, 4);
  739. AddComment("ToState");
  740. OS.EmitIntValue(IPStatePair.second, 4);
  741. }
  742. }
  743. }
  744. void WinException::computeIP2StateTable(
  745. const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
  746. SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
  747. for (MachineFunction::const_iterator FuncletStart = MF->begin(),
  748. FuncletEnd = MF->begin(),
  749. End = MF->end();
  750. FuncletStart != End; FuncletStart = FuncletEnd) {
  751. // Find the end of the funclet
  752. while (++FuncletEnd != End) {
  753. if (FuncletEnd->isEHFuncletEntry()) {
  754. break;
  755. }
  756. }
  757. // Don't emit ip2state entries for cleanup funclets. Any interesting
  758. // exceptional actions in cleanups must be handled in a separate IR
  759. // function.
  760. if (FuncletStart->isCleanupFuncletEntry())
  761. continue;
  762. MCSymbol *StartLabel;
  763. int BaseState;
  764. if (FuncletStart == MF->begin()) {
  765. BaseState = NullState;
  766. StartLabel = Asm->getFunctionBegin();
  767. } else {
  768. auto *FuncletPad =
  769. cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
  770. assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
  771. BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
  772. StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
  773. }
  774. assert(StartLabel && "need local function start label");
  775. IPToStateTable.push_back(
  776. std::make_pair(create32bitRef(StartLabel), BaseState));
  777. for (const auto &StateChange : InvokeStateChangeIterator::range(
  778. FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
  779. // Compute the label to report as the start of this entry; use the EH
  780. // start label for the invoke if we have one, otherwise (this is a call
  781. // which may unwind to our caller and does not have an EH start label, so)
  782. // use the previous end label.
  783. const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
  784. if (!ChangeLabel)
  785. ChangeLabel = StateChange.PreviousEndLabel;
  786. // Emit an entry indicating that PCs after 'Label' have this EH state.
  787. IPToStateTable.push_back(
  788. std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
  789. // FIXME: assert that NewState is between CatchLow and CatchHigh.
  790. }
  791. }
  792. }
  793. void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
  794. StringRef FLinkageName) {
  795. // Outlined helpers called by the EH runtime need to know the offset of the EH
  796. // registration in order to recover the parent frame pointer. Now that we know
  797. // we've code generated the parent, we can emit the label assignment that
  798. // those helpers use to get the offset of the registration node.
  799. // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
  800. // after optimization all the invokes were eliminated. We still need to emit
  801. // the parent frame offset label, but it should be garbage and should never be
  802. // used.
  803. int64_t Offset = 0;
  804. int FI = FuncInfo.EHRegNodeFrameIndex;
  805. if (FI != INT_MAX) {
  806. const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
  807. unsigned UnusedReg;
  808. Offset = TFI->getFrameIndexReference(*Asm->MF, FI, UnusedReg);
  809. }
  810. MCContext &Ctx = Asm->OutContext;
  811. MCSymbol *ParentFrameOffset =
  812. Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
  813. Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
  814. MCConstantExpr::create(Offset, Ctx));
  815. }
  816. /// Emit the language-specific data that _except_handler3 and 4 expect. This is
  817. /// functionally equivalent to the __C_specific_handler table, except it is
  818. /// indexed by state number instead of IP.
  819. void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
  820. MCStreamer &OS = *Asm->OutStreamer;
  821. const Function *F = MF->getFunction();
  822. StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
  823. bool VerboseAsm = OS.isVerboseAsm();
  824. auto AddComment = [&](const Twine &Comment) {
  825. if (VerboseAsm)
  826. OS.AddComment(Comment);
  827. };
  828. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  829. emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
  830. // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
  831. MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
  832. OS.EmitValueToAlignment(4);
  833. OS.EmitLabel(LSDALabel);
  834. const Function *Per =
  835. dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
  836. StringRef PerName = Per->getName();
  837. int BaseState = -1;
  838. if (PerName == "_except_handler4") {
  839. // The LSDA for _except_handler4 starts with this struct, followed by the
  840. // scope table:
  841. //
  842. // struct EH4ScopeTable {
  843. // int32_t GSCookieOffset;
  844. // int32_t GSCookieXOROffset;
  845. // int32_t EHCookieOffset;
  846. // int32_t EHCookieXOROffset;
  847. // ScopeTableEntry ScopeRecord[];
  848. // };
  849. //
  850. // Offsets are %ebp relative.
  851. //
  852. // The GS cookie is present only if the function needs stack protection.
  853. // GSCookieOffset = -2 means that GS cookie is not used.
  854. //
  855. // The EH cookie is always present.
  856. //
  857. // Check is done the following way:
  858. // (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
  859. // Retrieve the Guard Stack slot.
  860. int GSCookieOffset = -2;
  861. const MachineFrameInfo &MFI = MF->getFrameInfo();
  862. if (MFI.hasStackProtectorIndex()) {
  863. unsigned UnusedReg;
  864. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  865. int SSPIdx = MFI.getStackProtectorIndex();
  866. GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
  867. }
  868. // Retrieve the EH Guard slot.
  869. // TODO(etienneb): Get rid of this value and change it for and assertion.
  870. int EHCookieOffset = 9999;
  871. if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
  872. unsigned UnusedReg;
  873. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  874. int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
  875. EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
  876. }
  877. AddComment("GSCookieOffset");
  878. OS.EmitIntValue(GSCookieOffset, 4);
  879. AddComment("GSCookieXOROffset");
  880. OS.EmitIntValue(0, 4);
  881. AddComment("EHCookieOffset");
  882. OS.EmitIntValue(EHCookieOffset, 4);
  883. AddComment("EHCookieXOROffset");
  884. OS.EmitIntValue(0, 4);
  885. BaseState = -2;
  886. }
  887. assert(!FuncInfo.SEHUnwindMap.empty());
  888. for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
  889. auto *Handler = UME.Handler.get<MachineBasicBlock *>();
  890. const MCSymbol *ExceptOrFinally =
  891. UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
  892. // -1 is usually the base state for "unwind to caller", but for
  893. // _except_handler4 it's -2. Do that replacement here if necessary.
  894. int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
  895. AddComment("ToState");
  896. OS.EmitIntValue(ToState, 4);
  897. AddComment(UME.IsFinally ? "Null" : "FilterFunction");
  898. OS.EmitValue(create32bitRef(UME.Filter), 4);
  899. AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
  900. OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
  901. }
  902. }
  903. static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
  904. int Rank = 0;
  905. while (State != -1) {
  906. ++Rank;
  907. State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
  908. }
  909. return Rank;
  910. }
  911. static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
  912. int LeftRank = getTryRank(FuncInfo, Left);
  913. int RightRank = getTryRank(FuncInfo, Right);
  914. while (LeftRank < RightRank) {
  915. Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
  916. --RightRank;
  917. }
  918. while (RightRank < LeftRank) {
  919. Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
  920. --LeftRank;
  921. }
  922. while (Left != Right) {
  923. Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
  924. Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
  925. }
  926. return Left;
  927. }
  928. void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
  929. // CLR EH "states" are really just IDs that identify handlers/funclets;
  930. // states, handlers, and funclets all have 1:1 mappings between them, and a
  931. // handler/funclet's "state" is its index in the ClrEHUnwindMap.
  932. MCStreamer &OS = *Asm->OutStreamer;
  933. const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
  934. MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
  935. MCSymbol *FuncEndSym = Asm->getFunctionEnd();
  936. // A ClrClause describes a protected region.
  937. struct ClrClause {
  938. const MCSymbol *StartLabel; // Start of protected region
  939. const MCSymbol *EndLabel; // End of protected region
  940. int State; // Index of handler protecting the protected region
  941. int EnclosingState; // Index of funclet enclosing the protected region
  942. };
  943. SmallVector<ClrClause, 8> Clauses;
  944. // Build a map from handler MBBs to their corresponding states (i.e. their
  945. // indices in the ClrEHUnwindMap).
  946. int NumStates = FuncInfo.ClrEHUnwindMap.size();
  947. assert(NumStates > 0 && "Don't need exception table!");
  948. DenseMap<const MachineBasicBlock *, int> HandlerStates;
  949. for (int State = 0; State < NumStates; ++State) {
  950. MachineBasicBlock *HandlerBlock =
  951. FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
  952. HandlerStates[HandlerBlock] = State;
  953. // Use this loop through all handlers to verify our assumption (used in
  954. // the MinEnclosingState computation) that enclosing funclets have lower
  955. // state numbers than their enclosed funclets.
  956. assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
  957. "ill-formed state numbering");
  958. }
  959. // Map the main function to the NullState.
  960. HandlerStates[&MF->front()] = NullState;
  961. // Write out a sentinel indicating the end of the standard (Windows) xdata
  962. // and the start of the additional (CLR) info.
  963. OS.EmitIntValue(0xffffffff, 4);
  964. // Write out the number of funclets
  965. OS.EmitIntValue(NumStates, 4);
  966. // Walk the machine blocks/instrs, computing and emitting a few things:
  967. // 1. Emit a list of the offsets to each handler entry, in lexical order.
  968. // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
  969. // 3. Compute the list of ClrClauses, in the required order (inner before
  970. // outer, earlier before later; the order by which a forward scan with
  971. // early termination will find the innermost enclosing clause covering
  972. // a given address).
  973. // 4. A map (MinClauseMap) from each handler index to the index of the
  974. // outermost funclet/function which contains a try clause targeting the
  975. // key handler. This will be used to determine IsDuplicate-ness when
  976. // emitting ClrClauses. The NullState value is used to indicate that the
  977. // top-level function contains a try clause targeting the key handler.
  978. // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
  979. // try regions we entered before entering the PendingState try but which
  980. // we haven't yet exited.
  981. SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
  982. // EndSymbolMap and MinClauseMap are maps described above.
  983. std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
  984. SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
  985. // Visit the root function and each funclet.
  986. for (MachineFunction::const_iterator FuncletStart = MF->begin(),
  987. FuncletEnd = MF->begin(),
  988. End = MF->end();
  989. FuncletStart != End; FuncletStart = FuncletEnd) {
  990. int FuncletState = HandlerStates[&*FuncletStart];
  991. // Find the end of the funclet
  992. MCSymbol *EndSymbol = FuncEndSym;
  993. while (++FuncletEnd != End) {
  994. if (FuncletEnd->isEHFuncletEntry()) {
  995. EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
  996. break;
  997. }
  998. }
  999. // Emit the function/funclet end and, if this is a funclet (and not the
  1000. // root function), record it in the EndSymbolMap.
  1001. OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
  1002. if (FuncletState != NullState) {
  1003. // Record the end of the handler.
  1004. EndSymbolMap[FuncletState] = EndSymbol;
  1005. }
  1006. // Walk the state changes in this function/funclet and compute its clauses.
  1007. // Funclets always start in the null state.
  1008. const MCSymbol *CurrentStartLabel = nullptr;
  1009. int CurrentState = NullState;
  1010. assert(HandlerStack.empty());
  1011. for (const auto &StateChange :
  1012. InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
  1013. // Close any try regions we're not still under
  1014. int StillPendingState =
  1015. getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
  1016. while (CurrentState != StillPendingState) {
  1017. assert(CurrentState != NullState &&
  1018. "Failed to find still-pending state!");
  1019. // Close the pending clause
  1020. Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
  1021. CurrentState, FuncletState});
  1022. // Now the next-outer try region is current
  1023. CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
  1024. // Pop the new start label from the handler stack if we've exited all
  1025. // inner try regions of the corresponding try region.
  1026. if (HandlerStack.back().second == CurrentState)
  1027. CurrentStartLabel = HandlerStack.pop_back_val().first;
  1028. }
  1029. if (StateChange.NewState != CurrentState) {
  1030. // For each clause we're starting, update the MinClauseMap so we can
  1031. // know which is the topmost funclet containing a clause targeting
  1032. // it.
  1033. for (int EnteredState = StateChange.NewState;
  1034. EnteredState != CurrentState;
  1035. EnteredState =
  1036. FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
  1037. int &MinEnclosingState = MinClauseMap[EnteredState];
  1038. if (FuncletState < MinEnclosingState)
  1039. MinEnclosingState = FuncletState;
  1040. }
  1041. // Save the previous current start/label on the stack and update to
  1042. // the newly-current start/state.
  1043. HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
  1044. CurrentStartLabel = StateChange.NewStartLabel;
  1045. CurrentState = StateChange.NewState;
  1046. }
  1047. }
  1048. assert(HandlerStack.empty());
  1049. }
  1050. // Now emit the clause info, starting with the number of clauses.
  1051. OS.EmitIntValue(Clauses.size(), 4);
  1052. for (ClrClause &Clause : Clauses) {
  1053. // Emit a CORINFO_EH_CLAUSE :
  1054. /*
  1055. struct CORINFO_EH_CLAUSE
  1056. {
  1057. CORINFO_EH_CLAUSE_FLAGS Flags; // actually a CorExceptionFlag
  1058. DWORD TryOffset;
  1059. DWORD TryLength; // actually TryEndOffset
  1060. DWORD HandlerOffset;
  1061. DWORD HandlerLength; // actually HandlerEndOffset
  1062. union
  1063. {
  1064. DWORD ClassToken; // use for catch clauses
  1065. DWORD FilterOffset; // use for filter clauses
  1066. };
  1067. };
  1068. enum CORINFO_EH_CLAUSE_FLAGS
  1069. {
  1070. CORINFO_EH_CLAUSE_NONE = 0,
  1071. CORINFO_EH_CLAUSE_FILTER = 0x0001, // This clause is for a filter
  1072. CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
  1073. CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
  1074. };
  1075. typedef enum CorExceptionFlag
  1076. {
  1077. COR_ILEXCEPTION_CLAUSE_NONE,
  1078. COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001, // This is a filter clause
  1079. COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
  1080. COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004, // This is a fault clause
  1081. COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
  1082. // clause was duplicated
  1083. // to a funclet which was
  1084. // pulled out of line
  1085. } CorExceptionFlag;
  1086. */
  1087. // Add 1 to the start/end of the EH clause; the IP associated with a
  1088. // call when the runtime does its scan is the IP of the next instruction
  1089. // (the one to which control will return after the call), so we need
  1090. // to add 1 to the end of the clause to cover that offset. We also add
  1091. // 1 to the start of the clause to make sure that the ranges reported
  1092. // for all clauses are disjoint. Note that we'll need some additional
  1093. // logic when machine traps are supported, since in that case the IP
  1094. // that the runtime uses is the offset of the faulting instruction
  1095. // itself; if such an instruction immediately follows a call but the
  1096. // two belong to different clauses, we'll need to insert a nop between
  1097. // them so the runtime can distinguish the point to which the call will
  1098. // return from the point at which the fault occurs.
  1099. const MCExpr *ClauseBegin =
  1100. getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
  1101. const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
  1102. const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
  1103. MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
  1104. MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
  1105. const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
  1106. MCSymbol *EndSym = EndSymbolMap[Clause.State];
  1107. const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
  1108. uint32_t Flags = 0;
  1109. switch (Entry.HandlerType) {
  1110. case ClrHandlerType::Catch:
  1111. // Leaving bits 0-2 clear indicates catch.
  1112. break;
  1113. case ClrHandlerType::Filter:
  1114. Flags |= 1;
  1115. break;
  1116. case ClrHandlerType::Finally:
  1117. Flags |= 2;
  1118. break;
  1119. case ClrHandlerType::Fault:
  1120. Flags |= 4;
  1121. break;
  1122. }
  1123. if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
  1124. // This is a "duplicate" clause; the handler needs to be entered from a
  1125. // frame above the one holding the invoke.
  1126. assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
  1127. Flags |= 8;
  1128. }
  1129. OS.EmitIntValue(Flags, 4);
  1130. // Write the clause start/end
  1131. OS.EmitValue(ClauseBegin, 4);
  1132. OS.EmitValue(ClauseEnd, 4);
  1133. // Write out the handler start/end
  1134. OS.EmitValue(HandlerBegin, 4);
  1135. OS.EmitValue(HandlerEnd, 4);
  1136. // Write out the type token or filter offset
  1137. assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
  1138. OS.EmitIntValue(Entry.TypeToken, 4);
  1139. }
  1140. }