blob: f6945b1d1fb0c1b888968ddddf42b54ea1a2bf60 [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 Majnemera80c1512015-09-29 20:12:33 +0000149/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
150/// are used in the old WinEH scheme, and they will be removed eventually.
David Majnemerbfa5b982015-10-10 00:04:29 +0000151static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
152 const MachineBasicBlock *MBB) {
153 if (!MBB)
David Majnemera80c1512015-09-29 20:12:33 +0000154 return nullptr;
David Majnemera80c1512015-09-29 20:12:33 +0000155
David Majnemerbfa5b982015-10-10 00:04:29 +0000156 assert(MBB->isEHFuncletEntry());
157
158 // Give catches and cleanups a name based off of their parent function and
159 // their funclet entry block's number.
160 const MachineFunction *MF = MBB->getParent();
161 const Function *F = MF->getFunction();
162 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
163 MCContext &Ctx = MF->getContext();
164 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
165 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
166 Twine(MBB->getNumber()) + "@?0?" +
167 FuncLinkageName + "@4HA");
David Majnemera80c1512015-09-29 20:12:33 +0000168}
169
170void WinException::beginFunclet(const MachineBasicBlock &MBB,
171 MCSymbol *Sym) {
172 CurrentFuncletEntry = &MBB;
173
174 const Function *F = Asm->MF->getFunction();
175 // If a symbol was not provided for the funclet, invent one.
176 if (!Sym) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000177 Sym = getMCSymbolForMBB(Asm, &MBB);
David Majnemera80c1512015-09-29 20:12:33 +0000178
179 // Describe our funclet symbol as a function with internal linkage.
180 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
181 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
182 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
183 << COFF::SCT_COMPLEX_TYPE_SHIFT);
184 Asm->OutStreamer->EndCOFFSymbolDef();
185
186 // We want our funclet's entry point to be aligned such that no nops will be
187 // present after the label.
188 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
189 F);
190
191 // Now that we've emitted the alignment directive, point at our funclet.
192 Asm->OutStreamer->EmitLabel(Sym);
193 }
194
195 // Mark 'Sym' as starting our funclet.
David Majnemer0e705982015-09-11 17:34:34 +0000196 if (shouldEmitMoves || shouldEmitPersonality)
David Majnemera80c1512015-09-29 20:12:33 +0000197 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
198
199 if (shouldEmitPersonality) {
200 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
201 const Function *PerFn = nullptr;
202
203 // Determine which personality routine we are using for this funclet.
204 if (F->hasPersonalityFn())
205 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
206 const MCSymbol *PersHandlerSym =
207 TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
208
209 // Classify the personality routine so that we may reason about it.
210 EHPersonality Per = EHPersonality::Unknown;
211 if (F->hasPersonalityFn())
212 Per = classifyEHPersonality(F->getPersonalityFn());
213
214 // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
215 if (Per != EHPersonality::MSVC_CXX ||
216 !CurrentFuncletEntry->isCleanupFuncletEntry())
217 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
218 }
219}
220
221void WinException::endFunclet() {
222 // No funclet to process? Great, we have nothing to do.
223 if (!CurrentFuncletEntry)
224 return;
225
226 if (shouldEmitMoves || shouldEmitPersonality) {
227 const Function *F = Asm->MF->getFunction();
228 EHPersonality Per = EHPersonality::Unknown;
229 if (F->hasPersonalityFn())
230 Per = classifyEHPersonality(F->getPersonalityFn());
231
232 // The .seh_handlerdata directive implicitly switches section, push the
233 // current section so that we may return to it.
234 Asm->OutStreamer->PushSection();
235
236 // Emit an UNWIND_INFO struct describing the prologue.
237 Asm->OutStreamer->EmitWinEHHandlerData();
238
David Majnemera80c1512015-09-29 20:12:33 +0000239 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
240 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000241 // If this is a C++ catch funclet (or the parent function),
242 // emit a reference to the LSDA for the parent function.
David Majnemera80c1512015-09-29 20:12:33 +0000243 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
244 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
245 Twine("$cppxdata$", FuncLinkageName));
246 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000247 } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
248 !CurrentFuncletEntry->isEHFuncletEntry()) {
249 // If this is the parent function in Win64 SEH, emit the LSDA immediately
250 // following .seh_handlerdata.
251 emitCSpecificHandlerTable(Asm->MF);
David Majnemera80c1512015-09-29 20:12:33 +0000252 }
253
254 // Switch back to the previous section now that we are done writing to
255 // .xdata.
256 Asm->OutStreamer->PopSection();
257
258 // Emit a .seh_endproc directive to mark the end of the function.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000259 Asm->OutStreamer->EmitWinCFIEndProc();
David Majnemera80c1512015-09-29 20:12:33 +0000260 }
261
262 // Let's make sure we don't try to end the same funclet twice.
263 CurrentFuncletEntry = nullptr;
Charles Davis91ed7992011-05-27 23:47:32 +0000264}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000265
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000266const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000267 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000268 return MCConstantExpr::create(0, Asm->OutContext);
269 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000270 ? MCSymbolRefExpr::VK_COFF_IMGREL32
271 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000272 Asm->OutContext);
273}
274
David Majnemer0ad363e2015-08-18 19:07:12 +0000275const MCExpr *WinException::create32bitRef(const Value *V) {
276 if (!V)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000277 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner0e288232015-08-27 23:27:47 +0000278 // FIXME: Delete the GlobalValue case once the new IR is fully functional.
279 if (const auto *GV = dyn_cast<GlobalValue>(V))
280 return create32bitRef(Asm->getSymbol(GV));
281 return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
David Majnemercde33032015-03-30 22:58:10 +0000282}
283
Reid Klecknerc71d6272015-09-28 23:56:30 +0000284const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
285 return MCBinaryExpr::createAdd(create32bitRef(Label),
286 MCConstantExpr::create(1, Asm->OutContext),
287 Asm->OutContext);
288}
289
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000290int WinException::getFrameIndexOffset(int FrameIndex) {
291 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
292 unsigned UnusedReg;
293 if (Asm->MAI->usesWindowsCFI())
294 return TFI.getFrameIndexReferenceFromSP(*Asm->MF, FrameIndex, UnusedReg);
295 return TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
296}
297
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000298namespace {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000299/// Information describing an invoke range.
300struct InvokeRange {
301 MCSymbol *BeginLabel = nullptr;
302 MCSymbol *EndLabel = nullptr;
303 int State = -1;
304
305 /// If we saw a potentially throwing call between this range and the last
306 /// range.
307 bool SawPotentiallyThrowing = false;
308};
309
310/// Iterator over the begin/end label pairs of invokes within a basic block.
311class InvokeLabelIterator {
312public:
313 InvokeLabelIterator(WinEHFuncInfo &EHInfo,
314 MachineBasicBlock::const_iterator MBBI,
315 MachineBasicBlock::const_iterator MBBIEnd)
316 : EHInfo(EHInfo), MBBI(MBBI), MBBIEnd(MBBIEnd) {
317 scan();
318 }
319
320 // Iterator methods.
321 bool operator==(const InvokeLabelIterator &o) const { return MBBI == o.MBBI; }
322 bool operator!=(const InvokeLabelIterator &o) const { return MBBI != o.MBBI; }
323 InvokeRange &operator*() { return CurRange; }
324 InvokeRange *operator->() { return &CurRange; }
325 InvokeLabelIterator &operator++() { return scan(); }
326
327private:
328 // Scan forward to find the next invoke range, or hit the end iterator.
329 InvokeLabelIterator &scan();
330
331 WinEHFuncInfo &EHInfo;
332 MachineBasicBlock::const_iterator MBBI;
333 MachineBasicBlock::const_iterator MBBIEnd;
334 InvokeRange CurRange;
335};
Benjamin Kramer808d2a02015-10-05 21:20:26 +0000336} // end anonymous namespace
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000337
338/// Invoke label range iteration logic. Increment MBBI until we find the next
339/// EH_LABEL pair, and then update MBBI to point after the end label.
340InvokeLabelIterator &InvokeLabelIterator::scan() {
341 // Reset our state.
342 CurRange = InvokeRange{};
343
344 for (const MachineInstr &MI : make_range(MBBI, MBBIEnd)) {
345 // Remember if we had to cross a potentially throwing call instruction that
346 // must unwind to caller.
347 if (MI.isCall()) {
348 CurRange.SawPotentiallyThrowing |=
349 !EHStreamer::callToNoUnwindFunction(&MI);
350 continue;
351 }
352 // Find the next EH_LABEL instruction.
353 if (!MI.isEHLabel())
354 continue;
355
356 // If this is a begin label, break out with the state and end label.
357 // Otherwise this is probably a CFI EH_LABEL that we should continue past.
358 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
359 auto StateAndEnd = EHInfo.InvokeToStateMap.find(Label);
360 if (StateAndEnd == EHInfo.InvokeToStateMap.end())
361 continue;
362 MBBI = MachineBasicBlock::const_iterator(&MI);
363 CurRange.BeginLabel = Label;
364 CurRange.EndLabel = StateAndEnd->second.second;
365 CurRange.State = StateAndEnd->second.first;
366 break;
367 }
368
369 // If we didn't find a begin label, we are done, return the end iterator.
370 if (!CurRange.BeginLabel) {
371 MBBI = MBBIEnd;
372 return *this;
373 }
374
375 // If this is a begin label, update MBBI to point past the end label.
376 for (; MBBI != MBBIEnd; ++MBBI)
377 if (MBBI->isEHLabel() &&
378 MBBI->getOperand(0).getMCSymbol() == CurRange.EndLabel)
379 break;
380 return *this;
381}
382
383/// Utility for making a range for all the invoke ranges.
384static iterator_range<InvokeLabelIterator>
385invoke_ranges(WinEHFuncInfo &EHInfo, const MachineBasicBlock &MBB) {
386 return make_range(InvokeLabelIterator(EHInfo, MBB.begin(), MBB.end()),
387 InvokeLabelIterator(EHInfo, MBB.end(), MBB.end()));
388}
389
Reid Kleckner0a57f652015-01-14 01:05:27 +0000390/// Emit the language-specific data that __C_specific_handler expects. This
391/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
392/// up after faults with __try, __except, and __finally. The typeinfo values
393/// are not really RTTI data, but pointers to filter functions that return an
394/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
395/// blocks and other cleanups, the landing pad label is zero, and the filter
396/// function is actually a cleanup handler with the same prototype. A catch-all
397/// entry is modeled with a null filter function field and a non-zero landing
398/// pad label.
399///
400/// Possible filter function return values:
401/// EXCEPTION_EXECUTE_HANDLER (1):
402/// Jump to the landing pad label after cleanups.
403/// EXCEPTION_CONTINUE_SEARCH (0):
404/// Continue searching this table or continue unwinding.
405/// EXCEPTION_CONTINUE_EXECUTION (-1):
406/// Resume execution at the trapping PC.
407///
408/// Inferred table structure:
409/// struct Table {
410/// int NumEntries;
411/// struct Entry {
412/// imagerel32 LabelStart;
413/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000414/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner14e77352015-10-09 23:34:53 +0000415/// imagerel32 LabelLPad; // Zero means __finally.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000416/// } Entries[NumEntries];
417/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000418void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000419 auto &OS = *Asm->OutStreamer;
420 MCContext &Ctx = Asm->OutContext;
Reid Kleckner0a57f652015-01-14 01:05:27 +0000421
Reid Kleckner94b704c2015-09-09 21:10:03 +0000422 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000423
Reid Kleckner14e77352015-10-09 23:34:53 +0000424 // Remember what state we were in the last time we found a begin try label.
425 // This allows us to coalesce many nearby invokes with the same state into
426 // one entry.
427 int LastEHState = -1;
428 MCSymbol *LastBeginLabel = nullptr;
429 MCSymbol *LastEndLabel = nullptr;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000430
Reid Kleckner14e77352015-10-09 23:34:53 +0000431 // Use the assembler to compute the number of table entries through label
432 // difference and division.
433 MCSymbol *TableBegin =
434 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
435 MCSymbol *TableEnd =
436 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
437 const MCExpr *LabelDiff =
438 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TableEnd, Ctx),
439 MCSymbolRefExpr::create(TableBegin, Ctx), Ctx);
440 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
441 const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
442 OS.EmitValue(EntryCount, 4);
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000443
Reid Kleckner14e77352015-10-09 23:34:53 +0000444 OS.EmitLabel(TableBegin);
Reid Klecknereb7cd6c2015-10-09 23:05:54 +0000445
Reid Kleckner14e77352015-10-09 23:34:53 +0000446 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
447 // models exceptions from invokes. LLVM also allows arbitrary reordering of
448 // the code, so our tables end up looking a bit different. Rather than
449 // trying to match MSVC's tables exactly, we emit a denormalized table. For
450 // each range of invokes in the same state, we emit table entries for all
451 // the actions that would be taken in that state. This means our tables are
452 // slightly bigger, which is OK.
453 for (const auto &MBB : *MF) {
454 // Break out before we enter into a finally funclet.
455 // FIXME: We need to emit separate EH tables for cleanups.
456 if (MBB.isEHFuncletEntry() && &MBB != MF->begin())
457 break;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000458
Reid Kleckner14e77352015-10-09 23:34:53 +0000459 for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
460 // If this invoke is in the same state as the last invoke and there were
461 // no non-throwing calls between it, extend the range to include both
462 // and continue.
463 if (!I.SawPotentiallyThrowing && I.State == LastEHState) {
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000464 LastEndLabel = I.EndLabel;
Reid Kleckner14e77352015-10-09 23:34:53 +0000465 continue;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000466 }
Reid Klecknerd880dc72015-10-09 20:39:39 +0000467
Reid Kleckner14e77352015-10-09 23:34:53 +0000468 // If this invoke ends a previous one, emit all the actions for this
469 // state.
470 if (LastEHState != -1)
471 emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel,
472 LastEHState);
Reid Klecknerd880dc72015-10-09 20:39:39 +0000473
Reid Kleckner14e77352015-10-09 23:34:53 +0000474 LastBeginLabel = I.BeginLabel;
475 LastEndLabel = I.EndLabel;
476 LastEHState = I.State;
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000477 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000478 }
Reid Kleckner14e77352015-10-09 23:34:53 +0000479
480 // Hitting the end of the function causes us to emit the range for the
481 // previous invoke.
482 if (LastEndLabel)
483 emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel, LastEHState);
484
485 OS.EmitLabel(TableEnd);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000486}
David Majnemercde33032015-03-30 22:58:10 +0000487
Reid Klecknerd880dc72015-10-09 20:39:39 +0000488void WinException::emitSEHActionsForRange(WinEHFuncInfo &FuncInfo,
489 MCSymbol *BeginLabel,
490 MCSymbol *EndLabel, int State) {
491 auto &OS = *Asm->OutStreamer;
492 MCContext &Ctx = Asm->OutContext;
493
494 assert(BeginLabel && EndLabel);
495 while (State != -1) {
Reid Klecknerd880dc72015-10-09 20:39:39 +0000496 SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
497 const MCExpr *FilterOrFinally;
498 const MCExpr *ExceptOrNull;
499 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
500 if (UME.IsFinally) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000501 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
Reid Klecknerd880dc72015-10-09 20:39:39 +0000502 ExceptOrNull = MCConstantExpr::create(0, Ctx);
503 } else {
504 // For an except, the filter can be 1 (catch-all) or a function
505 // label.
506 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
507 : MCConstantExpr::create(1, Ctx);
508 ExceptOrNull = create32bitRef(Handler->getSymbol());
509 }
510
511 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
512 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
513 OS.EmitValue(FilterOrFinally, 4);
514 OS.EmitValue(ExceptOrNull, 4);
515
516 assert(UME.ToState < State && "states should decrease");
517 State = UME.ToState;
518 }
519}
520
Reid Kleckner60b640b2015-05-28 22:47:01 +0000521void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000522 const Function *F = MF->getFunction();
Lang Hames9ff69c82015-04-24 19:11:51 +0000523 auto &OS = *Asm->OutStreamer;
Reid Kleckner813f1b62015-09-16 22:14:46 +0000524 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
David Majnemercde33032015-03-30 22:58:10 +0000525
Reid Kleckner813f1b62015-09-16 22:14:46 +0000526 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
David Majnemercde33032015-03-30 22:58:10 +0000527
Reid Klecknerc71d6272015-09-28 23:56:30 +0000528 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000529 MCSymbol *FuncInfoXData = nullptr;
530 if (shouldEmitPersonality) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000531 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
532 // IPs to state numbers.
Reid Kleckner813f1b62015-09-16 22:14:46 +0000533 FuncInfoXData =
534 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000535 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000536 } else {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000537 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
538 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000539 }
540
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000541 int UnwindHelpOffset = 0;
542 if (Asm->MAI->usesWindowsCFI())
543 UnwindHelpOffset = getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx);
544
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000545 MCSymbol *UnwindMapXData = nullptr;
546 MCSymbol *TryBlockMapXData = nullptr;
547 MCSymbol *IPToStateXData = nullptr;
Reid Kleckner14e77352015-10-09 23:34:53 +0000548 if (!FuncInfo.CxxUnwindMap.empty())
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000549 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000550 Twine("$stateUnwindMap$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000551 if (!FuncInfo.TryBlockMap.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000552 TryBlockMapXData =
553 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
Reid Klecknerc71d6272015-09-28 23:56:30 +0000554 if (!IPToStateTable.empty())
Reid Kleckner813f1b62015-09-16 22:14:46 +0000555 IPToStateXData =
556 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000557
558 // FuncInfo {
559 // uint32_t MagicNumber
560 // int32_t MaxState;
561 // UnwindMapEntry *UnwindMap;
562 // uint32_t NumTryBlocks;
563 // TryBlockMapEntry *TryBlockMap;
564 // uint32_t IPMapEntries; // always 0 for x86
565 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
566 // uint32_t UnwindHelp; // non-x86 only
567 // ESTypeList *ESTypeList;
568 // int32_t EHFlags;
569 // }
570 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
571 // EHFlags & 2 -> ???
572 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000573 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000574 OS.EmitLabel(FuncInfoXData);
575 OS.EmitIntValue(0x19930522, 4); // MagicNumber
Reid Kleckner14e77352015-10-09 23:34:53 +0000576 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4); // MaxState
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000577 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
578 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
579 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
Reid Klecknerc71d6272015-09-28 23:56:30 +0000580 OS.EmitIntValue(IPToStateTable.size(), 4); // IPMapEntries
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000581 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
582 if (Asm->MAI->usesWindowsCFI())
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000583 OS.EmitIntValue(UnwindHelpOffset, 4); // UnwindHelp
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000584 OS.EmitIntValue(0, 4); // ESTypeList
585 OS.EmitIntValue(1, 4); // EHFlags
586
587 // UnwindMapEntry {
588 // int32_t ToState;
589 // void (*Action)();
590 // };
591 if (UnwindMapXData) {
592 OS.EmitLabel(UnwindMapXData);
Reid Kleckner14e77352015-10-09 23:34:53 +0000593 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
David Majnemerbfa5b982015-10-10 00:04:29 +0000594 MCSymbol *CleanupSym =
595 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
Reid Kleckner78783912015-09-10 00:25:23 +0000596 OS.EmitIntValue(UME.ToState, 4); // ToState
597 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000598 }
599 }
600
601 // TryBlockMap {
602 // int32_t TryLow;
603 // int32_t TryHigh;
604 // int32_t CatchHigh;
605 // int32_t NumCatches;
606 // HandlerType *HandlerArray;
607 // };
608 if (TryBlockMapXData) {
609 OS.EmitLabel(TryBlockMapXData);
610 SmallVector<MCSymbol *, 1> HandlerMaps;
611 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
612 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000613
Reid Kleckner813f1b62015-09-16 22:14:46 +0000614 MCSymbol *HandlerMapXData = nullptr;
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000615 if (!TBME.HandlerArray.empty())
616 HandlerMapXData =
617 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
618 .concat(Twine(I))
619 .concat("$")
Reid Kleckner813f1b62015-09-16 22:14:46 +0000620 .concat(FuncLinkageName));
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000621 HandlerMaps.push_back(HandlerMapXData);
622
Reid Kleckner813f1b62015-09-16 22:14:46 +0000623 // TBMEs should form intervals.
624 assert(0 <= TBME.TryLow && "bad trymap interval");
625 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
626 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
Reid Kleckner14e77352015-10-09 23:34:53 +0000627 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
Reid Kleckner813f1b62015-09-16 22:14:46 +0000628 "bad trymap interval");
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000629
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000630 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
631 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
Reid Kleckner813f1b62015-09-16 22:14:46 +0000632 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000633 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
634 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
635 }
636
637 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
638 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
639 MCSymbol *HandlerMapXData = HandlerMaps[I];
640 if (!HandlerMapXData)
641 continue;
642 // HandlerType {
643 // int32_t Adjectives;
644 // TypeDescriptor *Type;
645 // int32_t CatchObjOffset;
646 // void (*Handler)();
647 // int32_t ParentFrameOffset; // x64 only
648 // };
649 OS.EmitLabel(HandlerMapXData);
650 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
651 // Get the frame escape label with the offset of the catch object. If
652 // the index is -1, then there is no catch object, and we should emit an
653 // offset of zero, indicating that no copy will occur.
654 const MCExpr *FrameAllocOffsetRef = nullptr;
655 if (HT.CatchObjRecoverIdx >= 0) {
656 MCSymbol *FrameAllocOffset =
657 Asm->OutContext.getOrCreateFrameAllocSymbol(
Reid Kleckner813f1b62015-09-16 22:14:46 +0000658 FuncLinkageName, HT.CatchObjRecoverIdx);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000659 FrameAllocOffsetRef = MCSymbolRefExpr::create(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000660 FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
Reid Kleckner70bf6bb2015-10-07 21:13:15 +0000661 } else if (HT.CatchObj.FrameIndex != INT_MAX) {
662 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex);
Reid Klecknerb005d282015-09-16 20:16:27 +0000663 // For 32-bit, the catch object offset is relative to the end of the
664 // EH registration node. For 64-bit, it's relative to SP at the end of
665 // the prologue.
666 if (!shouldEmitPersonality) {
667 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
668 Offset += FuncInfo.EHRegNodeEndOffset;
669 }
670 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000671 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000672 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000673 }
674
David Majnemerbfa5b982015-10-10 00:04:29 +0000675 MCSymbol *HandlerSym =
676 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
Reid Kleckner94b704c2015-09-09 21:10:03 +0000677
678 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
679 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
680 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
681 OS.EmitValue(create32bitRef(HandlerSym), 4); // Handler
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000682
683 if (shouldEmitPersonality) {
Reid Kleckner813f1b62015-09-16 22:14:46 +0000684 // With the new IR, this is always 16 + 8 + getMaxCallFrameSize().
685 // Keep this in sync with X86FrameLowering::emitPrologue.
686 int ParentFrameOffset =
687 16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
688 OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000689 }
690 }
691 }
692 }
693
694 // IPToStateMapEntry {
695 // void *IP;
696 // int32_t State;
697 // };
698 if (IPToStateXData) {
699 OS.EmitLabel(IPToStateXData);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000700 for (auto &IPStatePair : IPToStateTable) {
701 OS.EmitValue(IPStatePair.first, 4); // IP
702 OS.EmitIntValue(IPStatePair.second, 4); // State
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000703 }
704 }
705}
706
Reid Klecknerc71d6272015-09-28 23:56:30 +0000707void WinException::computeIP2StateTable(
708 const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
709 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000710 // Remember what state we were in the last time we found a begin try label.
711 // This allows us to coalesce many nearby invokes with the same state into one
712 // entry.
713 int LastEHState = -1;
714 MCSymbol *LastEndLabel = Asm->getFunctionBegin();
715 assert(LastEndLabel && "need local function start label");
David Majnemercde33032015-03-30 22:58:10 +0000716
Reid Klecknerc71d6272015-09-28 23:56:30 +0000717 // Indicate that all calls from the prologue to the first invoke unwind to
718 // caller. We handle this as a special case since other ranges starting at end
719 // labels need to use LtmpN+1.
720 IPToStateTable.push_back(std::make_pair(create32bitRef(LastEndLabel), -1));
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000721
David Majnemercde33032015-03-30 22:58:10 +0000722 for (const auto &MBB : *MF) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000723 // FIXME: Do we need to emit entries for funclet base states?
724
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000725 for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
726 assert(I.BeginLabel && I.EndLabel);
Reid Klecknerc71d6272015-09-28 23:56:30 +0000727 // If there was a potentially throwing call between this begin label and
728 // the last end label, we need an extra base state entry to indicate that
729 // those calls unwind directly to the caller.
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000730 if (I.SawPotentiallyThrowing && LastEHState != -1) {
Reid Klecknerc71d6272015-09-28 23:56:30 +0000731 IPToStateTable.push_back(
732 std::make_pair(getLabelPlusOne(LastEndLabel), -1));
David Majnemercde33032015-03-30 22:58:10 +0000733 LastEHState = -1;
734 }
735
Reid Klecknerc71d6272015-09-28 23:56:30 +0000736 // Emit an entry indicating that PCs after 'Label' have this EH state.
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000737 if (I.State != LastEHState)
738 IPToStateTable.push_back(
Reid Kleckner33bd2d92015-10-07 17:49:32 +0000739 std::make_pair(getLabelPlusOne(I.BeginLabel), I.State));
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000740 LastEHState = I.State;
741 LastEndLabel = I.EndLabel;
David Majnemercde33032015-03-30 22:58:10 +0000742 }
743 }
Reid Klecknerc71d6272015-09-28 23:56:30 +0000744
745 if (LastEndLabel != Asm->getFunctionBegin()) {
746 // Indicate that all calls from the last invoke until the epilogue unwind to
747 // caller. This also ensures that we have at least one ip2state entry, if
748 // somehow all invokes were deleted during CodeGen.
749 IPToStateTable.push_back(std::make_pair(getLabelPlusOne(LastEndLabel), -1));
750 }
David Majnemercde33032015-03-30 22:58:10 +0000751}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000752
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000753void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
754 StringRef FLinkageName) {
755 // Outlined helpers called by the EH runtime need to know the offset of the EH
756 // registration in order to recover the parent frame pointer. Now that we know
757 // we've code generated the parent, we can emit the label assignment that
758 // those helpers use to get the offset of the registration node.
759 assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
Reid Kleckner60381792015-07-07 22:25:32 +0000760 "no EH reg node localescape index");
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000761 MCSymbol *ParentFrameOffset =
762 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
763 MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
764 FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
765 const MCExpr *RegistrationOffsetSymRef =
766 MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
767 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
768}
769
Reid Klecknerf12c0302015-06-09 21:42:19 +0000770/// Emit the language-specific data that _except_handler3 and 4 expect. This is
771/// functionally equivalent to the __C_specific_handler table, except it is
772/// indexed by state number instead of IP.
773void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000774 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000775 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000776 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000777
778 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
779 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000780
781 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000782 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000783 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000784 OS.EmitLabel(LSDALabel);
785
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000786 const Function *Per =
787 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000788 StringRef PerName = Per->getName();
789 int BaseState = -1;
790 if (PerName == "_except_handler4") {
791 // The LSDA for _except_handler4 starts with this struct, followed by the
792 // scope table:
793 //
794 // struct EH4ScopeTable {
795 // int32_t GSCookieOffset;
796 // int32_t GSCookieXOROffset;
797 // int32_t EHCookieOffset;
798 // int32_t EHCookieXOROffset;
799 // ScopeTableEntry ScopeRecord[];
800 // };
801 //
802 // Only the EHCookieOffset field appears to vary, and it appears to be the
803 // offset from the final saved SP value to the retaddr.
804 OS.EmitIntValue(-2, 4);
805 OS.EmitIntValue(0, 4);
806 // FIXME: Calculate.
807 OS.EmitIntValue(9999, 4);
808 OS.EmitIntValue(0, 4);
809 BaseState = -2;
810 }
811
Reid Kleckner14e77352015-10-09 23:34:53 +0000812 assert(!FuncInfo.SEHUnwindMap.empty());
813 for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
814 MCSymbol *ExceptOrFinally =
815 UME.Handler.get<MachineBasicBlock *>()->getSymbol();
816 // -1 is usually the base state for "unwind to caller", but for
817 // _except_handler4 it's -2. Do that replacement here if necessary.
818 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
819 OS.EmitIntValue(ToState, 4); // ToState
820 OS.EmitValue(create32bitRef(UME.Filter), 4); // Filter
821 OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
Reid Klecknerf12c0302015-06-09 21:42:19 +0000822 }
823}