blob: 882859afc48850af135210a20fb2fbe0c9c3abc9 [file] [log] [blame]
Reid Kleckner60b640b2015-05-28 22:47:01 +00001//===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
Charles Davis91ed7992011-05-27 23:47:32 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Charles Davis91ed7992011-05-27 23:47:32 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for writing Win64 exception info into asm files.
10//
11//===----------------------------------------------------------------------===//
12
Reid Kleckner60b640b2015-05-28 22:47:01 +000013#include "WinException.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000015#include "llvm/BinaryFormat/COFF.h"
16#include "llvm/BinaryFormat/Dwarf.h"
Charles Davis91ed7992011-05-27 23:47:32 +000017#include "llvm/CodeGen/AsmPrinter.h"
Charles Davis91ed7992011-05-27 23:47:32 +000018#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/CodeGen/MachineModuleInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000021#include "llvm/CodeGen/TargetFrameLowering.h"
22#include "llvm/CodeGen/TargetLowering.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000023#include "llvm/CodeGen/TargetSubtargetInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000024#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000026#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
Charles Davis91ed7992011-05-27 23:47:32 +000028#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCContext.h"
30#include "llvm/MC/MCExpr.h"
31#include "llvm/MC/MCSection.h"
32#include "llvm/MC/MCStreamer.h"
33#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/FormattedStream.h"
David Blaikie6054e652018-03-23 23:58:19 +000036#include "llvm/Target/TargetLoweringObjectFile.h"
Charles Davis91ed7992011-05-27 23:47:32 +000037#include "llvm/Target/TargetOptions.h"
Charles Davis91ed7992011-05-27 23:47:32 +000038using namespace llvm;
39
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000040WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
41 // MSVC's EH tables are always composed of 32-bit words. All known 64-bit
42 // platforms use an imagerel32 relocation to refer to symbols.
43 useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
Sanjin Sijaric96f2ea32018-10-27 06:13:06 +000044 isAArch64 = Asm->TM.getTargetTriple().isAArch64();
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000045}
Charles Davis91ed7992011-05-27 23:47:32 +000046
Reid Kleckner60b640b2015-05-28 22:47:01 +000047WinException::~WinException() {}
Charles Davis91ed7992011-05-27 23:47:32 +000048
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000049/// endModule - Emit all exception information that should come after the
Charles Davis91ed7992011-05-27 23:47:32 +000050/// content.
Reid Kleckner60b640b2015-05-28 22:47:01 +000051void WinException::endModule() {
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000052 auto &OS = *Asm->OutStreamer;
53 const Module *M = MMI->getModule();
Reid Klecknerca6ef662015-06-10 01:13:44 +000054 for (const Function &F : *M)
55 if (F.hasFnAttribute("safeseh"))
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000056 OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
Charles Davis91ed7992011-05-27 23:47:32 +000057}
58
Reid Kleckner60b640b2015-05-28 22:47:01 +000059void WinException::beginFunction(const MachineFunction *MF) {
Charles Davis5638b9f2011-05-28 04:21:04 +000060 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
61
62 // If any landing pads survive, we need an EH table.
Matthias Braund0ee66c2016-12-01 19:32:15 +000063 bool hasLandingPads = !MF->getLandingPads().empty();
64 bool hasEHFunclets = MF->hasEHFunclets();
Charles Davis5638b9f2011-05-28 04:21:04 +000065
Matthias Braunf1caa282017-12-15 22:22:58 +000066 const Function &F = MF->getFunction();
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000067
Reid Kleckner8819c732017-03-20 17:45:59 +000068 shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
Charles Davis5638b9f2011-05-28 04:21:04 +000069
70 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
71 unsigned PerEncoding = TLOF.getPersonalityEncoding();
Charles Davis5638b9f2011-05-28 04:21:04 +000072
Reid Kleckner9cb915b2016-09-30 22:10:12 +000073 EHPersonality Per = EHPersonality::Unknown;
74 const Function *PerFn = nullptr;
Matthias Braunf1caa282017-12-15 22:22:58 +000075 if (F.hasPersonalityFn()) {
76 PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
Reid Kleckner9cb915b2016-09-30 22:10:12 +000077 Per = classifyEHPersonality(PerFn);
78 }
79
Matthias Braunf1caa282017-12-15 22:22:58 +000080 bool forceEmitPersonality = F.hasPersonalityFn() &&
Reid Kleckner9cb915b2016-09-30 22:10:12 +000081 !isNoOpWithoutInvoke(Per) &&
Matthias Braunf1caa282017-12-15 22:22:58 +000082 F.needsUnwindTableEntry();
Keno Fischeraff703a2015-07-14 19:22:51 +000083
Reid Kleckner0e288232015-08-27 23:27:47 +000084 shouldEmitPersonality =
85 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
Reid Kleckner9cb915b2016-09-30 22:10:12 +000086 PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
Charles Davis5638b9f2011-05-28 04:21:04 +000087
88 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
89 shouldEmitLSDA = shouldEmitPersonality &&
90 LSDAEncoding != dwarf::DW_EH_PE_omit;
91
Reid Kleckner0e288232015-08-27 23:27:47 +000092 // If we're not using CFI, we don't want the CFI or the personality, but we
93 // might want EH tables if we had EH pads.
Reid Kleckner8819c732017-03-20 17:45:59 +000094 if (!Asm->MAI->usesWindowsCFI()) {
Reid Kleckner9cb915b2016-09-30 22:10:12 +000095 if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
96 // If this is 32-bit SEH and we don't have any funclets (really invokes),
97 // make sure we emit the parent offset label. Some unreferenced filter
98 // functions may still refer to it.
99 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
100 StringRef FLinkageName =
Matthias Braunf1caa282017-12-15 22:22:58 +0000101 GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000102 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
103 }
David Majnemerbfa5b982015-10-10 00:04:29 +0000104 shouldEmitLSDA = hasEHFunclets;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000105 shouldEmitPersonality = false;
106 return;
107 }
David Majnemera225a192015-03-31 22:35:44 +0000108
David Majnemera80c1512015-09-29 20:12:33 +0000109 beginFunclet(MF->front(), Asm->CurrentFnSym);
Charles Davis91ed7992011-05-27 23:47:32 +0000110}
111
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000112/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000113///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000114void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000115 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000116 return;
117
Matthias Braunf1caa282017-12-15 22:22:58 +0000118 const Function &F = MF->getFunction();
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000119 EHPersonality Per = EHPersonality::Unknown;
Matthias Braunf1caa282017-12-15 22:22:58 +0000120 if (F.hasPersonalityFn())
121 Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000122
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000123 // Get rid of any dead landing pads if we're not using funclets. In funclet
124 // schemes, the landing pad is not actually reachable. It only exists so
125 // that we can emit the right table data.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000126 if (!isFuncletEHPersonality(Per)) {
127 MachineFunction *NonConstMF = const_cast<MachineFunction*>(MF);
128 NonConstMF->tidyLandingPads();
129 }
Charles Davisa5752262011-05-30 00:13:34 +0000130
David Majnemera80c1512015-09-29 20:12:33 +0000131 endFunclet();
132
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000133 // endFunclet will emit the necessary .xdata tables for x64 SEH.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000134 if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets())
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000135 return;
136
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000137 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000138 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000139
Reid Kleckner97837b72016-05-02 23:22:18 +0000140 // Just switch sections to the right xdata section.
141 MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
142 Asm->OutStreamer->getCurrentSectionOnly());
David Majnemera80c1512015-09-29 20:12:33 +0000143 Asm->OutStreamer->SwitchSection(XData);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000144
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000145 // Emit the tables appropriate to the personality function in use. If we
146 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000147 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000148 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000149 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000150 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000151 else if (Per == EHPersonality::MSVC_CXX)
152 emitCXXFrameHandler3Table(MF);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000153 else if (Per == EHPersonality::CoreCLR)
154 emitCLRExceptionTable(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000155 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000156 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000157
Lang Hames9ff69c82015-04-24 19:11:51 +0000158 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000159 }
David Majnemera80c1512015-09-29 20:12:33 +0000160}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000161
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000162/// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
David Majnemerbfa5b982015-10-10 00:04:29 +0000163static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
164 const MachineBasicBlock *MBB) {
165 if (!MBB)
David Majnemera80c1512015-09-29 20:12:33 +0000166 return nullptr;
David Majnemera80c1512015-09-29 20:12:33 +0000167
David Majnemerbfa5b982015-10-10 00:04:29 +0000168 assert(MBB->isEHFuncletEntry());
169
170 // Give catches and cleanups a name based off of their parent function and
171 // their funclet entry block's number.
172 const MachineFunction *MF = MBB->getParent();
Matthias Braunf1caa282017-12-15 22:22:58 +0000173 const Function &F = MF->getFunction();
174 StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
David Majnemerbfa5b982015-10-10 00:04:29 +0000175 MCContext &Ctx = MF->getContext();
176 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
177 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
178 Twine(MBB->getNumber()) + "@?0?" +
179 FuncLinkageName + "@4HA");
David Majnemera80c1512015-09-29 20:12:33 +0000180}
181
182void WinException::beginFunclet(const MachineBasicBlock &MBB,
183 MCSymbol *Sym) {
184 CurrentFuncletEntry = &MBB;
185
Matthias Braunf1caa282017-12-15 22:22:58 +0000186 const Function &F = Asm->MF->getFunction();
David Majnemera80c1512015-09-29 20:12:33 +0000187 // If a symbol was not provided for the funclet, invent one.
188 if (!Sym) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000189 Sym = getMCSymbolForMBB(Asm, &MBB);
David Majnemera80c1512015-09-29 20:12:33 +0000190
191 // Describe our funclet symbol as a function with internal linkage.
192 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
193 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
194 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
195 << COFF::SCT_COMPLEX_TYPE_SHIFT);
196 Asm->OutStreamer->EndCOFFSymbolDef();
197
198 // We want our funclet's entry point to be aligned such that no nops will be
199 // present after the label.
200 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
Matthias Braunf1caa282017-12-15 22:22:58 +0000201 &F);
David Majnemera80c1512015-09-29 20:12:33 +0000202
203 // Now that we've emitted the alignment directive, point at our funclet.
204 Asm->OutStreamer->EmitLabel(Sym);
205 }
206
207 // Mark 'Sym' as starting our funclet.
Reid Kleckner92647362016-12-28 19:05:12 +0000208 if (shouldEmitMoves || shouldEmitPersonality) {
209 CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
David Majnemera80c1512015-09-29 20:12:33 +0000210 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
Reid Kleckner92647362016-12-28 19:05:12 +0000211 }
David Majnemera80c1512015-09-29 20:12:33 +0000212
213 if (shouldEmitPersonality) {
214 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
215 const Function *PerFn = nullptr;
216
217 // Determine which personality routine we are using for this funclet.
Matthias Braunf1caa282017-12-15 22:22:58 +0000218 if (F.hasPersonalityFn())
219 PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
David Majnemera80c1512015-09-29 20:12:33 +0000220 const MCSymbol *PersHandlerSym =
Eric Christopher4367c7f2016-09-16 07:33:15 +0000221 TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
David Majnemera80c1512015-09-29 20:12:33 +0000222
Reid Kleckner785e7d22016-12-08 20:38:46 +0000223 // Do not emit a .seh_handler directives for cleanup funclets.
224 // FIXME: This means cleanup funclets cannot handle exceptions. Given that
225 // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
226 // inliner doesn't allow inlining them, this isn't a major problem in
227 // practice.
228 if (!CurrentFuncletEntry->isCleanupFuncletEntry())
David Majnemera80c1512015-09-29 20:12:33 +0000229 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
230 }
231}
232
233void WinException::endFunclet() {
234 // No funclet to process? Great, we have nothing to do.
235 if (!CurrentFuncletEntry)
236 return;
237
Matthias Braund0ee66c2016-12-01 19:32:15 +0000238 const MachineFunction *MF = Asm->MF;
David Majnemera80c1512015-09-29 20:12:33 +0000239 if (shouldEmitMoves || shouldEmitPersonality) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000240 const Function &F = MF->getFunction();
David Majnemera80c1512015-09-29 20:12:33 +0000241 EHPersonality Per = EHPersonality::Unknown;
Matthias Braunf1caa282017-12-15 22:22:58 +0000242 if (F.hasPersonalityFn())
243 Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
David Majnemera80c1512015-09-29 20:12:33 +0000244
Sanjin Sijaric96f2ea32018-10-27 06:13:06 +0000245 // On funclet exit, we emit a fake "function" end marker, so that the call
246 // to EmitWinEHHandlerData below can calculate the size of the funclet or
247 // function.
248 if (isAArch64) {
249 Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
250 Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
251 MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
252 Asm->OutStreamer->getCurrentSectionOnly());
253 Asm->OutStreamer->SwitchSection(XData);
254 }
255
David Majnemera80c1512015-09-29 20:12:33 +0000256 // Emit an UNWIND_INFO struct describing the prologue.
257 Asm->OutStreamer->EmitWinEHHandlerData();
258
David Majnemera80c1512015-09-29 20:12:33 +0000259 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
260 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000261 // If this is a C++ catch funclet (or the parent function),
262 // emit a reference to the LSDA for the parent function.
Matthias Braunf1caa282017-12-15 22:22:58 +0000263 StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
David Majnemera80c1512015-09-29 20:12:33 +0000264 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
265 Twine("$cppxdata$", FuncLinkageName));
266 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Matthias Braund0ee66c2016-12-01 19:32:15 +0000267 } else if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets() &&
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000268 !CurrentFuncletEntry->isEHFuncletEntry()) {
269 // If this is the parent function in Win64 SEH, emit the LSDA immediately
270 // following .seh_handlerdata.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000271 emitCSpecificHandlerTable(MF);
David Majnemera80c1512015-09-29 20:12:33 +0000272 }
273
Reid Kleckner92647362016-12-28 19:05:12 +0000274 // Switch back to the funclet start .text section now that we are done
275 // writing to .xdata, and emit an .seh_endproc directive to mark the end of
276 // the function.
277 Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000278 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000279 }
280
281 // Let's make sure we don't try to end the same funclet twice.
282 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000283}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000284
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000285const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000286 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000287 return MCConstantExpr::create(0, Asm->OutContext);
288 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000289 ? MCSymbolRefExpr::VK_COFF_IMGREL32
290 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000291 Asm->OutContext);
292}
293
Joseph Tremoulet3d0fbf12015-10-23 15:06:05 +0000294const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
295 if (!GV)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000296 return MCConstantExpr::create(0, Asm->OutContext);
Joseph Tremoulet3d0fbf12015-10-23 15:06:05 +0000297 return create32bitRef(Asm->getSymbol(GV));
David Majnemercde33032015-03-30 22:58:10 +0000298}
299
Sanjin Sijaric96f2ea32018-10-27 06:13:06 +0000300const MCExpr *WinException::getLabel(const MCSymbol *Label) {
301 if (isAArch64)
302 return MCSymbolRefExpr::create(Label, MCSymbolRefExpr::VK_COFF_IMGREL32,
303 Asm->OutContext);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000304 return MCBinaryExpr::createAdd(create32bitRef(Label),
305 MCConstantExpr::create(1, Asm->OutContext),
306 Asm->OutContext);
307}
308
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000309const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
310 const MCSymbol *OffsetFrom) {
311 return MCBinaryExpr::createSub(
312 MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
313 MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
314}
315
316const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
317 const MCSymbol *OffsetFrom) {
318 return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
319 MCConstantExpr::create(1, Asm->OutContext),
320 Asm->OutContext);
321}
322
Reid Klecknerc20276d2015-11-17 21:10:25 +0000323int WinException::getFrameIndexOffset(int FrameIndex,
324 const WinEHFuncInfo &FuncInfo) {
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000325 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
326 unsigned UnusedReg;
Sanjoy Das0ebc9612016-06-16 18:54:06 +0000327 if (Asm->MAI->usesWindowsCFI()) {
328 int Offset =
329 TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
330 /*IgnoreSPUpdates*/ true);
331 assert(UnusedReg ==
332 Asm->MF->getSubtarget()
333 .getTargetLowering()
334 ->getStackPointerRegisterToSaveRestore());
335 return Offset;
336 }
337
Reid Kleckner6ddae312015-11-05 21:09:49 +0000338 // For 32-bit, offsets should be relative to the end of the EH registration
339 // node. For 64-bit, it's relative to SP at the end of the prologue.
340 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
341 int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
342 Offset += FuncInfo.EHRegNodeEndOffset;
343 return Offset;
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000344}
345
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000346namespace {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000347
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000348/// Top-level state used to represent unwind to caller
349const int NullState = -1;
350
351struct InvokeStateChange {
352 /// EH Label immediately after the last invoke in the previous state, or
353 /// nullptr if the previous state was the null state.
354 const MCSymbol *PreviousEndLabel;
355
356 /// EH label immediately before the first invoke in the new state, or nullptr
357 /// if the new state is the null state.
358 const MCSymbol *NewStartLabel;
359
360 /// State of the invoke following NewStartLabel, or NullState to indicate
361 /// the presence of calls which may unwind to caller.
362 int NewState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000363};
364
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000365/// Iterator that reports all the invoke state changes in a range of machine
366/// basic blocks. Changes to the null state are reported whenever a call that
367/// may unwind to caller is encountered. The MBB range is expected to be an
368/// entire function or funclet, and the start and end of the range are treated
369/// as being in the NullState even if there's not an unwind-to-caller call
370/// before the first invoke or after the last one (i.e., the first state change
371/// reported is the first change to something other than NullState, and a
372/// change back to NullState is always reported at the end of iteration).
373class InvokeStateChangeIterator {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000374 InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000375 MachineFunction::const_iterator MFI,
376 MachineFunction::const_iterator MFE,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000377 MachineBasicBlock::const_iterator MBBI,
378 int BaseState)
379 : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000380 LastStateChange.PreviousEndLabel = nullptr;
381 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000382 LastStateChange.NewState = BaseState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000383 scan();
384 }
385
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000386public:
387 static iterator_range<InvokeStateChangeIterator>
Reid Klecknerc20276d2015-11-17 21:10:25 +0000388 range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000389 MachineFunction::const_iterator End, int BaseState = NullState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000390 // Reject empty ranges to simplify bookkeeping by ensuring that we can get
391 // the end of the last block.
392 assert(Begin != End);
393 auto BlockBegin = Begin->begin();
394 auto BlockEnd = std::prev(End)->end();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000395 return make_range(
396 InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
397 InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000398 }
399
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000400 // Iterator methods.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000401 bool operator==(const InvokeStateChangeIterator &O) const {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000402 assert(BaseState == O.BaseState);
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000403 // Must be visiting same block.
404 if (MFI != O.MFI)
405 return false;
406 // Must be visiting same isntr.
407 if (MBBI != O.MBBI)
408 return false;
409 // At end of block/instr iteration, we can still have two distinct states:
410 // one to report the final EndLabel, and another indicating the end of the
411 // state change iteration. Check for CurrentEndLabel equality to
412 // distinguish these.
413 return CurrentEndLabel == O.CurrentEndLabel;
414 }
415
416 bool operator!=(const InvokeStateChangeIterator &O) const {
417 return !operator==(O);
418 }
419 InvokeStateChange &operator*() { return LastStateChange; }
420 InvokeStateChange *operator->() { return &LastStateChange; }
421 InvokeStateChangeIterator &operator++() { return scan(); }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000422
423private:
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000424 InvokeStateChangeIterator &scan();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000425
Reid Klecknerc20276d2015-11-17 21:10:25 +0000426 const WinEHFuncInfo &EHInfo;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000427 const MCSymbol *CurrentEndLabel = nullptr;
428 MachineFunction::const_iterator MFI;
429 MachineFunction::const_iterator MFE;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000430 MachineBasicBlock::const_iterator MBBI;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000431 InvokeStateChange LastStateChange;
432 bool VisitingInvoke = false;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000433 int BaseState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000434};
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000435
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000436} // end anonymous namespace
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000437
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000438InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
439 bool IsNewBlock = false;
440 for (; MFI != MFE; ++MFI, IsNewBlock = true) {
441 if (IsNewBlock)
442 MBBI = MFI->begin();
443 for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
444 const MachineInstr &MI = *MBBI;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000445 if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000446 MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
447 // Indicate a change of state to the null state. We don't have
448 // start/end EH labels handy but the caller won't expect them for
449 // null state regions.
450 LastStateChange.PreviousEndLabel = CurrentEndLabel;
451 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000452 LastStateChange.NewState = BaseState;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000453 CurrentEndLabel = nullptr;
454 // Don't re-visit this instr on the next scan
455 ++MBBI;
456 return *this;
457 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000458
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000459 // All other state changes are at EH labels before/after invokes.
460 if (!MI.isEHLabel())
461 continue;
462 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
463 if (Label == CurrentEndLabel) {
464 VisitingInvoke = false;
465 continue;
466 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000467 auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000468 // Ignore EH labels that aren't the ones inserted before an invoke
David Majnemer8a1c45d2015-12-12 05:38:55 +0000469 if (InvokeMapIter == EHInfo.LabelToStateMap.end())
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000470 continue;
471 auto &StateAndEnd = InvokeMapIter->second;
472 int NewState = StateAndEnd.first;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000473 // Keep track of the fact that we're between EH start/end labels so
474 // we know not to treat the inoke we'll see as unwinding to caller.
475 VisitingInvoke = true;
476 if (NewState == LastStateChange.NewState) {
477 // The state isn't actually changing here. Record the new end and
478 // keep going.
479 CurrentEndLabel = StateAndEnd.second;
480 continue;
481 }
482 // Found a state change to report
483 LastStateChange.PreviousEndLabel = CurrentEndLabel;
484 LastStateChange.NewStartLabel = Label;
485 LastStateChange.NewState = NewState;
486 // Start keeping track of the new current end
487 CurrentEndLabel = StateAndEnd.second;
488 // Don't re-visit this instr on the next scan
489 ++MBBI;
490 return *this;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000491 }
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000492 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000493 // Iteration hit the end of the block range.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000494 if (LastStateChange.NewState != BaseState) {
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000495 // Report the end of the last new state
496 LastStateChange.PreviousEndLabel = CurrentEndLabel;
497 LastStateChange.NewStartLabel = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000498 LastStateChange.NewState = BaseState;
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000499 // Leave CurrentEndLabel non-null to distinguish this state from end.
500 assert(CurrentEndLabel != nullptr);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000501 return *this;
502 }
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000503 // We've reported all state changes and hit the end state.
504 CurrentEndLabel = nullptr;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000505 return *this;
506}
507
Reid Kleckner0a57f652015-01-14 01:05:27 +0000508/// Emit the language-specific data that __C_specific_handler expects. This
509/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
510/// up after faults with __try, __except, and __finally. The typeinfo values
511/// are not really RTTI data, but pointers to filter functions that return an
512/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
513/// blocks and other cleanups, the landing pad label is zero, and the filter
514/// function is actually a cleanup handler with the same prototype. A catch-all
515/// entry is modeled with a null filter function field and a non-zero landing
516/// pad label.
517///
518/// Possible filter function return values:
519/// EXCEPTION_EXECUTE_HANDLER (1):
520/// Jump to the landing pad label after cleanups.
521/// EXCEPTION_CONTINUE_SEARCH (0):
522/// Continue searching this table or continue unwinding.
523/// EXCEPTION_CONTINUE_EXECUTION (-1):
524/// Resume execution at the trapping PC.
525///
526/// Inferred table structure:
527/// struct Table {
528/// int NumEntries;
529/// struct Entry {
530/// imagerel32 LabelStart;
531/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000532/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner14e77352015-10-09 23:34:53 +0000533/// imagerel32 LabelLPad; // Zero means __finally.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000534/// } Entries[NumEntries];
535/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000536void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000537 auto &OS = *Asm->OutStreamer;
538 MCContext &Ctx = Asm->OutContext;
Reid Klecknerc20276d2015-11-17 21:10:25 +0000539 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Reid Kleckner7850c9f2015-12-15 23:40:58 +0000540
David Majnemer081e8fe2015-12-27 06:07:12 +0000541 bool VerboseAsm = OS.isVerboseAsm();
542 auto AddComment = [&](const Twine &Comment) {
543 if (VerboseAsm)
544 OS.AddComment(Comment);
545 };
546
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +0000547 if (!isAArch64) {
548 // Emit a label assignment with the SEH frame offset so we can use it for
549 // llvm.eh.recoverfp.
550 StringRef FLinkageName =
551 GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
552 MCSymbol *ParentFrameOffset =
553 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
554 const MCExpr *MCOffset =
555 MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
556 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
557 }
Reid Kleckner7850c9f2015-12-15 23:40:58 +0000558
Reid Kleckner14e77352015-10-09 23:34:53 +0000559 // Use the assembler to compute the number of table entries through label
560 // difference and division.
561 MCSymbol *TableBegin =
562 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
563 MCSymbol *TableEnd =
564 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +0000565 const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
Reid Kleckner14e77352015-10-09 23:34:53 +0000566 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
567 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
David Majnemer081e8fe2015-12-27 06:07:12 +0000568 AddComment("Number of call sites");
Reid Kleckner14e77352015-10-09 23:34:53 +0000569 OS.EmitValue(EntryCount, 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000570
Reid Kleckner14e77352015-10-09 23:34:53 +0000571 OS.EmitLabel(TableBegin);
Reid Klecknereb7cd6c2015-10-09 23:05:54 +0000572
Reid Kleckner14e77352015-10-09 23:34:53 +0000573 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
574 // models exceptions from invokes. LLVM also allows arbitrary reordering of
575 // the code, so our tables end up looking a bit different. Rather than
576 // trying to match MSVC's tables exactly, we emit a denormalized table. For
577 // each range of invokes in the same state, we emit table entries for all
578 // the actions that would be taken in that state. This means our tables are
579 // slightly bigger, which is OK.
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000580 const MCSymbol *LastStartLabel = nullptr;
581 int LastEHState = -1;
582 // Break out before we enter into a finally funclet.
583 // FIXME: We need to emit separate EH tables for cleanups.
584 MachineFunction::const_iterator End = MF->end();
585 MachineFunction::const_iterator Stop = std::next(MF->begin());
586 while (Stop != End && !Stop->isEHFuncletEntry())
587 ++Stop;
588 for (const auto &StateChange :
589 InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
590 // Emit all the actions for the state we just transitioned out of
591 // if it was not the null state
592 if (LastEHState != -1)
593 emitSEHActionsForRange(FuncInfo, LastStartLabel,
594 StateChange.PreviousEndLabel, LastEHState);
595 LastStartLabel = StateChange.NewStartLabel;
596 LastEHState = StateChange.NewState;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000597 }
Reid Kleckner14e77352015-10-09 23:34:53 +0000598
Reid Kleckner14e77352015-10-09 23:34:53 +0000599 OS.EmitLabel(TableEnd);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000600}
David Majnemercde33032015-03-30 22:58:10 +0000601
Reid Klecknerc20276d2015-11-17 21:10:25 +0000602void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000603 const MCSymbol *BeginLabel,
604 const MCSymbol *EndLabel, int State) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000605 auto &OS = *Asm->OutStreamer;
606 MCContext &Ctx = Asm->OutContext;
David Majnemer081e8fe2015-12-27 06:07:12 +0000607 bool VerboseAsm = OS.isVerboseAsm();
608 auto AddComment = [&](const Twine &Comment) {
609 if (VerboseAsm)
610 OS.AddComment(Comment);
611 };
612
Reid Klecknerd880dc72015-10-09 20:39:39 +0000613 assert(BeginLabel && EndLabel);
614 while (State != -1) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000615 const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
Reid Klecknerd880dc72015-10-09 20:39:39 +0000616 const MCExpr *FilterOrFinally;
617 const MCExpr *ExceptOrNull;
618 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
619 if (UME.IsFinally) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000620 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
Reid Klecknerd880dc72015-10-09 20:39:39 +0000621 ExceptOrNull = MCConstantExpr::create(0, Ctx);
622 } else {
623 // For an except, the filter can be 1 (catch-all) or a function
624 // label.
625 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
626 : MCConstantExpr::create(1, Ctx);
627 ExceptOrNull = create32bitRef(Handler->getSymbol());
628 }
629
David Majnemer081e8fe2015-12-27 06:07:12 +0000630 AddComment("LabelStart");
Sanjin Sijaric96f2ea32018-10-27 06:13:06 +0000631 OS.EmitValue(getLabel(BeginLabel), 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000632 AddComment("LabelEnd");
Sanjin Sijaric96f2ea32018-10-27 06:13:06 +0000633 OS.EmitValue(getLabel(EndLabel), 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000634 AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
635 : "CatchAll");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000636 OS.EmitValue(FilterOrFinally, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +0000637 AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
Reid Klecknerd880dc72015-10-09 20:39:39 +0000638 OS.EmitValue(ExceptOrNull, 4);
639
640 assert(UME.ToState < State && "states should decrease");
641 State = UME.ToState;
642 }
643}
644
Reid Kleckner60b640b2015-05-28 22:47:01 +0000645void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000646 const Function &F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000647 auto &OS = *Asm->OutStreamer;
Reid Klecknerc20276d2015-11-17 21:10:25 +0000648 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
David Majnemercde33032015-03-30 22:58:10 +0000649
Matthias Braunf1caa282017-12-15 22:22:58 +0000650 StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
David Majnemercde33032015-03-30 22:58:10 +0000651
Reid Klecknerc71d6272015-09-28 23:56:30 +0000652 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000653 MCSymbol *FuncInfoXData = nullptr;
654 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000655 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
656 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000657 FuncInfoXData =
658 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000659 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000660 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000661 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000662 }
663
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000664 int UnwindHelpOffset = 0;
665 if (Asm->MAI->usesWindowsCFI())
Reid Kleckner6ddae312015-11-05 21:09:49 +0000666 UnwindHelpOffset =
667 getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000668
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000669 MCSymbol *UnwindMapXData = nullptr;
670 MCSymbol *TryBlockMapXData = nullptr;
671 MCSymbol *IPToStateXData = nullptr;
Reid Kleckner14e77352015-10-09 23:34:53 +0000672 if (!FuncInfo.CxxUnwindMap.empty())
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000673 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000674 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000675 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000676 TryBlockMapXData =
677 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000678 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000679 IPToStateXData =
680 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000681
David Majnemer081e8fe2015-12-27 06:07:12 +0000682 bool VerboseAsm = OS.isVerboseAsm();
683 auto AddComment = [&](const Twine &Comment) {
684 if (VerboseAsm)
685 OS.AddComment(Comment);
686 };
687
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000688 // FuncInfo {
689 // uint32_t MagicNumber
690 // int32_t MaxState;
691 // UnwindMapEntry *UnwindMap;
692 // uint32_t NumTryBlocks;
693 // TryBlockMapEntry *TryBlockMap;
694 // uint32_t IPMapEntries; // always 0 for x86
695 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
696 // uint32_t UnwindHelp; // non-x86 only
697 // ESTypeList *ESTypeList;
698 // int32_t EHFlags;
699 // }
700 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
701 // EHFlags & 2 -> ???
702 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000703 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000704 OS.EmitLabel(FuncInfoXData);
David Majnemer081e8fe2015-12-27 06:07:12 +0000705
706 AddComment("MagicNumber");
707 OS.EmitIntValue(0x19930522, 4);
708
709 AddComment("MaxState");
710 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
711
712 AddComment("UnwindMap");
713 OS.EmitValue(create32bitRef(UnwindMapXData), 4);
714
715 AddComment("NumTryBlocks");
716 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
717
718 AddComment("TryBlockMap");
719 OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
720
721 AddComment("IPMapEntries");
722 OS.EmitIntValue(IPToStateTable.size(), 4);
723
724 AddComment("IPToStateXData");
725 OS.EmitValue(create32bitRef(IPToStateXData), 4);
726
727 if (Asm->MAI->usesWindowsCFI()) {
728 AddComment("UnwindHelp");
729 OS.EmitIntValue(UnwindHelpOffset, 4);
730 }
731
732 AddComment("ESTypeList");
733 OS.EmitIntValue(0, 4);
734
735 AddComment("EHFlags");
736 OS.EmitIntValue(1, 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000737
738 // UnwindMapEntry {
739 // int32_t ToState;
740 // void (*Action)();
741 // };
742 if (UnwindMapXData) {
743 OS.EmitLabel(UnwindMapXData);
Reid Kleckner14e77352015-10-09 23:34:53 +0000744 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000745 MCSymbol *CleanupSym =
746 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
David Majnemer081e8fe2015-12-27 06:07:12 +0000747 AddComment("ToState");
748 OS.EmitIntValue(UME.ToState, 4);
749
750 AddComment("Action");
751 OS.EmitValue(create32bitRef(CleanupSym), 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000752 }
753 }
754
755 // TryBlockMap {
756 // int32_t TryLow;
757 // int32_t TryHigh;
758 // int32_t CatchHigh;
759 // int32_t NumCatches;
760 // HandlerType *HandlerArray;
761 // };
762 if (TryBlockMapXData) {
763 OS.EmitLabel(TryBlockMapXData);
764 SmallVector<MCSymbol *, 1> HandlerMaps;
765 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000766 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000767
Reid Kleckner813f1b62015-09-16 22:14:46 +0000768 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000769 if (!TBME.HandlerArray.empty())
770 HandlerMapXData =
771 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
772 .concat(Twine(I))
773 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000774 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000775 HandlerMaps.push_back(HandlerMapXData);
776
Reid Kleckner813f1b62015-09-16 22:14:46 +0000777 // TBMEs should form intervals.
778 assert(0 <= TBME.TryLow && "bad trymap interval");
779 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
780 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
Reid Kleckner14e77352015-10-09 23:34:53 +0000781 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
Reid Kleckner813f1b62015-09-16 22:14:46 +0000782 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000783
David Majnemer081e8fe2015-12-27 06:07:12 +0000784 AddComment("TryLow");
785 OS.EmitIntValue(TBME.TryLow, 4);
786
787 AddComment("TryHigh");
788 OS.EmitIntValue(TBME.TryHigh, 4);
789
790 AddComment("CatchHigh");
791 OS.EmitIntValue(TBME.CatchHigh, 4);
792
793 AddComment("NumCatches");
794 OS.EmitIntValue(TBME.HandlerArray.size(), 4);
795
796 AddComment("HandlerArray");
797 OS.EmitValue(create32bitRef(HandlerMapXData), 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000798 }
799
Reid Kleckner28e49032015-10-16 23:43:27 +0000800 // All funclets use the same parent frame offset currently.
801 unsigned ParentFrameOffset = 0;
802 if (shouldEmitPersonality) {
803 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
804 ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
805 }
806
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000807 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
Reid Klecknerc20276d2015-11-17 21:10:25 +0000808 const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000809 MCSymbol *HandlerMapXData = HandlerMaps[I];
810 if (!HandlerMapXData)
811 continue;
812 // HandlerType {
813 // int32_t Adjectives;
814 // TypeDescriptor *Type;
815 // int32_t CatchObjOffset;
816 // void (*Handler)();
Sanjin Sijaric96f2ea32018-10-27 06:13:06 +0000817 // int32_t ParentFrameOffset; // x64 and AArch64 only
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000818 // };
819 OS.EmitLabel(HandlerMapXData);
820 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
821 // Get the frame escape label with the offset of the catch object. If
David Majnemer99c1d132015-10-12 16:44:22 +0000822 // the index is INT_MAX, then there is no catch object, and we should
823 // emit an offset of zero, indicating that no copy will occur.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000824 const MCExpr *FrameAllocOffsetRef = nullptr;
David Majnemer99c1d132015-10-12 16:44:22 +0000825 if (HT.CatchObj.FrameIndex != INT_MAX) {
Reid Kleckner6ddae312015-11-05 21:09:49 +0000826 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
David Majnemercb305de2016-03-01 04:30:16 +0000827 assert(Offset != 0 && "Illegal offset for catch object!");
Reid Klecknerb005d282015-09-16 20:16:27 +0000828 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000829 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000830 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000831 }
832
David Majnemerbfa5b982015-10-10 00:04:29 +0000833 MCSymbol *HandlerSym =
834 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
Reid Kleckner94b704c2015-09-09 21:10:03 +0000835
David Majnemer081e8fe2015-12-27 06:07:12 +0000836 AddComment("Adjectives");
837 OS.EmitIntValue(HT.Adjectives, 4);
838
839 AddComment("Type");
840 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
841
842 AddComment("CatchObjOffset");
843 OS.EmitValue(FrameAllocOffsetRef, 4);
844
845 AddComment("Handler");
846 OS.EmitValue(create32bitRef(HandlerSym), 4);
847
848 if (shouldEmitPersonality) {
849 AddComment("ParentFrameOffset");
850 OS.EmitIntValue(ParentFrameOffset, 4);
851 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000852 }
853 }
854 }
855
856 // IPToStateMapEntry {
857 // void *IP;
858 // int32_t State;
859 // };
860 if (IPToStateXData) {
861 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000862 for (auto &IPStatePair : IPToStateTable) {
David Majnemer081e8fe2015-12-27 06:07:12 +0000863 AddComment("IP");
864 OS.EmitValue(IPStatePair.first, 4);
865 AddComment("ToState");
866 OS.EmitIntValue(IPStatePair.second, 4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000867 }
868 }
869}
870
Reid Klecknerc71d6272015-09-28 23:56:30 +0000871void WinException::computeIP2StateTable(
Reid Klecknerc20276d2015-11-17 21:10:25 +0000872 const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
Reid Klecknerc71d6272015-09-28 23:56:30 +0000873 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000874
David Majnemer8a1c45d2015-12-12 05:38:55 +0000875 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
876 FuncletEnd = MF->begin(),
877 End = MF->end();
878 FuncletStart != End; FuncletStart = FuncletEnd) {
879 // Find the end of the funclet
880 while (++FuncletEnd != End) {
881 if (FuncletEnd->isEHFuncletEntry()) {
882 break;
883 }
884 }
885
886 // Don't emit ip2state entries for cleanup funclets. Any interesting
887 // exceptional actions in cleanups must be handled in a separate IR
888 // function.
889 if (FuncletStart->isCleanupFuncletEntry())
890 continue;
891
892 MCSymbol *StartLabel;
893 int BaseState;
894 if (FuncletStart == MF->begin()) {
895 BaseState = NullState;
896 StartLabel = Asm->getFunctionBegin();
897 } else {
898 auto *FuncletPad =
899 cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
900 assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
901 BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
902 StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
903 }
904 assert(StartLabel && "need local function start label");
Joseph Tremoulet1e2f0622015-10-13 16:44:30 +0000905 IPToStateTable.push_back(
David Majnemer8a1c45d2015-12-12 05:38:55 +0000906 std::make_pair(create32bitRef(StartLabel), BaseState));
907
908 for (const auto &StateChange : InvokeStateChangeIterator::range(
909 FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
910 // Compute the label to report as the start of this entry; use the EH
911 // start label for the invoke if we have one, otherwise (this is a call
912 // which may unwind to our caller and does not have an EH start label, so)
913 // use the previous end label.
914 const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
915 if (!ChangeLabel)
916 ChangeLabel = StateChange.PreviousEndLabel;
917 // Emit an entry indicating that PCs after 'Label' have this EH state.
918 IPToStateTable.push_back(
Sanjin Sijaric96f2ea32018-10-27 06:13:06 +0000919 std::make_pair(getLabel(ChangeLabel), StateChange.NewState));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000920 // FIXME: assert that NewState is between CatchLow and CatchHigh.
921 }
Reid Klecknerc71d6272015-09-28 23:56:30 +0000922 }
David Majnemercde33032015-03-30 22:58:10 +0000923}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000924
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000925void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
926 StringRef FLinkageName) {
927 // Outlined helpers called by the EH runtime need to know the offset of the EH
928 // registration in order to recover the parent frame pointer. Now that we know
929 // we've code generated the parent, we can emit the label assignment that
930 // those helpers use to get the offset of the registration node.
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000931
932 // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
933 // after optimization all the invokes were eliminated. We still need to emit
934 // the parent frame offset label, but it should be garbage and should never be
935 // used.
936 int64_t Offset = 0;
937 int FI = FuncInfo.EHRegNodeFrameIndex;
938 if (FI != INT_MAX) {
939 const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
940 unsigned UnusedReg;
Mandeep Singh Grang33c49c02019-01-16 19:52:59 +0000941 // FIXME: getFrameIndexReference needs to match the behavior of
942 // AArch64RegisterInfo::hasBasePointer in which one of the scenarios where
943 // SP is used is if frame size >= 256.
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000944 Offset = TFI->getFrameIndexReference(*Asm->MF, FI, UnusedReg);
945 }
946
Reid Klecknerc20276d2015-11-17 21:10:25 +0000947 MCContext &Ctx = Asm->OutContext;
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000948 MCSymbol *ParentFrameOffset =
Reid Klecknerc20276d2015-11-17 21:10:25 +0000949 Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
Reid Kleckner9cb915b2016-09-30 22:10:12 +0000950 Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
951 MCConstantExpr::create(Offset, Ctx));
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000952}
953
Reid Klecknerf12c0302015-06-09 21:42:19 +0000954/// Emit the language-specific data that _except_handler3 and 4 expect. This is
955/// functionally equivalent to the __C_specific_handler table, except it is
956/// indexed by state number instead of IP.
957void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000958 MCStreamer &OS = *Asm->OutStreamer;
Matthias Braunf1caa282017-12-15 22:22:58 +0000959 const Function &F = MF->getFunction();
960 StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000961
David Majnemer081e8fe2015-12-27 06:07:12 +0000962 bool VerboseAsm = OS.isVerboseAsm();
963 auto AddComment = [&](const Twine &Comment) {
964 if (VerboseAsm)
965 OS.AddComment(Comment);
966 };
967
Reid Klecknerc20276d2015-11-17 21:10:25 +0000968 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000969 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000970
971 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000972 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000973 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000974 OS.EmitLabel(LSDALabel);
975
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000976 const Function *Per =
Matthias Braunf1caa282017-12-15 22:22:58 +0000977 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000978 StringRef PerName = Per->getName();
979 int BaseState = -1;
980 if (PerName == "_except_handler4") {
981 // The LSDA for _except_handler4 starts with this struct, followed by the
982 // scope table:
983 //
984 // struct EH4ScopeTable {
985 // int32_t GSCookieOffset;
986 // int32_t GSCookieXOROffset;
987 // int32_t EHCookieOffset;
988 // int32_t EHCookieXOROffset;
989 // ScopeTableEntry ScopeRecord[];
990 // };
991 //
Etienne Bergeronf6be62f2016-06-21 15:58:55 +0000992 // Offsets are %ebp relative.
993 //
994 // The GS cookie is present only if the function needs stack protection.
995 // GSCookieOffset = -2 means that GS cookie is not used.
996 //
997 // The EH cookie is always present.
998 //
999 // Check is done the following way:
1000 // (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
1001
1002 // Retrieve the Guard Stack slot.
1003 int GSCookieOffset = -2;
Matthias Braun941a7052016-07-28 18:40:00 +00001004 const MachineFrameInfo &MFI = MF->getFrameInfo();
1005 if (MFI.hasStackProtectorIndex()) {
Etienne Bergeronf6be62f2016-06-21 15:58:55 +00001006 unsigned UnusedReg;
1007 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +00001008 int SSPIdx = MFI.getStackProtectorIndex();
Etienne Bergeronf6be62f2016-06-21 15:58:55 +00001009 GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
1010 }
1011
1012 // Retrieve the EH Guard slot.
1013 // TODO(etienneb): Get rid of this value and change it for and assertion.
1014 int EHCookieOffset = 9999;
1015 if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
1016 unsigned UnusedReg;
1017 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1018 int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
1019 EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
1020 }
1021
David Majnemer081e8fe2015-12-27 06:07:12 +00001022 AddComment("GSCookieOffset");
Etienne Bergeronf6be62f2016-06-21 15:58:55 +00001023 OS.EmitIntValue(GSCookieOffset, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001024 AddComment("GSCookieXOROffset");
Reid Klecknerf12c0302015-06-09 21:42:19 +00001025 OS.EmitIntValue(0, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001026 AddComment("EHCookieOffset");
Etienne Bergeronf6be62f2016-06-21 15:58:55 +00001027 OS.EmitIntValue(EHCookieOffset, 4);
David Majnemer081e8fe2015-12-27 06:07:12 +00001028 AddComment("EHCookieXOROffset");
Reid Klecknerf12c0302015-06-09 21:42:19 +00001029 OS.EmitIntValue(0, 4);
1030 BaseState = -2;
1031 }
1032
Reid Kleckner14e77352015-10-09 23:34:53 +00001033 assert(!FuncInfo.SEHUnwindMap.empty());
Reid Klecknerc20276d2015-11-17 21:10:25 +00001034 for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
David Majnemer081e8fe2015-12-27 06:07:12 +00001035 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
1036 const MCSymbol *ExceptOrFinally =
1037 UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
Reid Kleckner14e77352015-10-09 23:34:53 +00001038 // -1 is usually the base state for "unwind to caller", but for
1039 // _except_handler4 it's -2. Do that replacement here if necessary.
1040 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
David Majnemer081e8fe2015-12-27 06:07:12 +00001041 AddComment("ToState");
1042 OS.EmitIntValue(ToState, 4);
1043 AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1044 OS.EmitValue(create32bitRef(UME.Filter), 4);
1045 AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1046 OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001047 }
1048}
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001049
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001050static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001051 int Rank = 0;
1052 while (State != -1) {
1053 ++Rank;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001054 State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001055 }
1056 return Rank;
1057}
1058
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001059static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
1060 int LeftRank = getTryRank(FuncInfo, Left);
1061 int RightRank = getTryRank(FuncInfo, Right);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001062
1063 while (LeftRank < RightRank) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001064 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001065 --RightRank;
1066 }
1067
1068 while (RightRank < LeftRank) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001069 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001070 --LeftRank;
1071 }
1072
1073 while (Left != Right) {
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001074 Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1075 Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001076 }
1077
1078 return Left;
1079}
1080
1081void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
1082 // CLR EH "states" are really just IDs that identify handlers/funclets;
1083 // states, handlers, and funclets all have 1:1 mappings between them, and a
1084 // handler/funclet's "state" is its index in the ClrEHUnwindMap.
1085 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknerc20276d2015-11-17 21:10:25 +00001086 const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001087 MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
1088 MCSymbol *FuncEndSym = Asm->getFunctionEnd();
1089
1090 // A ClrClause describes a protected region.
1091 struct ClrClause {
1092 const MCSymbol *StartLabel; // Start of protected region
1093 const MCSymbol *EndLabel; // End of protected region
1094 int State; // Index of handler protecting the protected region
1095 int EnclosingState; // Index of funclet enclosing the protected region
1096 };
1097 SmallVector<ClrClause, 8> Clauses;
1098
1099 // Build a map from handler MBBs to their corresponding states (i.e. their
1100 // indices in the ClrEHUnwindMap).
1101 int NumStates = FuncInfo.ClrEHUnwindMap.size();
1102 assert(NumStates > 0 && "Don't need exception table!");
1103 DenseMap<const MachineBasicBlock *, int> HandlerStates;
1104 for (int State = 0; State < NumStates; ++State) {
1105 MachineBasicBlock *HandlerBlock =
1106 FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
1107 HandlerStates[HandlerBlock] = State;
1108 // Use this loop through all handlers to verify our assumption (used in
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001109 // the MinEnclosingState computation) that enclosing funclets have lower
1110 // state numbers than their enclosed funclets.
1111 assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001112 "ill-formed state numbering");
1113 }
1114 // Map the main function to the NullState.
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001115 HandlerStates[&MF->front()] = NullState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001116
1117 // Write out a sentinel indicating the end of the standard (Windows) xdata
1118 // and the start of the additional (CLR) info.
1119 OS.EmitIntValue(0xffffffff, 4);
1120 // Write out the number of funclets
1121 OS.EmitIntValue(NumStates, 4);
1122
1123 // Walk the machine blocks/instrs, computing and emitting a few things:
1124 // 1. Emit a list of the offsets to each handler entry, in lexical order.
1125 // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
1126 // 3. Compute the list of ClrClauses, in the required order (inner before
1127 // outer, earlier before later; the order by which a forward scan with
1128 // early termination will find the innermost enclosing clause covering
1129 // a given address).
1130 // 4. A map (MinClauseMap) from each handler index to the index of the
1131 // outermost funclet/function which contains a try clause targeting the
1132 // key handler. This will be used to determine IsDuplicate-ness when
1133 // emitting ClrClauses. The NullState value is used to indicate that the
1134 // top-level function contains a try clause targeting the key handler.
1135 // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
1136 // try regions we entered before entering the PendingState try but which
1137 // we haven't yet exited.
1138 SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
1139 // EndSymbolMap and MinClauseMap are maps described above.
1140 std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
1141 SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
1142
1143 // Visit the root function and each funclet.
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001144 for (MachineFunction::const_iterator FuncletStart = MF->begin(),
1145 FuncletEnd = MF->begin(),
1146 End = MF->end();
1147 FuncletStart != End; FuncletStart = FuncletEnd) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001148 int FuncletState = HandlerStates[&*FuncletStart];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001149 // Find the end of the funclet
1150 MCSymbol *EndSymbol = FuncEndSym;
1151 while (++FuncletEnd != End) {
1152 if (FuncletEnd->isEHFuncletEntry()) {
Duncan P. N. Exon Smitha25ad062015-10-20 00:36:08 +00001153 EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001154 break;
1155 }
1156 }
1157 // Emit the function/funclet end and, if this is a funclet (and not the
1158 // root function), record it in the EndSymbolMap.
1159 OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
1160 if (FuncletState != NullState) {
1161 // Record the end of the handler.
1162 EndSymbolMap[FuncletState] = EndSymbol;
1163 }
1164
1165 // Walk the state changes in this function/funclet and compute its clauses.
1166 // Funclets always start in the null state.
1167 const MCSymbol *CurrentStartLabel = nullptr;
1168 int CurrentState = NullState;
1169 assert(HandlerStack.empty());
1170 for (const auto &StateChange :
1171 InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
1172 // Close any try regions we're not still under
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001173 int StillPendingState =
1174 getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
1175 while (CurrentState != StillPendingState) {
1176 assert(CurrentState != NullState &&
1177 "Failed to find still-pending state!");
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001178 // Close the pending clause
1179 Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
1180 CurrentState, FuncletState});
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001181 // Now the next-outer try region is current
1182 CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001183 // Pop the new start label from the handler stack if we've exited all
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001184 // inner try regions of the corresponding try region.
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001185 if (HandlerStack.back().second == CurrentState)
1186 CurrentStartLabel = HandlerStack.pop_back_val().first;
1187 }
1188
1189 if (StateChange.NewState != CurrentState) {
1190 // For each clause we're starting, update the MinClauseMap so we can
1191 // know which is the topmost funclet containing a clause targeting
1192 // it.
1193 for (int EnteredState = StateChange.NewState;
1194 EnteredState != CurrentState;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +00001195 EnteredState =
1196 FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001197 int &MinEnclosingState = MinClauseMap[EnteredState];
1198 if (FuncletState < MinEnclosingState)
1199 MinEnclosingState = FuncletState;
1200 }
1201 // Save the previous current start/label on the stack and update to
1202 // the newly-current start/state.
1203 HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
1204 CurrentStartLabel = StateChange.NewStartLabel;
1205 CurrentState = StateChange.NewState;
1206 }
1207 }
1208 assert(HandlerStack.empty());
1209 }
1210
1211 // Now emit the clause info, starting with the number of clauses.
1212 OS.EmitIntValue(Clauses.size(), 4);
1213 for (ClrClause &Clause : Clauses) {
1214 // Emit a CORINFO_EH_CLAUSE :
1215 /*
1216 struct CORINFO_EH_CLAUSE
1217 {
1218 CORINFO_EH_CLAUSE_FLAGS Flags; // actually a CorExceptionFlag
1219 DWORD TryOffset;
1220 DWORD TryLength; // actually TryEndOffset
1221 DWORD HandlerOffset;
1222 DWORD HandlerLength; // actually HandlerEndOffset
1223 union
1224 {
1225 DWORD ClassToken; // use for catch clauses
1226 DWORD FilterOffset; // use for filter clauses
1227 };
1228 };
1229
1230 enum CORINFO_EH_CLAUSE_FLAGS
1231 {
1232 CORINFO_EH_CLAUSE_NONE = 0,
1233 CORINFO_EH_CLAUSE_FILTER = 0x0001, // This clause is for a filter
1234 CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1235 CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
1236 };
1237 typedef enum CorExceptionFlag
1238 {
1239 COR_ILEXCEPTION_CLAUSE_NONE,
1240 COR_ILEXCEPTION_CLAUSE_FILTER = 0x0001, // This is a filter clause
1241 COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1242 COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004, // This is a fault clause
1243 COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1244 // clause was duplicated
1245 // to a funclet which was
1246 // pulled out of line
1247 } CorExceptionFlag;
1248 */
1249 // Add 1 to the start/end of the EH clause; the IP associated with a
1250 // call when the runtime does its scan is the IP of the next instruction
1251 // (the one to which control will return after the call), so we need
1252 // to add 1 to the end of the clause to cover that offset. We also add
1253 // 1 to the start of the clause to make sure that the ranges reported
1254 // for all clauses are disjoint. Note that we'll need some additional
1255 // logic when machine traps are supported, since in that case the IP
1256 // that the runtime uses is the offset of the faulting instruction
1257 // itself; if such an instruction immediately follows a call but the
1258 // two belong to different clauses, we'll need to insert a nop between
1259 // them so the runtime can distinguish the point to which the call will
1260 // return from the point at which the fault occurs.
1261
1262 const MCExpr *ClauseBegin =
1263 getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
1264 const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1265
Reid Klecknerc20276d2015-11-17 21:10:25 +00001266 const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
Joseph Tremoulet28c89bb2015-10-13 20:18:27 +00001267 MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
1268 MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1269 const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1270 MCSymbol *EndSym = EndSymbolMap[Clause.State];
1271 const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1272
1273 uint32_t Flags = 0;
1274 switch (Entry.HandlerType) {
1275 case ClrHandlerType::Catch:
1276 // Leaving bits 0-2 clear indicates catch.
1277 break;
1278 case ClrHandlerType::Filter:
1279 Flags |= 1;
1280 break;
1281 case ClrHandlerType::Finally:
1282 Flags |= 2;
1283 break;
1284 case ClrHandlerType::Fault:
1285 Flags |= 4;
1286 break;
1287 }
1288 if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1289 // This is a "duplicate" clause; the handler needs to be entered from a
1290 // frame above the one holding the invoke.
1291 assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1292 Flags |= 8;
1293 }
1294 OS.EmitIntValue(Flags, 4);
1295
1296 // Write the clause start/end
1297 OS.EmitValue(ClauseBegin, 4);
1298 OS.EmitValue(ClauseEnd, 4);
1299
1300 // Write out the handler start/end
1301 OS.EmitValue(HandlerBegin, 4);
1302 OS.EmitValue(HandlerEnd, 4);
1303
1304 // Write out the type token or filter offset
1305 assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1306 OS.EmitIntValue(Entry.TypeToken, 4);
1307 }
1308}