blob: 86e6881e892cd73ebae8ebc0c528291fc867cdc9 [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//
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
Reid Kleckner60b640b2015-05-28 22:47:01 +000014#include "WinException.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallString.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/ADT/Twine.h"
Charles Davis91ed7992011-05-27 23:47:32 +000018#include "llvm/CodeGen/AsmPrinter.h"
Charles Davis91ed7992011-05-27 23:47:32 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000022#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000024#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Module.h"
Charles Davis91ed7992011-05-27 23:47:32 +000026#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCExpr.h"
29#include "llvm/MC/MCSection.h"
30#include "llvm/MC/MCStreamer.h"
31#include "llvm/MC/MCSymbol.h"
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000032#include "llvm/MC/MCWin64EH.h"
David Majnemera80c1512015-09-29 20:12:33 +000033#include "llvm/Support/COFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/Dwarf.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/FormattedStream.h"
Charles Davis91ed7992011-05-27 23:47:32 +000037#include "llvm/Target/TargetFrameLowering.h"
38#include "llvm/Target/TargetLoweringObjectFile.h"
Charles Davis91ed7992011-05-27 23:47:32 +000039#include "llvm/Target/TargetOptions.h"
40#include "llvm/Target/TargetRegisterInfo.h"
Reid Kleckner70bf6bb2015-10-07 21:13:15 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Charles Davis91ed7992011-05-27 23:47:32 +000042using namespace llvm;
43
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000044WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
45 // MSVC's EH tables are always composed of 32-bit words. All known 64-bit
46 // platforms use an imagerel32 relocation to refer to symbols.
47 useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
48}
Charles Davis91ed7992011-05-27 23:47:32 +000049
Reid Kleckner60b640b2015-05-28 22:47:01 +000050WinException::~WinException() {}
Charles Davis91ed7992011-05-27 23:47:32 +000051
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000052/// endModule - Emit all exception information that should come after the
Charles Davis91ed7992011-05-27 23:47:32 +000053/// content.
Reid Kleckner60b640b2015-05-28 22:47:01 +000054void WinException::endModule() {
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000055 auto &OS = *Asm->OutStreamer;
56 const Module *M = MMI->getModule();
Reid Klecknerca6ef662015-06-10 01:13:44 +000057 for (const Function &F : *M)
58 if (F.hasFnAttribute("safeseh"))
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000059 OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
Charles Davis91ed7992011-05-27 23:47:32 +000060}
61
Reid Kleckner60b640b2015-05-28 22:47:01 +000062void WinException::beginFunction(const MachineFunction *MF) {
Charles Davis5638b9f2011-05-28 04:21:04 +000063 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
64
65 // If any landing pads survive, we need an EH table.
66 bool hasLandingPads = !MMI->getLandingPads().empty();
Reid Kleckner0e288232015-08-27 23:27:47 +000067 bool hasEHFunclets = MMI->hasEHFunclets();
Charles Davis5638b9f2011-05-28 04:21:04 +000068
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000069 const Function *F = MF->getFunction();
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000070
Charles Davis5638b9f2011-05-28 04:21:04 +000071 shouldEmitMoves = Asm->needsSEHMoves();
72
73 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
74 unsigned PerEncoding = TLOF.getPersonalityEncoding();
Reid Kleckner9a1a9192015-07-13 20:41:46 +000075 const Function *Per = nullptr;
76 if (F->hasPersonalityFn())
77 Per = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Charles Davis5638b9f2011-05-28 04:21:04 +000078
Keno Fischeraff703a2015-07-14 19:22:51 +000079 bool forceEmitPersonality =
80 F->hasPersonalityFn() && !isNoOpWithoutInvoke(classifyEHPersonality(Per)) &&
81 F->needsUnwindTableEntry();
82
Reid Kleckner0e288232015-08-27 23:27:47 +000083 shouldEmitPersonality =
84 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
85 PerEncoding != dwarf::DW_EH_PE_omit && Per);
Charles Davis5638b9f2011-05-28 04:21:04 +000086
87 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
88 shouldEmitLSDA = shouldEmitPersonality &&
89 LSDAEncoding != dwarf::DW_EH_PE_omit;
90
Reid Kleckner0e288232015-08-27 23:27:47 +000091 // If we're not using CFI, we don't want the CFI or the personality, but we
92 // might want EH tables if we had EH pads.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000093 if (!Asm->MAI->usesWindowsCFI()) {
David Majnemerbfa5b982015-10-10 00:04:29 +000094 shouldEmitLSDA = hasEHFunclets;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000095 shouldEmitPersonality = false;
96 return;
97 }
David Majnemera225a192015-03-31 22:35:44 +000098
David Majnemera80c1512015-09-29 20:12:33 +000099 beginFunclet(MF->front(), Asm->CurrentFnSym);
Charles Davis91ed7992011-05-27 23:47:32 +0000100}
101
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000102/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000103///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000104void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000105 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000106 return;
107
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000108 const Function *F = MF->getFunction();
109 EHPersonality Per = EHPersonality::Unknown;
110 if (F->hasPersonalityFn())
111 Per = classifyEHPersonality(F->getPersonalityFn());
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000112
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000113 // Get rid of any dead landing pads if we're not using funclets. In funclet
114 // schemes, the landing pad is not actually reachable. It only exists so
115 // that we can emit the right table data.
116 if (!isFuncletEHPersonality(Per))
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000117 MMI->TidyLandingPads();
Charles Davisa5752262011-05-30 00:13:34 +0000118
David Majnemera80c1512015-09-29 20:12:33 +0000119 endFunclet();
120
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000121 // endFunclet will emit the necessary .xdata tables for x64 SEH.
122 if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
123 return;
124
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000125 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000126 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000127
David Majnemera80c1512015-09-29 20:12:33 +0000128 // Just switch sections to the right xdata section. This use of CurrentFnSym
129 // assumes that we only emit the LSDA when ending the parent function.
130 MCSection *XData = WinEH::UnwindEmitter::getXDataSection(Asm->CurrentFnSym,
131 Asm->OutContext);
132 Asm->OutStreamer->SwitchSection(XData);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000133
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000134 // Emit the tables appropriate to the personality function in use. If we
135 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000136 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000137 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000138 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000139 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000140 else if (Per == EHPersonality::MSVC_CXX)
141 emitCXXFrameHandler3Table(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000142 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000143 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000144
Lang Hames9ff69c82015-04-24 19:11:51 +0000145 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000146 }
David Majnemera80c1512015-09-29 20:12:33 +0000147}
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000148
David Majnemer99c1d132015-10-12 16:44:22 +0000149/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock.
David Majnemerbfa5b982015-10-10 00:04:29 +0000150static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
151 const MachineBasicBlock *MBB) {
152 if (!MBB)
David Majnemera80c1512015-09-29 20:12:33 +0000153 return nullptr;
David Majnemera80c1512015-09-29 20:12:33 +0000154
David Majnemerbfa5b982015-10-10 00:04:29 +0000155 assert(MBB->isEHFuncletEntry());
156
157 // Give catches and cleanups a name based off of their parent function and
158 // their funclet entry block's number.
159 const MachineFunction *MF = MBB->getParent();
160 const Function *F = MF->getFunction();
161 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
162 MCContext &Ctx = MF->getContext();
163 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
164 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
165 Twine(MBB->getNumber()) + "@?0?" +
166 FuncLinkageName + "@4HA");
David Majnemera80c1512015-09-29 20:12:33 +0000167}
168
169void WinException::beginFunclet(const MachineBasicBlock &MBB,
170 MCSymbol *Sym) {
171 CurrentFuncletEntry = &MBB;
172
173 const Function *F = Asm->MF->getFunction();
174 // If a symbol was not provided for the funclet, invent one.
175 if (!Sym) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000176 Sym = getMCSymbolForMBB(Asm, &MBB);
David Majnemera80c1512015-09-29 20:12:33 +0000177
178 // Describe our funclet symbol as a function with internal linkage.
179 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
180 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
181 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
182 << COFF::SCT_COMPLEX_TYPE_SHIFT);
183 Asm->OutStreamer->EndCOFFSymbolDef();
184
185 // We want our funclet's entry point to be aligned such that no nops will be
186 // present after the label.
187 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
188 F);
189
190 // Now that we've emitted the alignment directive, point at our funclet.
191 Asm->OutStreamer->EmitLabel(Sym);
192 }
193
194 // Mark 'Sym' as starting our funclet.
David Majnemer0e705982015-09-11 17:34:34 +0000195 if (shouldEmitMoves || shouldEmitPersonality)
David Majnemera80c1512015-09-29 20:12:33 +0000196 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
197
198 if (shouldEmitPersonality) {
199 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
200 const Function *PerFn = nullptr;
201
202 // Determine which personality routine we are using for this funclet.
203 if (F->hasPersonalityFn())
204 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
205 const MCSymbol *PersHandlerSym =
206 TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
207
208 // Classify the personality routine so that we may reason about it.
209 EHPersonality Per = EHPersonality::Unknown;
210 if (F->hasPersonalityFn())
211 Per = classifyEHPersonality(F->getPersonalityFn());
212
213 // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
214 if (Per != EHPersonality::MSVC_CXX ||
215 !CurrentFuncletEntry->isCleanupFuncletEntry())
216 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
217 }
218}
219
220void WinException::endFunclet() {
221 // No funclet to process? Great, we have nothing to do.
222 if (!CurrentFuncletEntry)
223 return;
224
225 if (shouldEmitMoves || shouldEmitPersonality) {
226 const Function *F = Asm->MF->getFunction();
227 EHPersonality Per = EHPersonality::Unknown;
228 if (F->hasPersonalityFn())
229 Per = classifyEHPersonality(F->getPersonalityFn());
230
231 // The .seh_handlerdata directive implicitly switches section, push the
232 // current section so that we may return to it.
233 Asm->OutStreamer->PushSection();
234
235 // Emit an UNWIND_INFO struct describing the prologue.
236 Asm->OutStreamer->EmitWinEHHandlerData();
237
David Majnemera80c1512015-09-29 20:12:33 +0000238 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
239 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000240 // If this is a C++ catch funclet (or the parent function),
241 // emit a reference to the LSDA for the parent function.
David Majnemera80c1512015-09-29 20:12:33 +0000242 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
243 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
244 Twine("$cppxdata$", FuncLinkageName));
245 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000246 } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
247 !CurrentFuncletEntry->isEHFuncletEntry()) {
248 // If this is the parent function in Win64 SEH, emit the LSDA immediately
249 // following .seh_handlerdata.
250 emitCSpecificHandlerTable(Asm->MF);
David Majnemera80c1512015-09-29 20:12:33 +0000251 }
252
253 // Switch back to the previous section now that we are done writing to
254 // .xdata.
255 Asm->OutStreamer->PopSection();
256
257 // Emit a .seh_endproc directive to mark the end of the function.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000258 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000259 }
260
261 // Let's make sure we don't try to end the same funclet twice.
262 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000263}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000264
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000265const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000266 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000267 return MCConstantExpr::create(0, Asm->OutContext);
268 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000269 ? MCSymbolRefExpr::VK_COFF_IMGREL32
270 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000271 Asm->OutContext);
272}
273
David Majnemer0ad363e2015-08-18 19:07:12 +0000274const MCExpr *WinException::create32bitRef(const Value *V) {
275 if (!V)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000276 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner0e288232015-08-27 23:27:47 +0000277 if (const auto *GV = dyn_cast<GlobalValue>(V))
278 return create32bitRef(Asm->getSymbol(GV));
279 return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
David Majnemercde33032015-03-30 22:58:10 +0000280}
281
Reid Klecknerc71d6272015-09-28 23:56:30 +0000282const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
283 return MCBinaryExpr::createAdd(create32bitRef(Label),
284 MCConstantExpr::create(1, Asm->OutContext),
285 Asm->OutContext);
286}
287
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000288int WinException::getFrameIndexOffset(int FrameIndex) {
289 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
290 unsigned UnusedReg;
291 if (Asm->MAI->usesWindowsCFI())
292 return TFI.getFrameIndexReferenceFromSP(*Asm->MF, FrameIndex, UnusedReg);
293 return TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
294}
295
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000296namespace {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000297/// Information describing an invoke range.
298struct InvokeRange {
299 MCSymbol *BeginLabel = nullptr;
300 MCSymbol *EndLabel = nullptr;
301 int State = -1;
302
303 /// If we saw a potentially throwing call between this range and the last
304 /// range.
305 bool SawPotentiallyThrowing = false;
306};
307
308/// Iterator over the begin/end label pairs of invokes within a basic block.
309class InvokeLabelIterator {
310public:
311 InvokeLabelIterator(WinEHFuncInfo &EHInfo,
312 MachineBasicBlock::const_iterator MBBI,
313 MachineBasicBlock::const_iterator MBBIEnd)
314 : EHInfo(EHInfo), MBBI(MBBI), MBBIEnd(MBBIEnd) {
315 scan();
316 }
317
318 // Iterator methods.
319 bool operator==(const InvokeLabelIterator &o) const { return MBBI == o.MBBI; }
320 bool operator!=(const InvokeLabelIterator &o) const { return MBBI != o.MBBI; }
321 InvokeRange &operator*() { return CurRange; }
322 InvokeRange *operator->() { return &CurRange; }
323 InvokeLabelIterator &operator++() { return scan(); }
324
325private:
326 // Scan forward to find the next invoke range, or hit the end iterator.
327 InvokeLabelIterator &scan();
328
329 WinEHFuncInfo &EHInfo;
330 MachineBasicBlock::const_iterator MBBI;
331 MachineBasicBlock::const_iterator MBBIEnd;
332 InvokeRange CurRange;
333};
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000334} // end anonymous namespace
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000335
336/// Invoke label range iteration logic. Increment MBBI until we find the next
337/// EH_LABEL pair, and then update MBBI to point after the end label.
338InvokeLabelIterator &InvokeLabelIterator::scan() {
339 // Reset our state.
340 CurRange = InvokeRange{};
341
342 for (const MachineInstr &MI : make_range(MBBI, MBBIEnd)) {
343 // Remember if we had to cross a potentially throwing call instruction that
344 // must unwind to caller.
345 if (MI.isCall()) {
346 CurRange.SawPotentiallyThrowing |=
347 !EHStreamer::callToNoUnwindFunction(&MI);
348 continue;
349 }
350 // Find the next EH_LABEL instruction.
351 if (!MI.isEHLabel())
352 continue;
353
354 // If this is a begin label, break out with the state and end label.
355 // Otherwise this is probably a CFI EH_LABEL that we should continue past.
356 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
357 auto StateAndEnd = EHInfo.InvokeToStateMap.find(Label);
358 if (StateAndEnd == EHInfo.InvokeToStateMap.end())
359 continue;
360 MBBI = MachineBasicBlock::const_iterator(&MI);
361 CurRange.BeginLabel = Label;
362 CurRange.EndLabel = StateAndEnd->second.second;
363 CurRange.State = StateAndEnd->second.first;
364 break;
365 }
366
367 // If we didn't find a begin label, we are done, return the end iterator.
368 if (!CurRange.BeginLabel) {
369 MBBI = MBBIEnd;
370 return *this;
371 }
372
373 // If this is a begin label, update MBBI to point past the end label.
374 for (; MBBI != MBBIEnd; ++MBBI)
375 if (MBBI->isEHLabel() &&
376 MBBI->getOperand(0).getMCSymbol() == CurRange.EndLabel)
377 break;
378 return *this;
379}
380
381/// Utility for making a range for all the invoke ranges.
382static iterator_range<InvokeLabelIterator>
383invoke_ranges(WinEHFuncInfo &EHInfo, const MachineBasicBlock &MBB) {
384 return make_range(InvokeLabelIterator(EHInfo, MBB.begin(), MBB.end()),
385 InvokeLabelIterator(EHInfo, MBB.end(), MBB.end()));
386}
387
Reid Kleckner0a57f652015-01-14 01:05:27 +0000388/// Emit the language-specific data that __C_specific_handler expects. This
389/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
390/// up after faults with __try, __except, and __finally. The typeinfo values
391/// are not really RTTI data, but pointers to filter functions that return an
392/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
393/// blocks and other cleanups, the landing pad label is zero, and the filter
394/// function is actually a cleanup handler with the same prototype. A catch-all
395/// entry is modeled with a null filter function field and a non-zero landing
396/// pad label.
397///
398/// Possible filter function return values:
399/// EXCEPTION_EXECUTE_HANDLER (1):
400/// Jump to the landing pad label after cleanups.
401/// EXCEPTION_CONTINUE_SEARCH (0):
402/// Continue searching this table or continue unwinding.
403/// EXCEPTION_CONTINUE_EXECUTION (-1):
404/// Resume execution at the trapping PC.
405///
406/// Inferred table structure:
407/// struct Table {
408/// int NumEntries;
409/// struct Entry {
410/// imagerel32 LabelStart;
411/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000412/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner14e77352015-10-09 23:34:53 +0000413/// imagerel32 LabelLPad; // Zero means __finally.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000414/// } Entries[NumEntries];
415/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000416void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000417 auto &OS = *Asm->OutStreamer;
418 MCContext &Ctx = Asm->OutContext;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000419
Reid Kleckner94b704c2015-09-09 21:10:03 +0000420 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000421
Reid Kleckner14e77352015-10-09 23:34:53 +0000422 // Remember what state we were in the last time we found a begin try label.
423 // This allows us to coalesce many nearby invokes with the same state into
424 // one entry.
425 int LastEHState = -1;
426 MCSymbol *LastBeginLabel = nullptr;
427 MCSymbol *LastEndLabel = nullptr;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000428
Reid Kleckner14e77352015-10-09 23:34:53 +0000429 // Use the assembler to compute the number of table entries through label
430 // difference and division.
431 MCSymbol *TableBegin =
432 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
433 MCSymbol *TableEnd =
434 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
435 const MCExpr *LabelDiff =
436 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TableEnd, Ctx),
437 MCSymbolRefExpr::create(TableBegin, Ctx), Ctx);
438 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
439 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
440 OS.EmitValue(EntryCount, 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000441
Reid Kleckner14e77352015-10-09 23:34:53 +0000442 OS.EmitLabel(TableBegin);
Reid Klecknereb7cd6c2015-10-09 23:05:54 +0000443
Reid Kleckner14e77352015-10-09 23:34:53 +0000444 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
445 // models exceptions from invokes. LLVM also allows arbitrary reordering of
446 // the code, so our tables end up looking a bit different. Rather than
447 // trying to match MSVC's tables exactly, we emit a denormalized table. For
448 // each range of invokes in the same state, we emit table entries for all
449 // the actions that would be taken in that state. This means our tables are
450 // slightly bigger, which is OK.
451 for (const auto &MBB : *MF) {
452 // Break out before we enter into a finally funclet.
453 // FIXME: We need to emit separate EH tables for cleanups.
454 if (MBB.isEHFuncletEntry() && &MBB != MF->begin())
455 break;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000456
Reid Kleckner14e77352015-10-09 23:34:53 +0000457 for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
458 // If this invoke is in the same state as the last invoke and there were
459 // no non-throwing calls between it, extend the range to include both
460 // and continue.
461 if (!I.SawPotentiallyThrowing && I.State == LastEHState) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000462 LastEndLabel = I.EndLabel;
Reid Kleckner14e77352015-10-09 23:34:53 +0000463 continue;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000464 }
Reid Klecknerd880dc72015-10-09 20:39:39 +0000465
Reid Kleckner14e77352015-10-09 23:34:53 +0000466 // If this invoke ends a previous one, emit all the actions for this
467 // state.
468 if (LastEHState != -1)
469 emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel,
470 LastEHState);
Reid Klecknerd880dc72015-10-09 20:39:39 +0000471
Reid Kleckner14e77352015-10-09 23:34:53 +0000472 LastBeginLabel = I.BeginLabel;
473 LastEndLabel = I.EndLabel;
474 LastEHState = I.State;
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000475 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000476 }
Reid Kleckner14e77352015-10-09 23:34:53 +0000477
478 // Hitting the end of the function causes us to emit the range for the
479 // previous invoke.
480 if (LastEndLabel)
481 emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel, LastEHState);
482
483 OS.EmitLabel(TableEnd);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000484}
David Majnemercde33032015-03-30 22:58:10 +0000485
Reid Klecknerd880dc72015-10-09 20:39:39 +0000486void WinException::emitSEHActionsForRange(WinEHFuncInfo &FuncInfo,
487 MCSymbol *BeginLabel,
488 MCSymbol *EndLabel, int State) {
489 auto &OS = *Asm->OutStreamer;
490 MCContext &Ctx = Asm->OutContext;
491
492 assert(BeginLabel && EndLabel);
493 while (State != -1) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000494 SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
495 const MCExpr *FilterOrFinally;
496 const MCExpr *ExceptOrNull;
497 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
498 if (UME.IsFinally) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000499 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
Reid Klecknerd880dc72015-10-09 20:39:39 +0000500 ExceptOrNull = MCConstantExpr::create(0, Ctx);
501 } else {
502 // For an except, the filter can be 1 (catch-all) or a function
503 // label.
504 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
505 : MCConstantExpr::create(1, Ctx);
506 ExceptOrNull = create32bitRef(Handler->getSymbol());
507 }
508
509 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
510 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
511 OS.EmitValue(FilterOrFinally, 4);
512 OS.EmitValue(ExceptOrNull, 4);
513
514 assert(UME.ToState < State && "states should decrease");
515 State = UME.ToState;
516 }
517}
518
Reid Kleckner60b640b2015-05-28 22:47:01 +0000519void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000520 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000521 auto &OS = *Asm->OutStreamer;
Reid Kleckner813f1b62015-09-16 22:14:46 +0000522 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
David Majnemercde33032015-03-30 22:58:10 +0000523
Reid Kleckner813f1b62015-09-16 22:14:46 +0000524 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000525
Reid Klecknerc71d6272015-09-28 23:56:30 +0000526 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000527 MCSymbol *FuncInfoXData = nullptr;
528 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000529 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
530 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000531 FuncInfoXData =
532 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000533 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000534 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000535 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
536 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000537 }
538
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000539 int UnwindHelpOffset = 0;
540 if (Asm->MAI->usesWindowsCFI())
541 UnwindHelpOffset = getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx);
542
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000543 MCSymbol *UnwindMapXData = nullptr;
544 MCSymbol *TryBlockMapXData = nullptr;
545 MCSymbol *IPToStateXData = nullptr;
Reid Kleckner14e77352015-10-09 23:34:53 +0000546 if (!FuncInfo.CxxUnwindMap.empty())
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000547 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000548 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000549 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000550 TryBlockMapXData =
551 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000552 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000553 IPToStateXData =
554 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000555
556 // FuncInfo {
557 // uint32_t MagicNumber
558 // int32_t MaxState;
559 // UnwindMapEntry *UnwindMap;
560 // uint32_t NumTryBlocks;
561 // TryBlockMapEntry *TryBlockMap;
562 // uint32_t IPMapEntries; // always 0 for x86
563 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
564 // uint32_t UnwindHelp; // non-x86 only
565 // ESTypeList *ESTypeList;
566 // int32_t EHFlags;
567 // }
568 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
569 // EHFlags & 2 -> ???
570 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000571 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000572 OS.EmitLabel(FuncInfoXData);
573 OS.EmitIntValue(0x19930522, 4); // MagicNumber
Reid Kleckner14e77352015-10-09 23:34:53 +0000574 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4); // MaxState
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000575 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
576 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
577 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
Reid Klecknerc71d6272015-09-28 23:56:30 +0000578 OS.EmitIntValue(IPToStateTable.size(), 4); // IPMapEntries
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000579 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
580 if (Asm->MAI->usesWindowsCFI())
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000581 OS.EmitIntValue(UnwindHelpOffset, 4); // UnwindHelp
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000582 OS.EmitIntValue(0, 4); // ESTypeList
583 OS.EmitIntValue(1, 4); // EHFlags
584
585 // UnwindMapEntry {
586 // int32_t ToState;
587 // void (*Action)();
588 // };
589 if (UnwindMapXData) {
590 OS.EmitLabel(UnwindMapXData);
Reid Kleckner14e77352015-10-09 23:34:53 +0000591 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000592 MCSymbol *CleanupSym =
593 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
Reid Kleckner78783912015-09-10 00:25:23 +0000594 OS.EmitIntValue(UME.ToState, 4); // ToState
595 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000596 }
597 }
598
599 // TryBlockMap {
600 // int32_t TryLow;
601 // int32_t TryHigh;
602 // int32_t CatchHigh;
603 // int32_t NumCatches;
604 // HandlerType *HandlerArray;
605 // };
606 if (TryBlockMapXData) {
607 OS.EmitLabel(TryBlockMapXData);
608 SmallVector<MCSymbol *, 1> HandlerMaps;
609 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
610 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000611
Reid Kleckner813f1b62015-09-16 22:14:46 +0000612 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000613 if (!TBME.HandlerArray.empty())
614 HandlerMapXData =
615 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
616 .concat(Twine(I))
617 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000618 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000619 HandlerMaps.push_back(HandlerMapXData);
620
Reid Kleckner813f1b62015-09-16 22:14:46 +0000621 // TBMEs should form intervals.
622 assert(0 <= TBME.TryLow && "bad trymap interval");
623 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
624 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
Reid Kleckner14e77352015-10-09 23:34:53 +0000625 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
Reid Kleckner813f1b62015-09-16 22:14:46 +0000626 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000627
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000628 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
629 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
Reid Kleckner813f1b62015-09-16 22:14:46 +0000630 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000631 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
632 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
633 }
634
635 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
636 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
637 MCSymbol *HandlerMapXData = HandlerMaps[I];
638 if (!HandlerMapXData)
639 continue;
640 // HandlerType {
641 // int32_t Adjectives;
642 // TypeDescriptor *Type;
643 // int32_t CatchObjOffset;
644 // void (*Handler)();
645 // int32_t ParentFrameOffset; // x64 only
646 // };
647 OS.EmitLabel(HandlerMapXData);
648 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
649 // Get the frame escape label with the offset of the catch object. If
David Majnemer99c1d132015-10-12 16:44:22 +0000650 // the index is INT_MAX, then there is no catch object, and we should
651 // emit an offset of zero, indicating that no copy will occur.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000652 const MCExpr *FrameAllocOffsetRef = nullptr;
David Majnemer99c1d132015-10-12 16:44:22 +0000653 if (HT.CatchObj.FrameIndex != INT_MAX) {
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000654 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex);
Reid Klecknerb005d282015-09-16 20:16:27 +0000655 // For 32-bit, the catch object offset is relative to the end of the
656 // EH registration node. For 64-bit, it's relative to SP at the end of
657 // the prologue.
658 if (!shouldEmitPersonality) {
659 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
660 Offset += FuncInfo.EHRegNodeEndOffset;
661 }
662 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000663 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000664 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000665 }
666
David Majnemerbfa5b982015-10-10 00:04:29 +0000667 MCSymbol *HandlerSym =
668 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
Reid Kleckner94b704c2015-09-09 21:10:03 +0000669
670 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
671 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
672 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
673 OS.EmitValue(create32bitRef(HandlerSym), 4); // Handler
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000674
675 if (shouldEmitPersonality) {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000676 // Keep this in sync with X86FrameLowering::emitPrologue.
677 int ParentFrameOffset =
678 16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
679 OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000680 }
681 }
682 }
683 }
684
685 // IPToStateMapEntry {
686 // void *IP;
687 // int32_t State;
688 // };
689 if (IPToStateXData) {
690 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000691 for (auto &IPStatePair : IPToStateTable) {
692 OS.EmitValue(IPStatePair.first, 4); // IP
693 OS.EmitIntValue(IPStatePair.second, 4); // State
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000694 }
695 }
696}
697
Reid Klecknerc71d6272015-09-28 23:56:30 +0000698void WinException::computeIP2StateTable(
699 const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
700 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000701 // Remember what state we were in the last time we found a begin try label.
702 // This allows us to coalesce many nearby invokes with the same state into one
703 // entry.
704 int LastEHState = -1;
705 MCSymbol *LastEndLabel = Asm->getFunctionBegin();
706 assert(LastEndLabel && "need local function start label");
David Majnemercde33032015-03-30 22:58:10 +0000707
Reid Klecknerc71d6272015-09-28 23:56:30 +0000708 // Indicate that all calls from the prologue to the first invoke unwind to
709 // caller. We handle this as a special case since other ranges starting at end
710 // labels need to use LtmpN+1.
711 IPToStateTable.push_back(std::make_pair(create32bitRef(LastEndLabel), -1));
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000712
David Majnemercde33032015-03-30 22:58:10 +0000713 for (const auto &MBB : *MF) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000714 // FIXME: Do we need to emit entries for funclet base states?
715
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000716 for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
717 assert(I.BeginLabel && I.EndLabel);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000718 // If there was a potentially throwing call between this begin label and
719 // the last end label, we need an extra base state entry to indicate that
720 // those calls unwind directly to the caller.
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000721 if (I.SawPotentiallyThrowing && LastEHState != -1) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000722 IPToStateTable.push_back(
723 std::make_pair(getLabelPlusOne(LastEndLabel), -1));
David Majnemercde33032015-03-30 22:58:10 +0000724 LastEHState = -1;
725 }
726
Reid Klecknerc71d6272015-09-28 23:56:30 +0000727 // Emit an entry indicating that PCs after 'Label' have this EH state.
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000728 if (I.State != LastEHState)
729 IPToStateTable.push_back(
Reid Kleckner33bd2d92015-10-07 17:49:32 +0000730 std::make_pair(getLabelPlusOne(I.BeginLabel), I.State));
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000731 LastEHState = I.State;
732 LastEndLabel = I.EndLabel;
David Majnemercde33032015-03-30 22:58:10 +0000733 }
734 }
Reid Klecknerc71d6272015-09-28 23:56:30 +0000735
736 if (LastEndLabel != Asm->getFunctionBegin()) {
737 // Indicate that all calls from the last invoke until the epilogue unwind to
738 // caller. This also ensures that we have at least one ip2state entry, if
739 // somehow all invokes were deleted during CodeGen.
740 IPToStateTable.push_back(std::make_pair(getLabelPlusOne(LastEndLabel), -1));
741 }
David Majnemercde33032015-03-30 22:58:10 +0000742}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000743
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000744void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
745 StringRef FLinkageName) {
746 // Outlined helpers called by the EH runtime need to know the offset of the EH
747 // registration in order to recover the parent frame pointer. Now that we know
748 // we've code generated the parent, we can emit the label assignment that
749 // those helpers use to get the offset of the registration node.
750 assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
Reid Kleckner60381792015-07-07 22:25:32 +0000751 "no EH reg node localescape index");
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000752 MCSymbol *ParentFrameOffset =
753 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
754 MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
755 FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
756 const MCExpr *RegistrationOffsetSymRef =
757 MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
758 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
759}
760
Reid Klecknerf12c0302015-06-09 21:42:19 +0000761/// Emit the language-specific data that _except_handler3 and 4 expect. This is
762/// functionally equivalent to the __C_specific_handler table, except it is
763/// indexed by state number instead of IP.
764void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000765 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000766 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000767 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000768
769 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
770 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000771
772 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000773 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000774 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000775 OS.EmitLabel(LSDALabel);
776
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000777 const Function *Per =
778 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000779 StringRef PerName = Per->getName();
780 int BaseState = -1;
781 if (PerName == "_except_handler4") {
782 // The LSDA for _except_handler4 starts with this struct, followed by the
783 // scope table:
784 //
785 // struct EH4ScopeTable {
786 // int32_t GSCookieOffset;
787 // int32_t GSCookieXOROffset;
788 // int32_t EHCookieOffset;
789 // int32_t EHCookieXOROffset;
790 // ScopeTableEntry ScopeRecord[];
791 // };
792 //
793 // Only the EHCookieOffset field appears to vary, and it appears to be the
794 // offset from the final saved SP value to the retaddr.
795 OS.EmitIntValue(-2, 4);
796 OS.EmitIntValue(0, 4);
797 // FIXME: Calculate.
798 OS.EmitIntValue(9999, 4);
799 OS.EmitIntValue(0, 4);
800 BaseState = -2;
801 }
802
Reid Kleckner14e77352015-10-09 23:34:53 +0000803 assert(!FuncInfo.SEHUnwindMap.empty());
804 for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
805 MCSymbol *ExceptOrFinally =
806 UME.Handler.get<MachineBasicBlock *>()->getSymbol();
807 // -1 is usually the base state for "unwind to caller", but for
808 // _except_handler4 it's -2. Do that replacement here if necessary.
809 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
810 OS.EmitIntValue(ToState, 4); // ToState
811 OS.EmitValue(create32bitRef(UME.Filter), 4); // Filter
812 OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
Reid Klecknerf12c0302015-06-09 21:42:19 +0000813 }
814}