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();
71 shouldEmitMoves = Asm->needsSEHMoves();
73 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
74 unsigned PerEncoding = TLOF.getPersonalityEncoding();
75 const Function *Per = nullptr;
76 if (F->hasPersonalityFn())
77 Per = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
79 bool forceEmitPersonality =
80 F->hasPersonalityFn() && !isNoOpWithoutInvoke(classifyEHPersonality(Per)) &&
81 F->needsUnwindTableEntry();
83 shouldEmitPersonality =
84 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
85 PerEncoding != dwarf::DW_EH_PE_omit && Per);
87 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
88 shouldEmitLSDA = shouldEmitPersonality &&
89 LSDAEncoding != dwarf::DW_EH_PE_omit;
91 // 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.
93 if (!Asm->MAI->usesWindowsCFI()) {
94 shouldEmitLSDA = hasEHFunclets;
95 shouldEmitPersonality = false;
99 beginFunclet(MF->front(), Asm->CurrentFnSym);
102 /// endFunction - Gather and emit post-function exception information.
104 void WinException::endFunction(const MachineFunction *MF) {
105 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
108 const Function *F = MF->getFunction();
109 EHPersonality Per = EHPersonality::Unknown;
110 if (F->hasPersonalityFn())
111 Per = classifyEHPersonality(F->getPersonalityFn());
113 // 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))
117 MMI->TidyLandingPads();
121 // endFunclet will emit the necessary .xdata tables for x64 SEH.
122 if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
125 if (shouldEmitPersonality || shouldEmitLSDA) {
126 Asm->OutStreamer->PushSection();
128 // 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,
132 Asm->OutStreamer->SwitchSection(XData);
134 // 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.
136 if (Per == EHPersonality::MSVC_Win64SEH)
137 emitCSpecificHandlerTable(MF);
138 else if (Per == EHPersonality::MSVC_X86SEH)
139 emitExceptHandlerTable(MF);
140 else if (Per == EHPersonality::MSVC_CXX)
141 emitCXXFrameHandler3Table(MF);
143 emitExceptionTable();
145 Asm->OutStreamer->PopSection();
149 /// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
150 /// are used in the old WinEH scheme, and they will be removed eventually.
151 static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
152 const MachineBasicBlock *MBB) {
156 assert(MBB->isEHFuncletEntry());
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");
170 void WinException::beginFunclet(const MachineBasicBlock &MBB,
172 CurrentFuncletEntry = &MBB;
174 const Function *F = Asm->MF->getFunction();
175 // If a symbol was not provided for the funclet, invent one.
177 Sym = getMCSymbolForMBB(Asm, &MBB);
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();
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()),
191 // Now that we've emitted the alignment directive, point at our funclet.
192 Asm->OutStreamer->EmitLabel(Sym);
195 // Mark 'Sym' as starting our funclet.
196 if (shouldEmitMoves || shouldEmitPersonality)
197 Asm->OutStreamer->EmitWinCFIStartProc(Sym);
199 if (shouldEmitPersonality) {
200 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
201 const Function *PerFn = nullptr;
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);
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());
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);
221 void WinException::endFunclet() {
222 // No funclet to process? Great, we have nothing to do.
223 if (!CurrentFuncletEntry)
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());
232 // The .seh_handlerdata directive implicitly switches section, push the
233 // current section so that we may return to it.
234 Asm->OutStreamer->PushSection();
236 // Emit an UNWIND_INFO struct describing the prologue.
237 Asm->OutStreamer->EmitWinEHHandlerData();
239 if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
240 !CurrentFuncletEntry->isCleanupFuncletEntry()) {
241 // If this is a C++ catch funclet (or the parent function),
242 // emit a reference to the LSDA for the parent function.
243 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
244 MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
245 Twine("$cppxdata$", FuncLinkageName));
246 Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
247 } 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);
254 // Switch back to the previous section now that we are done writing to
256 Asm->OutStreamer->PopSection();
258 // Emit a .seh_endproc directive to mark the end of the function.
259 Asm->OutStreamer->EmitWinCFIEndProc();
262 // Let's make sure we don't try to end the same funclet twice.
263 CurrentFuncletEntry = nullptr;
266 const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
268 return MCConstantExpr::create(0, Asm->OutContext);
269 return MCSymbolRefExpr::create(Value, useImageRel32
270 ? MCSymbolRefExpr::VK_COFF_IMGREL32
271 : MCSymbolRefExpr::VK_None,
275 const MCExpr *WinException::create32bitRef(const Value *V) {
277 return MCConstantExpr::create(0, Asm->OutContext);
278 // 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)));
284 const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
285 return MCBinaryExpr::createAdd(create32bitRef(Label),
286 MCConstantExpr::create(1, Asm->OutContext),
290 int WinException::getFrameIndexOffset(int FrameIndex) {
291 const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
293 if (Asm->MAI->usesWindowsCFI())
294 return TFI.getFrameIndexReferenceFromSP(*Asm->MF, FrameIndex, UnusedReg);
295 return TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
299 /// Information describing an invoke range.
301 MCSymbol *BeginLabel = nullptr;
302 MCSymbol *EndLabel = nullptr;
305 /// If we saw a potentially throwing call between this range and the last
307 bool SawPotentiallyThrowing = false;
310 /// Iterator over the begin/end label pairs of invokes within a basic block.
311 class InvokeLabelIterator {
313 InvokeLabelIterator(WinEHFuncInfo &EHInfo,
314 MachineBasicBlock::const_iterator MBBI,
315 MachineBasicBlock::const_iterator MBBIEnd)
316 : EHInfo(EHInfo), MBBI(MBBI), MBBIEnd(MBBIEnd) {
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(); }
328 // Scan forward to find the next invoke range, or hit the end iterator.
329 InvokeLabelIterator &scan();
331 WinEHFuncInfo &EHInfo;
332 MachineBasicBlock::const_iterator MBBI;
333 MachineBasicBlock::const_iterator MBBIEnd;
334 InvokeRange CurRange;
336 } // end anonymous namespace
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.
340 InvokeLabelIterator &InvokeLabelIterator::scan() {
342 CurRange = InvokeRange{};
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.
348 CurRange.SawPotentiallyThrowing |=
349 !EHStreamer::callToNoUnwindFunction(&MI);
352 // Find the next EH_LABEL instruction.
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())
362 MBBI = MachineBasicBlock::const_iterator(&MI);
363 CurRange.BeginLabel = Label;
364 CurRange.EndLabel = StateAndEnd->second.second;
365 CurRange.State = StateAndEnd->second.first;
369 // If we didn't find a begin label, we are done, return the end iterator.
370 if (!CurRange.BeginLabel) {
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)
383 /// Utility for making a range for all the invoke ranges.
384 static iterator_range<InvokeLabelIterator>
385 invoke_ranges(WinEHFuncInfo &EHInfo, const MachineBasicBlock &MBB) {
386 return make_range(InvokeLabelIterator(EHInfo, MBB.begin(), MBB.end()),
387 InvokeLabelIterator(EHInfo, MBB.end(), MBB.end()));
390 /// 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
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.
408 /// Inferred table structure:
412 /// imagerel32 LabelStart;
413 /// imagerel32 LabelEnd;
414 /// imagerel32 FilterOrFinally; // One means catch-all.
415 /// imagerel32 LabelLPad; // Zero means __finally.
416 /// } Entries[NumEntries];
418 void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
419 auto &OS = *Asm->OutStreamer;
420 MCContext &Ctx = Asm->OutContext;
422 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
424 // 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
427 int LastEHState = -1;
428 MCSymbol *LastBeginLabel = nullptr;
429 MCSymbol *LastEndLabel = nullptr;
431 // 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);
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);
444 OS.EmitLabel(TableBegin);
446 // 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())
459 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
463 if (!I.SawPotentiallyThrowing && I.State == LastEHState) {
464 LastEndLabel = I.EndLabel;
468 // If this invoke ends a previous one, emit all the actions for this
470 if (LastEHState != -1)
471 emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel,
474 LastBeginLabel = I.BeginLabel;
475 LastEndLabel = I.EndLabel;
476 LastEHState = I.State;
480 // Hitting the end of the function causes us to emit the range for the
483 emitSEHActionsForRange(FuncInfo, LastBeginLabel, LastEndLabel, LastEHState);
485 OS.EmitLabel(TableEnd);
488 void WinException::emitSEHActionsForRange(WinEHFuncInfo &FuncInfo,
489 MCSymbol *BeginLabel,
490 MCSymbol *EndLabel, int State) {
491 auto &OS = *Asm->OutStreamer;
492 MCContext &Ctx = Asm->OutContext;
494 assert(BeginLabel && EndLabel);
495 while (State != -1) {
496 SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
497 const MCExpr *FilterOrFinally;
498 const MCExpr *ExceptOrNull;
499 auto *Handler = UME.Handler.get<MachineBasicBlock *>();
501 FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
502 ExceptOrNull = MCConstantExpr::create(0, Ctx);
504 // For an except, the filter can be 1 (catch-all) or a function
506 FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
507 : MCConstantExpr::create(1, Ctx);
508 ExceptOrNull = create32bitRef(Handler->getSymbol());
511 OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
512 OS.EmitValue(getLabelPlusOne(EndLabel), 4);
513 OS.EmitValue(FilterOrFinally, 4);
514 OS.EmitValue(ExceptOrNull, 4);
516 assert(UME.ToState < State && "states should decrease");
521 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
522 const Function *F = MF->getFunction();
523 auto &OS = *Asm->OutStreamer;
524 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
526 StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
528 SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
529 MCSymbol *FuncInfoXData = nullptr;
530 if (shouldEmitPersonality) {
531 // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
532 // IPs to state numbers.
534 Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
535 computeIP2StateTable(MF, FuncInfo, IPToStateTable);
537 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
538 emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
541 int UnwindHelpOffset = 0;
542 if (Asm->MAI->usesWindowsCFI())
543 UnwindHelpOffset = getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx);
545 MCSymbol *UnwindMapXData = nullptr;
546 MCSymbol *TryBlockMapXData = nullptr;
547 MCSymbol *IPToStateXData = nullptr;
548 if (!FuncInfo.CxxUnwindMap.empty())
549 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
550 Twine("$stateUnwindMap$", FuncLinkageName));
551 if (!FuncInfo.TryBlockMap.empty())
553 Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
554 if (!IPToStateTable.empty())
556 Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
559 // uint32_t MagicNumber
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;
570 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
571 // EHFlags & 2 -> ???
572 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
573 OS.EmitValueToAlignment(4);
574 OS.EmitLabel(FuncInfoXData);
575 OS.EmitIntValue(0x19930522, 4); // MagicNumber
576 OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4); // MaxState
577 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
578 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
579 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
580 OS.EmitIntValue(IPToStateTable.size(), 4); // IPMapEntries
581 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
582 if (Asm->MAI->usesWindowsCFI())
583 OS.EmitIntValue(UnwindHelpOffset, 4); // UnwindHelp
584 OS.EmitIntValue(0, 4); // ESTypeList
585 OS.EmitIntValue(1, 4); // EHFlags
591 if (UnwindMapXData) {
592 OS.EmitLabel(UnwindMapXData);
593 for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
594 MCSymbol *CleanupSym =
595 getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
596 OS.EmitIntValue(UME.ToState, 4); // ToState
597 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
604 // int32_t CatchHigh;
605 // int32_t NumCatches;
606 // HandlerType *HandlerArray;
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];
614 MCSymbol *HandlerMapXData = nullptr;
615 if (!TBME.HandlerArray.empty())
617 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
620 .concat(FuncLinkageName));
621 HandlerMaps.push_back(HandlerMapXData);
623 // 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");
627 assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
628 "bad trymap interval");
630 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
631 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
632 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
633 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
634 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
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)
643 // int32_t Adjectives;
644 // TypeDescriptor *Type;
645 // int32_t CatchObjOffset;
646 // void (*Handler)();
647 // int32_t ParentFrameOffset; // x64 only
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(
658 FuncLinkageName, HT.CatchObjRecoverIdx);
659 FrameAllocOffsetRef = MCSymbolRefExpr::create(
660 FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
661 } else if (HT.CatchObj.FrameIndex != INT_MAX) {
662 int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex);
663 // 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
666 if (!shouldEmitPersonality) {
667 assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
668 Offset += FuncInfo.EHRegNodeEndOffset;
670 FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
672 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
675 MCSymbol *HandlerSym =
676 getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
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
683 if (shouldEmitPersonality) {
684 // 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
694 // IPToStateMapEntry {
698 if (IPToStateXData) {
699 OS.EmitLabel(IPToStateXData);
700 for (auto &IPStatePair : IPToStateTable) {
701 OS.EmitValue(IPStatePair.first, 4); // IP
702 OS.EmitIntValue(IPStatePair.second, 4); // State
707 void WinException::computeIP2StateTable(
708 const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
709 SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
710 // 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
713 int LastEHState = -1;
714 MCSymbol *LastEndLabel = Asm->getFunctionBegin();
715 assert(LastEndLabel && "need local function start label");
717 // 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));
722 for (const auto &MBB : *MF) {
723 // FIXME: Do we need to emit entries for funclet base states?
725 for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
726 assert(I.BeginLabel && I.EndLabel);
727 // 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.
730 if (I.SawPotentiallyThrowing && LastEHState != -1) {
731 IPToStateTable.push_back(
732 std::make_pair(getLabelPlusOne(LastEndLabel), -1));
736 // Emit an entry indicating that PCs after 'Label' have this EH state.
737 if (I.State != LastEHState)
738 IPToStateTable.push_back(
739 std::make_pair(getLabelPlusOne(I.BeginLabel), I.State));
740 LastEHState = I.State;
741 LastEndLabel = I.EndLabel;
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));
753 void 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 &&
760 "no EH reg node localescape index");
761 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);
770 /// 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.
773 void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
774 MCStreamer &OS = *Asm->OutStreamer;
775 const Function *F = MF->getFunction();
776 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
778 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
779 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
781 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
782 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
783 OS.EmitValueToAlignment(4);
784 OS.EmitLabel(LSDALabel);
786 const Function *Per =
787 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
788 StringRef PerName = Per->getName();
790 if (PerName == "_except_handler4") {
791 // The LSDA for _except_handler4 starts with this struct, followed by the
794 // struct EH4ScopeTable {
795 // int32_t GSCookieOffset;
796 // int32_t GSCookieXOROffset;
797 // int32_t EHCookieOffset;
798 // int32_t EHCookieXOROffset;
799 // ScopeTableEntry ScopeRecord[];
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);
807 OS.EmitIntValue(9999, 4);
808 OS.EmitIntValue(0, 4);
812 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