1 //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing Win64 exception info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "WinException.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/WinEHFuncInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Mangler.h"
25 #include "llvm/IR/Module.h"
26 #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"
32 #include "llvm/MC/MCWin64EH.h"
33 #include "llvm/Support/COFF.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Target/TargetFrameLowering.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
44 WinException::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);
50 WinException::~WinException() {}
52 /// endModule - Emit all exception information that should come after the
54 void WinException::endModule() {
55 auto &OS = *Asm->OutStreamer;
56 const Module *M = MMI->getModule();
57 for (const Function &F : *M)
58 if (F.hasFnAttribute("safeseh"))
59 OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
62 void WinException::beginFunction(const MachineFunction *MF) {
63 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
65 // If any landing pads survive, we need an EH table.
66 bool hasLandingPads = !MMI->getLandingPads().empty();
67 bool hasEHFunclets = MMI->hasEHFunclets();
69 const Function *F = MF->getFunction();
70 const Function *ParentF = MMI->getWinEHParent(F);
72 shouldEmitMoves = Asm->needsSEHMoves();
74 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
75 unsigned PerEncoding = TLOF.getPersonalityEncoding();
76 const Function *Per = nullptr;
77 if (F->hasPersonalityFn())
78 Per = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
80 bool forceEmitPersonality =
81 F->hasPersonalityFn() && !isNoOpWithoutInvoke(classifyEHPersonality(Per)) &&
82 F->needsUnwindTableEntry();
84 shouldEmitPersonality =
85 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
86 PerEncoding != dwarf::DW_EH_PE_omit && Per);
88 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
89 shouldEmitLSDA = shouldEmitPersonality &&
90 LSDAEncoding != dwarf::DW_EH_PE_omit;
92 // 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.
94 // FIXME: If WinEHPrepare outlined something, we should emit the LSDA. Remove
95 // this once WinEHPrepare stops doing that.
96 if (!Asm->MAI->usesWindowsCFI()) {
98 hasEHFunclets || (F->hasFnAttribute("wineh-parent") && F == ParentF);
99 shouldEmitPersonality = false;
103 beginFunclet(MF->front(), Asm->CurrentFnSym);
106 /// endFunction - Gather and emit post-function exception information.
108 void WinException::endFunction(const MachineFunction *MF) {
109 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
112 const Function *F = MF->getFunction();
113 EHPersonality Per = EHPersonality::Unknown;
114 if (F->hasPersonalityFn())
115 Per = classifyEHPersonality(F->getPersonalityFn());
117 // Get rid of any dead landing pads if we're not using funclets. In funclet
118 // schemes, the landing pad is not actually reachable. It only exists so
119 // that we can emit the right table data.
120 if (!isFuncletEHPersonality(Per))
121 MMI->TidyLandingPads();
125 // endFunclet will emit the necessary .xdata tables for x64 SEH.
126 if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
129 if (shouldEmitPersonality || shouldEmitLSDA) {
130 Asm->OutStreamer->PushSection();
132 // Just switch sections to the right xdata section. This use of CurrentFnSym
133 // assumes that we only emit the LSDA when ending the parent function.
134 MCSection *XData = WinEH::UnwindEmitter::getXDataSection(Asm->CurrentFnSym,
136 Asm->OutStreamer->SwitchSection(XData);
138 // Emit the tables appropriate to the personality function in use. If we
139 // don't recognize the personality, assume it uses an Itanium-style LSDA.
140 if (Per == EHPersonality::MSVC_Win64SEH)
141 emitCSpecificHandlerTable(MF);
142 else if (Per == EHPersonality::MSVC_X86SEH)
143 emitExceptHandlerTable(MF);
144 else if (Per == EHPersonality::MSVC_CXX)
145 emitCXXFrameHandler3Table(MF);
147 emitExceptionTable();
149 Asm->OutStreamer->PopSection();
153 /// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
154 /// are used in the old WinEH scheme, and they will be removed eventually.
155 static MCSymbol *getMCSymbolForMBBOrGV(AsmPrinter *Asm, ValueOrMBB Handler) {
158 if (Handler.is<const MachineBasicBlock *>()) {
159 auto *MBB = Handler.get<const MachineBasicBlock *>();
160 assert(MBB->isEHFuncletEntry());
162 // Give catches and cleanups a name based off of their parent function and
163 // their funclet entry block's number.
164 const MachineFunction *MF = MBB->getParent();
165 const Function *F = MF->getFunction();
166 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
167 MCContext &Ctx = MF->getContext();
168 StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
169 return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
170 Twine(MBB->getNumber()) + "@?0?" +
171 FuncLinkageName + "@4HA");
173 return Asm->getSymbol(cast<GlobalValue>(Handler.get<const Value *>()));
176 void WinException::beginFunclet(const MachineBasicBlock &MBB,
178 CurrentFuncletEntry = &MBB;
180 const Function *F = Asm->MF->getFunction();
181 // If a symbol was not provided for the funclet, invent one.
183 Sym = getMCSymbolForMBBOrGV(Asm, &MBB);
185 // Describe our funclet symbol as a function with internal linkage.
186 Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
187 Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
188 Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
189 << COFF::SCT_COMPLEX_TYPE_SHIFT);
190 Asm->OutStreamer->EndCOFFSymbolDef();
192 // We want our funclet's entry point to be aligned such that no nops will be
193 // present after the label.
194 Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
197 // Now that we've emitted the alignment directive, point at our funclet.
198 Asm->OutStreamer->EmitLabel(Sym);
201 // Mark 'Sym' as starting our funclet.
202 if (shouldEmitMoves || shouldEmitPersonality)
203 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
205 if (shouldEmitPersonality) {
206 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
207 const Function *PerFn = nullptr;
209 // Determine which personality routine we are using for this funclet.
210 if (F->hasPersonalityFn())
211 PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
212 const MCSymbol *PersHandlerSym =
213 TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
215 // Classify the personality routine so that we may reason about it.
216 EHPersonality Per = EHPersonality::Unknown;
217 if (F->hasPersonalityFn())
218 Per = classifyEHPersonality(F->getPersonalityFn());
220 // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
221 if (Per != EHPersonality::MSVC_CXX ||
222 !CurrentFuncletEntry->isCleanupFuncletEntry())
223 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
227 void WinException::endFunclet() {
228 // No funclet to process? Great, we have nothing to do.
229 if (!CurrentFuncletEntry)
232 if (shouldEmitMoves || shouldEmitPersonality) {
233 const Function *F = Asm->MF->getFunction();
234 EHPersonality Per = EHPersonality::Unknown;
235 if (F->hasPersonalityFn())
236 Per = classifyEHPersonality(F->getPersonalityFn());
238 // The .seh_handlerdata directive implicitly switches section, push the
239 // current section so that we may return to it.
240 Asm->OutStreamer->PushSection();
242 // Emit an UNWIND_INFO struct describing the prologue.
243 Asm->OutStreamer->EmitWinEHHandlerData();
245 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
246 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
247 // If this is a C++ catch funclet (or the parent function),
248 // emit a reference to the LSDA for the parent function.
249 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
250 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
251 Twine("$cppxdata$", FuncLinkageName));
252 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
253 } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
254 !CurrentFuncletEntry->isEHFuncletEntry()) {
255 // If this is the parent function in Win64 SEH, emit the LSDA immediately
256 // following .seh_handlerdata.
257 emitCSpecificHandlerTable(Asm->MF);
260 // Switch back to the previous section now that we are done writing to
262 Asm->OutStreamer->PopSection();
264 // Emit a .seh_endproc directive to mark the end of the function.
265 Asm->OutStreamer->EmitWinCFIEndProc();
268 // Let's make sure we don't try to end the same funclet twice.
269 CurrentFuncletEntry = nullptr;
272 const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
274 return MCConstantExpr::create(0, Asm->OutContext);
275 return MCSymbolRefExpr::create(Value, useImageRel32
276 ? MCSymbolRefExpr::VK_COFF_IMGREL32
277 : MCSymbolRefExpr::VK_None,
281 const MCExpr *WinException::create32bitRef(const Value *V) {
283 return MCConstantExpr::create(0, Asm->OutContext);
284 // FIXME: Delete the GlobalValue case once the new IR is fully functional.
285 if (const auto *GV = dyn_cast<GlobalValue>(V))
286 return create32bitRef(Asm->getSymbol(GV));
287 return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
290 const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
291 return MCBinaryExpr::createAdd(create32bitRef(Label),
292 MCConstantExpr::create(1, Asm->OutContext),
296 int WinException::getFrameIndexOffset(int FrameIndex) {
297 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
299 if (Asm->MAI->usesWindowsCFI())
300 return TFI.getFrameIndexReferenceFromSP(*Asm->MF, FrameIndex, UnusedReg);
301 return TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
305 /// Information describing an invoke range.
307 MCSymbol *BeginLabel = nullptr;
308 MCSymbol *EndLabel = nullptr;
311 /// If we saw a potentially throwing call between this range and the last
313 bool SawPotentiallyThrowing = false;
316 /// Iterator over the begin/end label pairs of invokes within a basic block.
317 class InvokeLabelIterator {
319 InvokeLabelIterator(WinEHFuncInfo &EHInfo,
320 MachineBasicBlock::const_iterator MBBI,
321 MachineBasicBlock::const_iterator MBBIEnd)
322 : EHInfo(EHInfo), MBBI(MBBI), MBBIEnd(MBBIEnd) {
327 bool operator==(const InvokeLabelIterator &o) const { return MBBI == o.MBBI; }
328 bool operator!=(const InvokeLabelIterator &o) const { return MBBI != o.MBBI; }
329 InvokeRange &operator*() { return CurRange; }
330 InvokeRange *operator->() { return &CurRange; }
331 InvokeLabelIterator &operator++() { return scan(); }
334 // Scan forward to find the next invoke range, or hit the end iterator.
335 InvokeLabelIterator &scan();
337 WinEHFuncInfo &EHInfo;
338 MachineBasicBlock::const_iterator MBBI;
339 MachineBasicBlock::const_iterator MBBIEnd;
340 InvokeRange CurRange;
342 } // end anonymous namespace
344 /// Invoke label range iteration logic. Increment MBBI until we find the next
345 /// EH_LABEL pair, and then update MBBI to point after the end label.
346 InvokeLabelIterator &InvokeLabelIterator::scan() {
348 CurRange = InvokeRange{};
350 for (const MachineInstr &MI : make_range(MBBI, MBBIEnd)) {
351 // Remember if we had to cross a potentially throwing call instruction that
352 // must unwind to caller.
354 CurRange.SawPotentiallyThrowing |=
355 !EHStreamer::callToNoUnwindFunction(&MI);
358 // Find the next EH_LABEL instruction.
362 // If this is a begin label, break out with the state and end label.
363 // Otherwise this is probably a CFI EH_LABEL that we should continue past.
364 MCSymbol *Label = MI.getOperand(0).getMCSymbol();
365 auto StateAndEnd = EHInfo.InvokeToStateMap.find(Label);
366 if (StateAndEnd == EHInfo.InvokeToStateMap.end())
368 MBBI = MachineBasicBlock::const_iterator(&MI);
369 CurRange.BeginLabel = Label;
370 CurRange.EndLabel = StateAndEnd->second.second;
371 CurRange.State = StateAndEnd->second.first;
375 // If we didn't find a begin label, we are done, return the end iterator.
376 if (!CurRange.BeginLabel) {
381 // If this is a begin label, update MBBI to point past the end label.
382 for (; MBBI != MBBIEnd; ++MBBI)
383 if (MBBI->isEHLabel() &&
384 MBBI->getOperand(0).getMCSymbol() == CurRange.EndLabel)
389 /// Utility for making a range for all the invoke ranges.
390 static iterator_range<InvokeLabelIterator>
391 invoke_ranges(WinEHFuncInfo &EHInfo, const MachineBasicBlock &MBB) {
392 return make_range(InvokeLabelIterator(EHInfo, MBB.begin(), MBB.end()),
393 InvokeLabelIterator(EHInfo, MBB.end(), MBB.end()));
396 /// Emit the language-specific data that __C_specific_handler expects. This
397 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
398 /// up after faults with __try, __except, and __finally. The typeinfo values
399 /// are not really RTTI data, but pointers to filter functions that return an
400 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
401 /// blocks and other cleanups, the landing pad label is zero, and the filter
402 /// function is actually a cleanup handler with the same prototype. A catch-all
403 /// entry is modeled with a null filter function field and a non-zero landing
406 /// Possible filter function return values:
407 /// EXCEPTION_EXECUTE_HANDLER (1):
408 /// Jump to the landing pad label after cleanups.
409 /// EXCEPTION_CONTINUE_SEARCH (0):
410 /// Continue searching this table or continue unwinding.
411 /// EXCEPTION_CONTINUE_EXECUTION (-1):
412 /// Resume execution at the trapping PC.
414 /// Inferred table structure:
418 /// imagerel32 LabelStart;
419 /// imagerel32 LabelEnd;
420 /// imagerel32 FilterOrFinally; // One means catch-all.
421 /// imagerel32 ExceptOrNull; // Zero means __finally.
422 /// } Entries[NumEntries];
424 void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
425 auto &OS = *Asm->OutStreamer;
426 MCContext &Ctx = Asm->OutContext;
428 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
429 if (!FuncInfo.SEHUnwindMap.empty()) {
430 // Remember what state we were in the last time we found a begin try label.
431 // This allows us to coalesce many nearby invokes with the same state into
433 int LastEHState = -1;
434 MCSymbol *LastBeginLabel = nullptr;
435 MCSymbol *LastEndLabel = nullptr;
437 // Use the assembler to compute the number of table entries through label
438 // difference and division.
439 MCSymbol *TableBegin =
440 Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
442 Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
443 const MCExpr *LabelDiff =
444 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TableEnd, Ctx),
445 MCSymbolRefExpr::create(TableBegin, Ctx), Ctx);
446 const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
447 const MCExpr *EntryCount =
448 MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
449 OS.EmitValue(EntryCount, 4);
451 OS.EmitLabel(TableBegin);
453 // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
454 // models exceptions from invokes. LLVM also allows arbitrary reordering of
455 // the code, so our tables end up looking a bit different. Rather than
456 // trying to match MSVC's tables exactly, we emit a denormalized table. For
457 // each range of invokes in the same state, we emit table entries for all
458 // the actions that would be taken in that state. This means our tables are
459 // slightly bigger, which is OK.
460 for (const auto &MBB : *MF) {
461 // Break out before we enter into a finally funclet.
462 // FIXME: We need to emit separate EH tables for cleanups.
463 if (MBB.isEHFuncletEntry() && &MBB != MF->begin())
466 for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
467 // If this invoke is in the same state as the last invoke and there were
468 // no non-throwing calls between it, extend the range to include both
470 if (!I.SawPotentiallyThrowing && I.State == LastEHState) {
471 LastEndLabel = I.EndLabel;
475 // If this invoke ends a previous one, emit all the actions for this
477 if (LastEHState != -1)
478 emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel,
481 LastBeginLabel = I.BeginLabel;
482 LastEndLabel = I.EndLabel;
483 LastEHState = I.State;
488 emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel,
491 OS.EmitLabel(TableEnd);
495 // Simplifying assumptions for first implementation:
496 // - Cleanups are not implemented.
497 // - Filters are not implemented.
499 // The Itanium LSDA table sorts similar landing pads together to simplify the
500 // actions table, but we don't need that.
501 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
502 SmallVector<const LandingPadInfo *, 64> LandingPads;
503 LandingPads.reserve(PadInfos.size());
504 for (const auto &LP : PadInfos)
505 LandingPads.push_back(&LP);
507 // Compute label ranges for call sites as we would for the Itanium LSDA, but
508 // use an all zero action table because we aren't using these actions.
509 SmallVector<unsigned, 64> FirstActions;
510 FirstActions.resize(LandingPads.size());
511 SmallVector<CallSiteEntry, 64> CallSites;
512 computeCallSiteTable(CallSites, LandingPads, FirstActions);
514 MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
515 MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
517 // Emit the number of table entries.
518 unsigned NumEntries = 0;
519 for (const CallSiteEntry &CSE : CallSites) {
521 continue; // Ignore gaps.
522 NumEntries += CSE.LPad->SEHHandlers.size();
524 OS.EmitIntValue(NumEntries, 4);
526 // If there are no actions, we don't need to iterate again.
530 // Emit the four-label records for each call site entry. The table has to be
531 // sorted in layout order, and the call sites should already be sorted.
532 for (const CallSiteEntry &CSE : CallSites) {
533 // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
534 // an EH table entry will propagate the exception rather than terminating
538 const LandingPadInfo *LPad = CSE.LPad;
540 // Compute the label range. We may reuse the function begin and end labels
541 // rather than forming new ones.
542 const MCExpr *Begin =
543 create32bitRef(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
546 // The interval is half-open, so we have to add one to include the return
547 // address of the last invoke in the range.
548 End = getLabelPlusOne(CSE.EndLabel);
550 End = create32bitRef(EHFuncEndSym);
553 // Emit an entry for each action.
554 for (SEHHandler Handler : LPad->SEHHandlers) {
555 OS.EmitValue(Begin, 4);
556 OS.EmitValue(End, 4);
558 // Emit the filter or finally function pointer, if present. Otherwise,
559 // emit '1' to indicate a catch-all.
560 const Function *F = Handler.FilterOrFinally;
562 OS.EmitValue(create32bitRef(Asm->getSymbol(F)), 4);
564 OS.EmitIntValue(1, 4);
566 // Emit the recovery address, if present. Otherwise, this must be a
568 const BlockAddress *BA = Handler.RecoverBA;
571 create32bitRef(Asm->GetBlockAddressSymbol(BA)), 4);
573 OS.EmitIntValue(0, 4);
578 void WinException::emitSEHActionsForRange(WinEHFuncInfo &FuncInfo,
579 MCSymbol *BeginLabel,
580 MCSymbol *EndLabel, int State) {
581 auto &OS = *Asm->OutStreamer;
582 MCContext &Ctx = Asm->OutContext;
584 assert(BeginLabel && EndLabel);
585 while (State != -1) {
587 // imagerel32 LabelStart;
588 // imagerel32 LabelEnd;
589 // imagerel32 FilterOrFinally; // One means catch-all.
590 // imagerel32 ExceptOrNull; // Zero means __finally.
592 SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
593 const MCExpr *FilterOrFinally;
594 const MCExpr *ExceptOrNull;
595 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
597 FilterOrFinally = create32bitRef(getMCSymbolForMBBOrGV(Asm, Handler));
598 ExceptOrNull = MCConstantExpr::create(0, Ctx);
600 // For an except, the filter can be 1 (catch-all) or a function
602 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
603 : MCConstantExpr::create(1, Ctx);
604 ExceptOrNull = create32bitRef(Handler->getSymbol());
607 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
608 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
609 OS.EmitValue(FilterOrFinally, 4);
610 OS.EmitValue(ExceptOrNull, 4);
612 assert(UME.ToState < State && "states should decrease");
617 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
618 const Function *F = MF->getFunction();
619 auto &OS = *Asm->OutStreamer;
620 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
622 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
624 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
625 MCSymbol *FuncInfoXData = nullptr;
626 if (shouldEmitPersonality) {
627 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
628 // IPs to state numbers.
630 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
631 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
633 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
634 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
637 int UnwindHelpOffset = 0;
638 if (Asm->MAI->usesWindowsCFI())
639 UnwindHelpOffset = getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx);
641 MCSymbol *UnwindMapXData = nullptr;
642 MCSymbol *TryBlockMapXData = nullptr;
643 MCSymbol *IPToStateXData = nullptr;
644 if (!FuncInfo.UnwindMap.empty())
645 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
646 Twine("$stateUnwindMap$", FuncLinkageName));
647 if (!FuncInfo.TryBlockMap.empty())
649 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
650 if (!IPToStateTable.empty())
652 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
655 // uint32_t MagicNumber
657 // UnwindMapEntry *UnwindMap;
658 // uint32_t NumTryBlocks;
659 // TryBlockMapEntry *TryBlockMap;
660 // uint32_t IPMapEntries; // always 0 for x86
661 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
662 // uint32_t UnwindHelp; // non-x86 only
663 // ESTypeList *ESTypeList;
666 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
667 // EHFlags & 2 -> ???
668 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
669 OS.EmitValueToAlignment(4);
670 OS.EmitLabel(FuncInfoXData);
671 OS.EmitIntValue(0x19930522, 4); // MagicNumber
672 OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4); // MaxState
673 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
674 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
675 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
676 OS.EmitIntValue(IPToStateTable.size(), 4); // IPMapEntries
677 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
678 if (Asm->MAI->usesWindowsCFI())
679 OS.EmitIntValue(UnwindHelpOffset, 4); // UnwindHelp
680 OS.EmitIntValue(0, 4); // ESTypeList
681 OS.EmitIntValue(1, 4); // EHFlags
687 if (UnwindMapXData) {
688 OS.EmitLabel(UnwindMapXData);
689 for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
690 MCSymbol *CleanupSym = getMCSymbolForMBBOrGV(Asm, UME.Cleanup);
691 OS.EmitIntValue(UME.ToState, 4); // ToState
692 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
699 // int32_t CatchHigh;
700 // int32_t NumCatches;
701 // HandlerType *HandlerArray;
703 if (TryBlockMapXData) {
704 OS.EmitLabel(TryBlockMapXData);
705 SmallVector<MCSymbol *, 1> HandlerMaps;
706 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
707 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
709 MCSymbol *HandlerMapXData = nullptr;
710 if (!TBME.HandlerArray.empty())
712 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
715 .concat(FuncLinkageName));
716 HandlerMaps.push_back(HandlerMapXData);
718 // TBMEs should form intervals.
719 assert(0 <= TBME.TryLow && "bad trymap interval");
720 assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
721 assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
722 assert(TBME.CatchHigh < int(FuncInfo.UnwindMap.size()) &&
723 "bad trymap interval");
725 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
726 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
727 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
728 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
729 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
732 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
733 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
734 MCSymbol *HandlerMapXData = HandlerMaps[I];
735 if (!HandlerMapXData)
738 // int32_t Adjectives;
739 // TypeDescriptor *Type;
740 // int32_t CatchObjOffset;
741 // void (*Handler)();
742 // int32_t ParentFrameOffset; // x64 only
744 OS.EmitLabel(HandlerMapXData);
745 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
746 // Get the frame escape label with the offset of the catch object. If
747 // the index is -1, then there is no catch object, and we should emit an
748 // offset of zero, indicating that no copy will occur.
749 const MCExpr *FrameAllocOffsetRef = nullptr;
750 if (HT.CatchObjRecoverIdx >= 0) {
751 MCSymbol *FrameAllocOffset =
752 Asm->OutContext.getOrCreateFrameAllocSymbol(
753 FuncLinkageName, HT.CatchObjRecoverIdx);
754 FrameAllocOffsetRef = MCSymbolRefExpr::create(
755 FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
756 } else if (HT.CatchObj.FrameIndex != INT_MAX) {
757 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex);
758 // For 32-bit, the catch object offset is relative to the end of the
759 // EH registration node. For 64-bit, it's relative to SP at the end of
761 if (!shouldEmitPersonality) {
762 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
763 Offset += FuncInfo.EHRegNodeEndOffset;
765 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
767 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
770 MCSymbol *HandlerSym = getMCSymbolForMBBOrGV(Asm, HT.Handler);
772 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
773 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
774 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
775 OS.EmitValue(create32bitRef(HandlerSym), 4); // Handler
777 if (shouldEmitPersonality) {
778 // With the new IR, this is always 16 + 8 + getMaxCallFrameSize().
779 // Keep this in sync with X86FrameLowering::emitPrologue.
780 int ParentFrameOffset =
781 16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
782 OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
788 // IPToStateMapEntry {
792 if (IPToStateXData) {
793 OS.EmitLabel(IPToStateXData);
794 for (auto &IPStatePair : IPToStateTable) {
795 OS.EmitValue(IPStatePair.first, 4); // IP
796 OS.EmitIntValue(IPStatePair.second, 4); // State
801 void WinException::computeIP2StateTable(
802 const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
803 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
804 // Remember what state we were in the last time we found a begin try label.
805 // This allows us to coalesce many nearby invokes with the same state into one
807 int LastEHState = -1;
808 MCSymbol *LastEndLabel = Asm->getFunctionBegin();
809 assert(LastEndLabel && "need local function start label");
811 // Indicate that all calls from the prologue to the first invoke unwind to
812 // caller. We handle this as a special case since other ranges starting at end
813 // labels need to use LtmpN+1.
814 IPToStateTable.push_back(std::make_pair(create32bitRef(LastEndLabel), -1));
816 for (const auto &MBB : *MF) {
817 // FIXME: Do we need to emit entries for funclet base states?
819 for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
820 assert(I.BeginLabel && I.EndLabel);
821 // If there was a potentially throwing call between this begin label and
822 // the last end label, we need an extra base state entry to indicate that
823 // those calls unwind directly to the caller.
824 if (I.SawPotentiallyThrowing && LastEHState != -1) {
825 IPToStateTable.push_back(
826 std::make_pair(getLabelPlusOne(LastEndLabel), -1));
830 // Emit an entry indicating that PCs after 'Label' have this EH state.
831 if (I.State != LastEHState)
832 IPToStateTable.push_back(
833 std::make_pair(getLabelPlusOne(I.BeginLabel), I.State));
834 LastEHState = I.State;
835 LastEndLabel = I.EndLabel;
839 if (LastEndLabel != Asm->getFunctionBegin()) {
840 // Indicate that all calls from the last invoke until the epilogue unwind to
841 // caller. This also ensures that we have at least one ip2state entry, if
842 // somehow all invokes were deleted during CodeGen.
843 IPToStateTable.push_back(std::make_pair(getLabelPlusOne(LastEndLabel), -1));
847 void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
848 StringRef FLinkageName) {
849 // Outlined helpers called by the EH runtime need to know the offset of the EH
850 // registration in order to recover the parent frame pointer. Now that we know
851 // we've code generated the parent, we can emit the label assignment that
852 // those helpers use to get the offset of the registration node.
853 assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
854 "no EH reg node localescape index");
855 MCSymbol *ParentFrameOffset =
856 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
857 MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
858 FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
859 const MCExpr *RegistrationOffsetSymRef =
860 MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
861 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
864 /// Emit the language-specific data that _except_handler3 and 4 expect. This is
865 /// functionally equivalent to the __C_specific_handler table, except it is
866 /// indexed by state number instead of IP.
867 void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
868 MCStreamer &OS = *Asm->OutStreamer;
869 const Function *F = MF->getFunction();
870 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
872 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
873 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
875 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
876 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
877 OS.EmitValueToAlignment(4);
878 OS.EmitLabel(LSDALabel);
880 const Function *Per =
881 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
882 StringRef PerName = Per->getName();
884 if (PerName == "_except_handler4") {
885 // The LSDA for _except_handler4 starts with this struct, followed by the
888 // struct EH4ScopeTable {
889 // int32_t GSCookieOffset;
890 // int32_t GSCookieXOROffset;
891 // int32_t EHCookieOffset;
892 // int32_t EHCookieXOROffset;
893 // ScopeTableEntry ScopeRecord[];
896 // Only the EHCookieOffset field appears to vary, and it appears to be the
897 // offset from the final saved SP value to the retaddr.
898 OS.EmitIntValue(-2, 4);
899 OS.EmitIntValue(0, 4);
901 OS.EmitIntValue(9999, 4);
902 OS.EmitIntValue(0, 4);
906 if (!FuncInfo.SEHUnwindMap.empty()) {
907 for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
908 MCSymbol *ExceptOrFinally =
909 UME.Handler.get<MachineBasicBlock *>()->getSymbol();
910 // -1 is usually the base state for "unwind to caller", but for
911 // _except_handler4 it's -2. Do that replacement here if necessary.
912 int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
913 OS.EmitIntValue(ToState, 4); // ToState
914 OS.EmitValue(create32bitRef(UME.Filter), 4); // Filter
915 OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
919 // FIXME: The following code is for the old landingpad-based SEH
920 // implementation. Remove it when possible.
922 // Build a list of pointers to LandingPadInfos and then sort by WinEHState.
923 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
924 SmallVector<const LandingPadInfo *, 4> LPads;
925 LPads.reserve((PadInfos.size()));
926 for (const LandingPadInfo &LPInfo : PadInfos)
927 LPads.push_back(&LPInfo);
928 std::sort(LPads.begin(), LPads.end(),
929 [](const LandingPadInfo *L, const LandingPadInfo *R) {
930 return L->WinEHState < R->WinEHState;
933 // For each action in each lpad, emit one of these:
934 // struct ScopeTableEntry {
935 // int32_t EnclosingLevel;
936 // int32_t (__cdecl *Filter)();
937 // void *HandlerOrFinally;
940 // The "outermost" action will use BaseState as its enclosing level. Each
941 // other action will refer to the previous state as its enclosing level.
943 for (const LandingPadInfo *LPInfo : LPads) {
944 int EnclosingLevel = BaseState;
945 assert(CurState + int(LPInfo->SEHHandlers.size()) - 1 ==
946 LPInfo->WinEHState &&
947 "gaps in the SEH scope table");
948 for (auto I = LPInfo->SEHHandlers.rbegin(), E = LPInfo->SEHHandlers.rend();
950 const SEHHandler &Handler = *I;
951 const BlockAddress *BA = Handler.RecoverBA;
952 const Function *F = Handler.FilterOrFinally;
953 assert(F && "cannot catch all in 32-bit SEH without filter function");
954 const MCExpr *FilterOrNull =
955 create32bitRef(BA ? Asm->getSymbol(F) : nullptr);
956 const MCExpr *ExceptOrFinally = create32bitRef(
957 BA ? Asm->GetBlockAddressSymbol(BA) : Asm->getSymbol(F));
959 OS.EmitIntValue(EnclosingLevel, 4);
960 OS.EmitValue(FilterOrNull, 4);
961 OS.EmitValue(ExceptOrFinally, 4);
963 // The next state unwinds to this state.
964 EnclosingLevel = CurState;