xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinException.cpp (revision 8bcb0991864975618c09697b1aca10683346d9f0)
10b57cec5SDimitry Andric //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains support for writing Win64 exception info into asm files.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "WinException.h"
140b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
150b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
160b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
210b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
250b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
260b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
270b57cec5SDimitry Andric #include "llvm/IR/Module.h"
280b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
290b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
300b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
310b57cec5SDimitry Andric #include "llvm/MC/MCSection.h"
320b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
330b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
340b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
350b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
360b57cec5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
370b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
380b57cec5SDimitry Andric using namespace llvm;
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
410b57cec5SDimitry Andric   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
420b57cec5SDimitry Andric   // platforms use an imagerel32 relocation to refer to symbols.
430b57cec5SDimitry Andric   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
440b57cec5SDimitry Andric   isAArch64 = Asm->TM.getTargetTriple().isAArch64();
450b57cec5SDimitry Andric }
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric WinException::~WinException() {}
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric /// endModule - Emit all exception information that should come after the
500b57cec5SDimitry Andric /// content.
510b57cec5SDimitry Andric void WinException::endModule() {
520b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
530b57cec5SDimitry Andric   const Module *M = MMI->getModule();
540b57cec5SDimitry Andric   for (const Function &F : *M)
550b57cec5SDimitry Andric     if (F.hasFnAttribute("safeseh"))
560b57cec5SDimitry Andric       OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
570b57cec5SDimitry Andric }
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric void WinException::beginFunction(const MachineFunction *MF) {
600b57cec5SDimitry Andric   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric   // If any landing pads survive, we need an EH table.
630b57cec5SDimitry Andric   bool hasLandingPads = !MF->getLandingPads().empty();
640b57cec5SDimitry Andric   bool hasEHFunclets = MF->hasEHFunclets();
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric   const Function &F = MF->getFunction();
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric   shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
710b57cec5SDimitry Andric   unsigned PerEncoding = TLOF.getPersonalityEncoding();
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric   EHPersonality Per = EHPersonality::Unknown;
740b57cec5SDimitry Andric   const Function *PerFn = nullptr;
750b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
760b57cec5SDimitry Andric     PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
770b57cec5SDimitry Andric     Per = classifyEHPersonality(PerFn);
780b57cec5SDimitry Andric   }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric   bool forceEmitPersonality = F.hasPersonalityFn() &&
810b57cec5SDimitry Andric                               !isNoOpWithoutInvoke(Per) &&
820b57cec5SDimitry Andric                               F.needsUnwindTableEntry();
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric   shouldEmitPersonality =
850b57cec5SDimitry Andric       forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
860b57cec5SDimitry Andric                                PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
890b57cec5SDimitry Andric   shouldEmitLSDA = shouldEmitPersonality &&
900b57cec5SDimitry Andric     LSDAEncoding != dwarf::DW_EH_PE_omit;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   // If we're not using CFI, we don't want the CFI or the personality, but we
930b57cec5SDimitry Andric   // might want EH tables if we had EH pads.
940b57cec5SDimitry Andric   if (!Asm->MAI->usesWindowsCFI()) {
950b57cec5SDimitry Andric     if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
960b57cec5SDimitry Andric       // If this is 32-bit SEH and we don't have any funclets (really invokes),
970b57cec5SDimitry Andric       // make sure we emit the parent offset label. Some unreferenced filter
980b57cec5SDimitry Andric       // functions may still refer to it.
990b57cec5SDimitry Andric       const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
1000b57cec5SDimitry Andric       StringRef FLinkageName =
1010b57cec5SDimitry Andric           GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
1020b57cec5SDimitry Andric       emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
1030b57cec5SDimitry Andric     }
1040b57cec5SDimitry Andric     shouldEmitLSDA = hasEHFunclets;
1050b57cec5SDimitry Andric     shouldEmitPersonality = false;
1060b57cec5SDimitry Andric     return;
1070b57cec5SDimitry Andric   }
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   beginFunclet(MF->front(), Asm->CurrentFnSym);
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric void WinException::markFunctionEnd() {
1130b57cec5SDimitry Andric   if (isAArch64 && CurrentFuncletEntry &&
1140b57cec5SDimitry Andric       (shouldEmitMoves || shouldEmitPersonality))
1150b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
1160b57cec5SDimitry Andric }
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric /// endFunction - Gather and emit post-function exception information.
1190b57cec5SDimitry Andric ///
1200b57cec5SDimitry Andric void WinException::endFunction(const MachineFunction *MF) {
1210b57cec5SDimitry Andric   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
1220b57cec5SDimitry Andric     return;
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric   const Function &F = MF->getFunction();
1250b57cec5SDimitry Andric   EHPersonality Per = EHPersonality::Unknown;
1260b57cec5SDimitry Andric   if (F.hasPersonalityFn())
1270b57cec5SDimitry Andric     Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   // Get rid of any dead landing pads if we're not using funclets. In funclet
1300b57cec5SDimitry Andric   // schemes, the landing pad is not actually reachable. It only exists so
1310b57cec5SDimitry Andric   // that we can emit the right table data.
1320b57cec5SDimitry Andric   if (!isFuncletEHPersonality(Per)) {
1330b57cec5SDimitry Andric     MachineFunction *NonConstMF = const_cast<MachineFunction*>(MF);
1340b57cec5SDimitry Andric     NonConstMF->tidyLandingPads();
1350b57cec5SDimitry Andric   }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   endFuncletImpl();
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   // endFunclet will emit the necessary .xdata tables for x64 SEH.
1400b57cec5SDimitry Andric   if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets())
1410b57cec5SDimitry Andric     return;
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric   if (shouldEmitPersonality || shouldEmitLSDA) {
1440b57cec5SDimitry Andric     Asm->OutStreamer->PushSection();
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric     // Just switch sections to the right xdata section.
1470b57cec5SDimitry Andric     MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
1480b57cec5SDimitry Andric         Asm->OutStreamer->getCurrentSectionOnly());
1490b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(XData);
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric     // Emit the tables appropriate to the personality function in use. If we
1520b57cec5SDimitry Andric     // don't recognize the personality, assume it uses an Itanium-style LSDA.
1530b57cec5SDimitry Andric     if (Per == EHPersonality::MSVC_Win64SEH)
1540b57cec5SDimitry Andric       emitCSpecificHandlerTable(MF);
1550b57cec5SDimitry Andric     else if (Per == EHPersonality::MSVC_X86SEH)
1560b57cec5SDimitry Andric       emitExceptHandlerTable(MF);
1570b57cec5SDimitry Andric     else if (Per == EHPersonality::MSVC_CXX)
1580b57cec5SDimitry Andric       emitCXXFrameHandler3Table(MF);
1590b57cec5SDimitry Andric     else if (Per == EHPersonality::CoreCLR)
1600b57cec5SDimitry Andric       emitCLRExceptionTable(MF);
1610b57cec5SDimitry Andric     else
1620b57cec5SDimitry Andric       emitExceptionTable();
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric     Asm->OutStreamer->PopSection();
1650b57cec5SDimitry Andric   }
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric /// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
1690b57cec5SDimitry Andric static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
1700b57cec5SDimitry Andric                                    const MachineBasicBlock *MBB) {
1710b57cec5SDimitry Andric   if (!MBB)
1720b57cec5SDimitry Andric     return nullptr;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   assert(MBB->isEHFuncletEntry());
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   // Give catches and cleanups a name based off of their parent function and
1770b57cec5SDimitry Andric   // their funclet entry block's number.
1780b57cec5SDimitry Andric   const MachineFunction *MF = MBB->getParent();
1790b57cec5SDimitry Andric   const Function &F = MF->getFunction();
1800b57cec5SDimitry Andric   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
1810b57cec5SDimitry Andric   MCContext &Ctx = MF->getContext();
1820b57cec5SDimitry Andric   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
1830b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
1840b57cec5SDimitry Andric                                Twine(MBB->getNumber()) + "@?0?" +
1850b57cec5SDimitry Andric                                FuncLinkageName + "@4HA");
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric void WinException::beginFunclet(const MachineBasicBlock &MBB,
1890b57cec5SDimitry Andric                                 MCSymbol *Sym) {
1900b57cec5SDimitry Andric   CurrentFuncletEntry = &MBB;
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   const Function &F = Asm->MF->getFunction();
1930b57cec5SDimitry Andric   // If a symbol was not provided for the funclet, invent one.
1940b57cec5SDimitry Andric   if (!Sym) {
1950b57cec5SDimitry Andric     Sym = getMCSymbolForMBB(Asm, &MBB);
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric     // Describe our funclet symbol as a function with internal linkage.
1980b57cec5SDimitry Andric     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
1990b57cec5SDimitry Andric     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
2000b57cec5SDimitry Andric     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
2010b57cec5SDimitry Andric                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
2020b57cec5SDimitry Andric     Asm->OutStreamer->EndCOFFSymbolDef();
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric     // We want our funclet's entry point to be aligned such that no nops will be
2050b57cec5SDimitry Andric     // present after the label.
2060b57cec5SDimitry Andric     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
2070b57cec5SDimitry Andric                        &F);
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric     // Now that we've emitted the alignment directive, point at our funclet.
2100b57cec5SDimitry Andric     Asm->OutStreamer->EmitLabel(Sym);
2110b57cec5SDimitry Andric   }
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric   // Mark 'Sym' as starting our funclet.
2140b57cec5SDimitry Andric   if (shouldEmitMoves || shouldEmitPersonality) {
2150b57cec5SDimitry Andric     CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
2160b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
2170b57cec5SDimitry Andric   }
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric   if (shouldEmitPersonality) {
2200b57cec5SDimitry Andric     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2210b57cec5SDimitry Andric     const Function *PerFn = nullptr;
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric     // Determine which personality routine we are using for this funclet.
2240b57cec5SDimitry Andric     if (F.hasPersonalityFn())
2250b57cec5SDimitry Andric       PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2260b57cec5SDimitry Andric     const MCSymbol *PersHandlerSym =
2270b57cec5SDimitry Andric         TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric     // Do not emit a .seh_handler directives for cleanup funclets.
2300b57cec5SDimitry Andric     // FIXME: This means cleanup funclets cannot handle exceptions. Given that
2310b57cec5SDimitry Andric     // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
2320b57cec5SDimitry Andric     // inliner doesn't allow inlining them, this isn't a major problem in
2330b57cec5SDimitry Andric     // practice.
2340b57cec5SDimitry Andric     if (!CurrentFuncletEntry->isCleanupFuncletEntry())
2350b57cec5SDimitry Andric       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric void WinException::endFunclet() {
2400b57cec5SDimitry Andric   if (isAArch64 && CurrentFuncletEntry &&
2410b57cec5SDimitry Andric       (shouldEmitMoves || shouldEmitPersonality)) {
2420b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
2430b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
2440b57cec5SDimitry Andric   }
2450b57cec5SDimitry Andric   endFuncletImpl();
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric void WinException::endFuncletImpl() {
2490b57cec5SDimitry Andric   // No funclet to process?  Great, we have nothing to do.
2500b57cec5SDimitry Andric   if (!CurrentFuncletEntry)
2510b57cec5SDimitry Andric     return;
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   const MachineFunction *MF = Asm->MF;
2540b57cec5SDimitry Andric   if (shouldEmitMoves || shouldEmitPersonality) {
2550b57cec5SDimitry Andric     const Function &F = MF->getFunction();
2560b57cec5SDimitry Andric     EHPersonality Per = EHPersonality::Unknown;
2570b57cec5SDimitry Andric     if (F.hasPersonalityFn())
2580b57cec5SDimitry Andric       Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric     // On funclet exit, we emit a fake "function" end marker, so that the call
2610b57cec5SDimitry Andric     // to EmitWinEHHandlerData below can calculate the size of the funclet or
2620b57cec5SDimitry Andric     // function.
2630b57cec5SDimitry Andric     if (isAArch64) {
2640b57cec5SDimitry Andric       MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
2650b57cec5SDimitry Andric           Asm->OutStreamer->getCurrentSectionOnly());
2660b57cec5SDimitry Andric       Asm->OutStreamer->SwitchSection(XData);
2670b57cec5SDimitry Andric     }
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric     // Emit an UNWIND_INFO struct describing the prologue.
2700b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinEHHandlerData();
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
2730b57cec5SDimitry Andric         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
2740b57cec5SDimitry Andric       // If this is a C++ catch funclet (or the parent function),
2750b57cec5SDimitry Andric       // emit a reference to the LSDA for the parent function.
2760b57cec5SDimitry Andric       StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
2770b57cec5SDimitry Andric       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
2780b57cec5SDimitry Andric           Twine("$cppxdata$", FuncLinkageName));
2790b57cec5SDimitry Andric       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
2800b57cec5SDimitry Andric     } else if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets() &&
2810b57cec5SDimitry Andric                !CurrentFuncletEntry->isEHFuncletEntry()) {
2820b57cec5SDimitry Andric       // If this is the parent function in Win64 SEH, emit the LSDA immediately
2830b57cec5SDimitry Andric       // following .seh_handlerdata.
2840b57cec5SDimitry Andric       emitCSpecificHandlerTable(MF);
2850b57cec5SDimitry Andric     }
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric     // Switch back to the funclet start .text section now that we are done
2880b57cec5SDimitry Andric     // writing to .xdata, and emit an .seh_endproc directive to mark the end of
2890b57cec5SDimitry Andric     // the function.
2900b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
2910b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIEndProc();
2920b57cec5SDimitry Andric   }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   // Let's make sure we don't try to end the same funclet twice.
2950b57cec5SDimitry Andric   CurrentFuncletEntry = nullptr;
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
2990b57cec5SDimitry Andric   if (!Value)
3000b57cec5SDimitry Andric     return MCConstantExpr::create(0, Asm->OutContext);
3010b57cec5SDimitry Andric   return MCSymbolRefExpr::create(Value, useImageRel32
3020b57cec5SDimitry Andric                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
3030b57cec5SDimitry Andric                                             : MCSymbolRefExpr::VK_None,
3040b57cec5SDimitry Andric                                  Asm->OutContext);
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
3080b57cec5SDimitry Andric   if (!GV)
3090b57cec5SDimitry Andric     return MCConstantExpr::create(0, Asm->OutContext);
3100b57cec5SDimitry Andric   return create32bitRef(Asm->getSymbol(GV));
3110b57cec5SDimitry Andric }
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric const MCExpr *WinException::getLabel(const MCSymbol *Label) {
3140b57cec5SDimitry Andric   if (isAArch64)
3150b57cec5SDimitry Andric     return MCSymbolRefExpr::create(Label, MCSymbolRefExpr::VK_COFF_IMGREL32,
3160b57cec5SDimitry Andric                                    Asm->OutContext);
3170b57cec5SDimitry Andric   return MCBinaryExpr::createAdd(create32bitRef(Label),
3180b57cec5SDimitry Andric                                  MCConstantExpr::create(1, Asm->OutContext),
3190b57cec5SDimitry Andric                                  Asm->OutContext);
3200b57cec5SDimitry Andric }
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
3230b57cec5SDimitry Andric                                       const MCSymbol *OffsetFrom) {
3240b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
3250b57cec5SDimitry Andric       MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
3260b57cec5SDimitry Andric       MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
3270b57cec5SDimitry Andric }
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
3300b57cec5SDimitry Andric                                              const MCSymbol *OffsetFrom) {
3310b57cec5SDimitry Andric   return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
3320b57cec5SDimitry Andric                                  MCConstantExpr::create(1, Asm->OutContext),
3330b57cec5SDimitry Andric                                  Asm->OutContext);
3340b57cec5SDimitry Andric }
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric int WinException::getFrameIndexOffset(int FrameIndex,
3370b57cec5SDimitry Andric                                       const WinEHFuncInfo &FuncInfo) {
3380b57cec5SDimitry Andric   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
3390b57cec5SDimitry Andric   unsigned UnusedReg;
3400b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI()) {
3410b57cec5SDimitry Andric     int Offset =
3420b57cec5SDimitry Andric         TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
3430b57cec5SDimitry Andric                                            /*IgnoreSPUpdates*/ true);
3440b57cec5SDimitry Andric     assert(UnusedReg ==
3450b57cec5SDimitry Andric            Asm->MF->getSubtarget()
3460b57cec5SDimitry Andric                .getTargetLowering()
3470b57cec5SDimitry Andric                ->getStackPointerRegisterToSaveRestore());
3480b57cec5SDimitry Andric     return Offset;
3490b57cec5SDimitry Andric   }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   // For 32-bit, offsets should be relative to the end of the EH registration
3520b57cec5SDimitry Andric   // node. For 64-bit, it's relative to SP at the end of the prologue.
3530b57cec5SDimitry Andric   assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
3540b57cec5SDimitry Andric   int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
3550b57cec5SDimitry Andric   Offset += FuncInfo.EHRegNodeEndOffset;
3560b57cec5SDimitry Andric   return Offset;
3570b57cec5SDimitry Andric }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric namespace {
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric /// Top-level state used to represent unwind to caller
3620b57cec5SDimitry Andric const int NullState = -1;
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric struct InvokeStateChange {
3650b57cec5SDimitry Andric   /// EH Label immediately after the last invoke in the previous state, or
3660b57cec5SDimitry Andric   /// nullptr if the previous state was the null state.
3670b57cec5SDimitry Andric   const MCSymbol *PreviousEndLabel;
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   /// EH label immediately before the first invoke in the new state, or nullptr
3700b57cec5SDimitry Andric   /// if the new state is the null state.
3710b57cec5SDimitry Andric   const MCSymbol *NewStartLabel;
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   /// State of the invoke following NewStartLabel, or NullState to indicate
3740b57cec5SDimitry Andric   /// the presence of calls which may unwind to caller.
3750b57cec5SDimitry Andric   int NewState;
3760b57cec5SDimitry Andric };
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric /// Iterator that reports all the invoke state changes in a range of machine
3790b57cec5SDimitry Andric /// basic blocks.  Changes to the null state are reported whenever a call that
3800b57cec5SDimitry Andric /// may unwind to caller is encountered.  The MBB range is expected to be an
3810b57cec5SDimitry Andric /// entire function or funclet, and the start and end of the range are treated
3820b57cec5SDimitry Andric /// as being in the NullState even if there's not an unwind-to-caller call
3830b57cec5SDimitry Andric /// before the first invoke or after the last one (i.e., the first state change
3840b57cec5SDimitry Andric /// reported is the first change to something other than NullState, and a
3850b57cec5SDimitry Andric /// change back to NullState is always reported at the end of iteration).
3860b57cec5SDimitry Andric class InvokeStateChangeIterator {
3870b57cec5SDimitry Andric   InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
3880b57cec5SDimitry Andric                             MachineFunction::const_iterator MFI,
3890b57cec5SDimitry Andric                             MachineFunction::const_iterator MFE,
3900b57cec5SDimitry Andric                             MachineBasicBlock::const_iterator MBBI,
3910b57cec5SDimitry Andric                             int BaseState)
3920b57cec5SDimitry Andric       : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
3930b57cec5SDimitry Andric     LastStateChange.PreviousEndLabel = nullptr;
3940b57cec5SDimitry Andric     LastStateChange.NewStartLabel = nullptr;
3950b57cec5SDimitry Andric     LastStateChange.NewState = BaseState;
3960b57cec5SDimitry Andric     scan();
3970b57cec5SDimitry Andric   }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric public:
4000b57cec5SDimitry Andric   static iterator_range<InvokeStateChangeIterator>
4010b57cec5SDimitry Andric   range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
4020b57cec5SDimitry Andric         MachineFunction::const_iterator End, int BaseState = NullState) {
4030b57cec5SDimitry Andric     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
4040b57cec5SDimitry Andric     // the end of the last block.
4050b57cec5SDimitry Andric     assert(Begin != End);
4060b57cec5SDimitry Andric     auto BlockBegin = Begin->begin();
4070b57cec5SDimitry Andric     auto BlockEnd = std::prev(End)->end();
4080b57cec5SDimitry Andric     return make_range(
4090b57cec5SDimitry Andric         InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
4100b57cec5SDimitry Andric         InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
4110b57cec5SDimitry Andric   }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   // Iterator methods.
4140b57cec5SDimitry Andric   bool operator==(const InvokeStateChangeIterator &O) const {
4150b57cec5SDimitry Andric     assert(BaseState == O.BaseState);
4160b57cec5SDimitry Andric     // Must be visiting same block.
4170b57cec5SDimitry Andric     if (MFI != O.MFI)
4180b57cec5SDimitry Andric       return false;
4190b57cec5SDimitry Andric     // Must be visiting same isntr.
4200b57cec5SDimitry Andric     if (MBBI != O.MBBI)
4210b57cec5SDimitry Andric       return false;
4220b57cec5SDimitry Andric     // At end of block/instr iteration, we can still have two distinct states:
4230b57cec5SDimitry Andric     // one to report the final EndLabel, and another indicating the end of the
4240b57cec5SDimitry Andric     // state change iteration.  Check for CurrentEndLabel equality to
4250b57cec5SDimitry Andric     // distinguish these.
4260b57cec5SDimitry Andric     return CurrentEndLabel == O.CurrentEndLabel;
4270b57cec5SDimitry Andric   }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   bool operator!=(const InvokeStateChangeIterator &O) const {
4300b57cec5SDimitry Andric     return !operator==(O);
4310b57cec5SDimitry Andric   }
4320b57cec5SDimitry Andric   InvokeStateChange &operator*() { return LastStateChange; }
4330b57cec5SDimitry Andric   InvokeStateChange *operator->() { return &LastStateChange; }
4340b57cec5SDimitry Andric   InvokeStateChangeIterator &operator++() { return scan(); }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric private:
4370b57cec5SDimitry Andric   InvokeStateChangeIterator &scan();
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric   const WinEHFuncInfo &EHInfo;
4400b57cec5SDimitry Andric   const MCSymbol *CurrentEndLabel = nullptr;
4410b57cec5SDimitry Andric   MachineFunction::const_iterator MFI;
4420b57cec5SDimitry Andric   MachineFunction::const_iterator MFE;
4430b57cec5SDimitry Andric   MachineBasicBlock::const_iterator MBBI;
4440b57cec5SDimitry Andric   InvokeStateChange LastStateChange;
4450b57cec5SDimitry Andric   bool VisitingInvoke = false;
4460b57cec5SDimitry Andric   int BaseState;
4470b57cec5SDimitry Andric };
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric } // end anonymous namespace
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
4520b57cec5SDimitry Andric   bool IsNewBlock = false;
4530b57cec5SDimitry Andric   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
4540b57cec5SDimitry Andric     if (IsNewBlock)
4550b57cec5SDimitry Andric       MBBI = MFI->begin();
4560b57cec5SDimitry Andric     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
4570b57cec5SDimitry Andric       const MachineInstr &MI = *MBBI;
4580b57cec5SDimitry Andric       if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
4590b57cec5SDimitry Andric           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
4600b57cec5SDimitry Andric         // Indicate a change of state to the null state.  We don't have
4610b57cec5SDimitry Andric         // start/end EH labels handy but the caller won't expect them for
4620b57cec5SDimitry Andric         // null state regions.
4630b57cec5SDimitry Andric         LastStateChange.PreviousEndLabel = CurrentEndLabel;
4640b57cec5SDimitry Andric         LastStateChange.NewStartLabel = nullptr;
4650b57cec5SDimitry Andric         LastStateChange.NewState = BaseState;
4660b57cec5SDimitry Andric         CurrentEndLabel = nullptr;
4670b57cec5SDimitry Andric         // Don't re-visit this instr on the next scan
4680b57cec5SDimitry Andric         ++MBBI;
4690b57cec5SDimitry Andric         return *this;
4700b57cec5SDimitry Andric       }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric       // All other state changes are at EH labels before/after invokes.
4730b57cec5SDimitry Andric       if (!MI.isEHLabel())
4740b57cec5SDimitry Andric         continue;
4750b57cec5SDimitry Andric       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
4760b57cec5SDimitry Andric       if (Label == CurrentEndLabel) {
4770b57cec5SDimitry Andric         VisitingInvoke = false;
4780b57cec5SDimitry Andric         continue;
4790b57cec5SDimitry Andric       }
4800b57cec5SDimitry Andric       auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
4810b57cec5SDimitry Andric       // Ignore EH labels that aren't the ones inserted before an invoke
4820b57cec5SDimitry Andric       if (InvokeMapIter == EHInfo.LabelToStateMap.end())
4830b57cec5SDimitry Andric         continue;
4840b57cec5SDimitry Andric       auto &StateAndEnd = InvokeMapIter->second;
4850b57cec5SDimitry Andric       int NewState = StateAndEnd.first;
4860b57cec5SDimitry Andric       // Keep track of the fact that we're between EH start/end labels so
4870b57cec5SDimitry Andric       // we know not to treat the inoke we'll see as unwinding to caller.
4880b57cec5SDimitry Andric       VisitingInvoke = true;
4890b57cec5SDimitry Andric       if (NewState == LastStateChange.NewState) {
4900b57cec5SDimitry Andric         // The state isn't actually changing here.  Record the new end and
4910b57cec5SDimitry Andric         // keep going.
4920b57cec5SDimitry Andric         CurrentEndLabel = StateAndEnd.second;
4930b57cec5SDimitry Andric         continue;
4940b57cec5SDimitry Andric       }
4950b57cec5SDimitry Andric       // Found a state change to report
4960b57cec5SDimitry Andric       LastStateChange.PreviousEndLabel = CurrentEndLabel;
4970b57cec5SDimitry Andric       LastStateChange.NewStartLabel = Label;
4980b57cec5SDimitry Andric       LastStateChange.NewState = NewState;
4990b57cec5SDimitry Andric       // Start keeping track of the new current end
5000b57cec5SDimitry Andric       CurrentEndLabel = StateAndEnd.second;
5010b57cec5SDimitry Andric       // Don't re-visit this instr on the next scan
5020b57cec5SDimitry Andric       ++MBBI;
5030b57cec5SDimitry Andric       return *this;
5040b57cec5SDimitry Andric     }
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric   // Iteration hit the end of the block range.
5070b57cec5SDimitry Andric   if (LastStateChange.NewState != BaseState) {
5080b57cec5SDimitry Andric     // Report the end of the last new state
5090b57cec5SDimitry Andric     LastStateChange.PreviousEndLabel = CurrentEndLabel;
5100b57cec5SDimitry Andric     LastStateChange.NewStartLabel = nullptr;
5110b57cec5SDimitry Andric     LastStateChange.NewState = BaseState;
5120b57cec5SDimitry Andric     // Leave CurrentEndLabel non-null to distinguish this state from end.
5130b57cec5SDimitry Andric     assert(CurrentEndLabel != nullptr);
5140b57cec5SDimitry Andric     return *this;
5150b57cec5SDimitry Andric   }
5160b57cec5SDimitry Andric   // We've reported all state changes and hit the end state.
5170b57cec5SDimitry Andric   CurrentEndLabel = nullptr;
5180b57cec5SDimitry Andric   return *this;
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric /// Emit the language-specific data that __C_specific_handler expects.  This
5220b57cec5SDimitry Andric /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
5230b57cec5SDimitry Andric /// up after faults with __try, __except, and __finally.  The typeinfo values
5240b57cec5SDimitry Andric /// are not really RTTI data, but pointers to filter functions that return an
5250b57cec5SDimitry Andric /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
5260b57cec5SDimitry Andric /// blocks and other cleanups, the landing pad label is zero, and the filter
5270b57cec5SDimitry Andric /// function is actually a cleanup handler with the same prototype.  A catch-all
5280b57cec5SDimitry Andric /// entry is modeled with a null filter function field and a non-zero landing
5290b57cec5SDimitry Andric /// pad label.
5300b57cec5SDimitry Andric ///
5310b57cec5SDimitry Andric /// Possible filter function return values:
5320b57cec5SDimitry Andric ///   EXCEPTION_EXECUTE_HANDLER (1):
5330b57cec5SDimitry Andric ///     Jump to the landing pad label after cleanups.
5340b57cec5SDimitry Andric ///   EXCEPTION_CONTINUE_SEARCH (0):
5350b57cec5SDimitry Andric ///     Continue searching this table or continue unwinding.
5360b57cec5SDimitry Andric ///   EXCEPTION_CONTINUE_EXECUTION (-1):
5370b57cec5SDimitry Andric ///     Resume execution at the trapping PC.
5380b57cec5SDimitry Andric ///
5390b57cec5SDimitry Andric /// Inferred table structure:
5400b57cec5SDimitry Andric ///   struct Table {
5410b57cec5SDimitry Andric ///     int NumEntries;
5420b57cec5SDimitry Andric ///     struct Entry {
5430b57cec5SDimitry Andric ///       imagerel32 LabelStart;
5440b57cec5SDimitry Andric ///       imagerel32 LabelEnd;
5450b57cec5SDimitry Andric ///       imagerel32 FilterOrFinally;  // One means catch-all.
5460b57cec5SDimitry Andric ///       imagerel32 LabelLPad;        // Zero means __finally.
5470b57cec5SDimitry Andric ///     } Entries[NumEntries];
5480b57cec5SDimitry Andric ///   };
5490b57cec5SDimitry Andric void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
5500b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
5510b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
5520b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
5550b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
5560b57cec5SDimitry Andric     if (VerboseAsm)
5570b57cec5SDimitry Andric       OS.AddComment(Comment);
5580b57cec5SDimitry Andric   };
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric   if (!isAArch64) {
5610b57cec5SDimitry Andric     // Emit a label assignment with the SEH frame offset so we can use it for
5620b57cec5SDimitry Andric     // llvm.eh.recoverfp.
5630b57cec5SDimitry Andric     StringRef FLinkageName =
5640b57cec5SDimitry Andric         GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
5650b57cec5SDimitry Andric     MCSymbol *ParentFrameOffset =
5660b57cec5SDimitry Andric         Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
5670b57cec5SDimitry Andric     const MCExpr *MCOffset =
5680b57cec5SDimitry Andric         MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
5690b57cec5SDimitry Andric     Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
5700b57cec5SDimitry Andric   }
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   // Use the assembler to compute the number of table entries through label
5730b57cec5SDimitry Andric   // difference and division.
5740b57cec5SDimitry Andric   MCSymbol *TableBegin =
5750b57cec5SDimitry Andric       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
5760b57cec5SDimitry Andric   MCSymbol *TableEnd =
5770b57cec5SDimitry Andric       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
5780b57cec5SDimitry Andric   const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
5790b57cec5SDimitry Andric   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
5800b57cec5SDimitry Andric   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
5810b57cec5SDimitry Andric   AddComment("Number of call sites");
5820b57cec5SDimitry Andric   OS.EmitValue(EntryCount, 4);
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   OS.EmitLabel(TableBegin);
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
5870b57cec5SDimitry Andric   // models exceptions from invokes. LLVM also allows arbitrary reordering of
5880b57cec5SDimitry Andric   // the code, so our tables end up looking a bit different. Rather than
5890b57cec5SDimitry Andric   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
5900b57cec5SDimitry Andric   // each range of invokes in the same state, we emit table entries for all
5910b57cec5SDimitry Andric   // the actions that would be taken in that state. This means our tables are
5920b57cec5SDimitry Andric   // slightly bigger, which is OK.
5930b57cec5SDimitry Andric   const MCSymbol *LastStartLabel = nullptr;
5940b57cec5SDimitry Andric   int LastEHState = -1;
5950b57cec5SDimitry Andric   // Break out before we enter into a finally funclet.
5960b57cec5SDimitry Andric   // FIXME: We need to emit separate EH tables for cleanups.
5970b57cec5SDimitry Andric   MachineFunction::const_iterator End = MF->end();
5980b57cec5SDimitry Andric   MachineFunction::const_iterator Stop = std::next(MF->begin());
5990b57cec5SDimitry Andric   while (Stop != End && !Stop->isEHFuncletEntry())
6000b57cec5SDimitry Andric     ++Stop;
6010b57cec5SDimitry Andric   for (const auto &StateChange :
6020b57cec5SDimitry Andric        InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
6030b57cec5SDimitry Andric     // Emit all the actions for the state we just transitioned out of
6040b57cec5SDimitry Andric     // if it was not the null state
6050b57cec5SDimitry Andric     if (LastEHState != -1)
6060b57cec5SDimitry Andric       emitSEHActionsForRange(FuncInfo, LastStartLabel,
6070b57cec5SDimitry Andric                              StateChange.PreviousEndLabel, LastEHState);
6080b57cec5SDimitry Andric     LastStartLabel = StateChange.NewStartLabel;
6090b57cec5SDimitry Andric     LastEHState = StateChange.NewState;
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   OS.EmitLabel(TableEnd);
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
6160b57cec5SDimitry Andric                                           const MCSymbol *BeginLabel,
6170b57cec5SDimitry Andric                                           const MCSymbol *EndLabel, int State) {
6180b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
6190b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
6200b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
6210b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
6220b57cec5SDimitry Andric     if (VerboseAsm)
6230b57cec5SDimitry Andric       OS.AddComment(Comment);
6240b57cec5SDimitry Andric   };
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   assert(BeginLabel && EndLabel);
6270b57cec5SDimitry Andric   while (State != -1) {
6280b57cec5SDimitry Andric     const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
6290b57cec5SDimitry Andric     const MCExpr *FilterOrFinally;
6300b57cec5SDimitry Andric     const MCExpr *ExceptOrNull;
6310b57cec5SDimitry Andric     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
6320b57cec5SDimitry Andric     if (UME.IsFinally) {
6330b57cec5SDimitry Andric       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
6340b57cec5SDimitry Andric       ExceptOrNull = MCConstantExpr::create(0, Ctx);
6350b57cec5SDimitry Andric     } else {
6360b57cec5SDimitry Andric       // For an except, the filter can be 1 (catch-all) or a function
6370b57cec5SDimitry Andric       // label.
6380b57cec5SDimitry Andric       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
6390b57cec5SDimitry Andric                                    : MCConstantExpr::create(1, Ctx);
6400b57cec5SDimitry Andric       ExceptOrNull = create32bitRef(Handler->getSymbol());
6410b57cec5SDimitry Andric     }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric     AddComment("LabelStart");
6440b57cec5SDimitry Andric     OS.EmitValue(getLabel(BeginLabel), 4);
6450b57cec5SDimitry Andric     AddComment("LabelEnd");
6460b57cec5SDimitry Andric     OS.EmitValue(getLabel(EndLabel), 4);
6470b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
6480b57cec5SDimitry Andric                                                              : "CatchAll");
6490b57cec5SDimitry Andric     OS.EmitValue(FilterOrFinally, 4);
6500b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
6510b57cec5SDimitry Andric     OS.EmitValue(ExceptOrNull, 4);
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric     assert(UME.ToState < State && "states should decrease");
6540b57cec5SDimitry Andric     State = UME.ToState;
6550b57cec5SDimitry Andric   }
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
6590b57cec5SDimitry Andric   const Function &F = MF->getFunction();
6600b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
6610b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
6660b57cec5SDimitry Andric   MCSymbol *FuncInfoXData = nullptr;
6670b57cec5SDimitry Andric   if (shouldEmitPersonality) {
6680b57cec5SDimitry Andric     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
6690b57cec5SDimitry Andric     // IPs to state numbers.
6700b57cec5SDimitry Andric     FuncInfoXData =
6710b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
6720b57cec5SDimitry Andric     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
6730b57cec5SDimitry Andric   } else {
6740b57cec5SDimitry Andric     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
6750b57cec5SDimitry Andric   }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric   int UnwindHelpOffset = 0;
6780b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI())
6790b57cec5SDimitry Andric     UnwindHelpOffset =
6800b57cec5SDimitry Andric         getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   MCSymbol *UnwindMapXData = nullptr;
6830b57cec5SDimitry Andric   MCSymbol *TryBlockMapXData = nullptr;
6840b57cec5SDimitry Andric   MCSymbol *IPToStateXData = nullptr;
6850b57cec5SDimitry Andric   if (!FuncInfo.CxxUnwindMap.empty())
6860b57cec5SDimitry Andric     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
6870b57cec5SDimitry Andric         Twine("$stateUnwindMap$", FuncLinkageName));
6880b57cec5SDimitry Andric   if (!FuncInfo.TryBlockMap.empty())
6890b57cec5SDimitry Andric     TryBlockMapXData =
6900b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
6910b57cec5SDimitry Andric   if (!IPToStateTable.empty())
6920b57cec5SDimitry Andric     IPToStateXData =
6930b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
6960b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
6970b57cec5SDimitry Andric     if (VerboseAsm)
6980b57cec5SDimitry Andric       OS.AddComment(Comment);
6990b57cec5SDimitry Andric   };
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   // FuncInfo {
7020b57cec5SDimitry Andric   //   uint32_t           MagicNumber
7030b57cec5SDimitry Andric   //   int32_t            MaxState;
7040b57cec5SDimitry Andric   //   UnwindMapEntry    *UnwindMap;
7050b57cec5SDimitry Andric   //   uint32_t           NumTryBlocks;
7060b57cec5SDimitry Andric   //   TryBlockMapEntry  *TryBlockMap;
7070b57cec5SDimitry Andric   //   uint32_t           IPMapEntries; // always 0 for x86
7080b57cec5SDimitry Andric   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
7090b57cec5SDimitry Andric   //   uint32_t           UnwindHelp;   // non-x86 only
7100b57cec5SDimitry Andric   //   ESTypeList        *ESTypeList;
7110b57cec5SDimitry Andric   //   int32_t            EHFlags;
7120b57cec5SDimitry Andric   // }
7130b57cec5SDimitry Andric   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
7140b57cec5SDimitry Andric   // EHFlags & 2 -> ???
7150b57cec5SDimitry Andric   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
7160b57cec5SDimitry Andric   OS.EmitValueToAlignment(4);
7170b57cec5SDimitry Andric   OS.EmitLabel(FuncInfoXData);
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   AddComment("MagicNumber");
7200b57cec5SDimitry Andric   OS.EmitIntValue(0x19930522, 4);
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric   AddComment("MaxState");
7230b57cec5SDimitry Andric   OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric   AddComment("UnwindMap");
7260b57cec5SDimitry Andric   OS.EmitValue(create32bitRef(UnwindMapXData), 4);
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   AddComment("NumTryBlocks");
7290b57cec5SDimitry Andric   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric   AddComment("TryBlockMap");
7320b57cec5SDimitry Andric   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric   AddComment("IPMapEntries");
7350b57cec5SDimitry Andric   OS.EmitIntValue(IPToStateTable.size(), 4);
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric   AddComment("IPToStateXData");
7380b57cec5SDimitry Andric   OS.EmitValue(create32bitRef(IPToStateXData), 4);
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI()) {
7410b57cec5SDimitry Andric     AddComment("UnwindHelp");
7420b57cec5SDimitry Andric     OS.EmitIntValue(UnwindHelpOffset, 4);
7430b57cec5SDimitry Andric   }
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   AddComment("ESTypeList");
7460b57cec5SDimitry Andric   OS.EmitIntValue(0, 4);
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   AddComment("EHFlags");
7490b57cec5SDimitry Andric   OS.EmitIntValue(1, 4);
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   // UnwindMapEntry {
7520b57cec5SDimitry Andric   //   int32_t ToState;
7530b57cec5SDimitry Andric   //   void  (*Action)();
7540b57cec5SDimitry Andric   // };
7550b57cec5SDimitry Andric   if (UnwindMapXData) {
7560b57cec5SDimitry Andric     OS.EmitLabel(UnwindMapXData);
7570b57cec5SDimitry Andric     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
7580b57cec5SDimitry Andric       MCSymbol *CleanupSym =
7590b57cec5SDimitry Andric           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
7600b57cec5SDimitry Andric       AddComment("ToState");
7610b57cec5SDimitry Andric       OS.EmitIntValue(UME.ToState, 4);
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric       AddComment("Action");
7640b57cec5SDimitry Andric       OS.EmitValue(create32bitRef(CleanupSym), 4);
7650b57cec5SDimitry Andric     }
7660b57cec5SDimitry Andric   }
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   // TryBlockMap {
7690b57cec5SDimitry Andric   //   int32_t      TryLow;
7700b57cec5SDimitry Andric   //   int32_t      TryHigh;
7710b57cec5SDimitry Andric   //   int32_t      CatchHigh;
7720b57cec5SDimitry Andric   //   int32_t      NumCatches;
7730b57cec5SDimitry Andric   //   HandlerType *HandlerArray;
7740b57cec5SDimitry Andric   // };
7750b57cec5SDimitry Andric   if (TryBlockMapXData) {
7760b57cec5SDimitry Andric     OS.EmitLabel(TryBlockMapXData);
7770b57cec5SDimitry Andric     SmallVector<MCSymbol *, 1> HandlerMaps;
7780b57cec5SDimitry Andric     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
7790b57cec5SDimitry Andric       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric       MCSymbol *HandlerMapXData = nullptr;
7820b57cec5SDimitry Andric       if (!TBME.HandlerArray.empty())
7830b57cec5SDimitry Andric         HandlerMapXData =
7840b57cec5SDimitry Andric             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
7850b57cec5SDimitry Andric                                                   .concat(Twine(I))
7860b57cec5SDimitry Andric                                                   .concat("$")
7870b57cec5SDimitry Andric                                                   .concat(FuncLinkageName));
7880b57cec5SDimitry Andric       HandlerMaps.push_back(HandlerMapXData);
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric       // TBMEs should form intervals.
7910b57cec5SDimitry Andric       assert(0 <= TBME.TryLow && "bad trymap interval");
7920b57cec5SDimitry Andric       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
7930b57cec5SDimitry Andric       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
7940b57cec5SDimitry Andric       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
7950b57cec5SDimitry Andric              "bad trymap interval");
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric       AddComment("TryLow");
7980b57cec5SDimitry Andric       OS.EmitIntValue(TBME.TryLow, 4);
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric       AddComment("TryHigh");
8010b57cec5SDimitry Andric       OS.EmitIntValue(TBME.TryHigh, 4);
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric       AddComment("CatchHigh");
8040b57cec5SDimitry Andric       OS.EmitIntValue(TBME.CatchHigh, 4);
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric       AddComment("NumCatches");
8070b57cec5SDimitry Andric       OS.EmitIntValue(TBME.HandlerArray.size(), 4);
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric       AddComment("HandlerArray");
8100b57cec5SDimitry Andric       OS.EmitValue(create32bitRef(HandlerMapXData), 4);
8110b57cec5SDimitry Andric     }
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric     // All funclets use the same parent frame offset currently.
8140b57cec5SDimitry Andric     unsigned ParentFrameOffset = 0;
8150b57cec5SDimitry Andric     if (shouldEmitPersonality) {
8160b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
8170b57cec5SDimitry Andric       ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
8180b57cec5SDimitry Andric     }
8190b57cec5SDimitry Andric 
8200b57cec5SDimitry Andric     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
8210b57cec5SDimitry Andric       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
8220b57cec5SDimitry Andric       MCSymbol *HandlerMapXData = HandlerMaps[I];
8230b57cec5SDimitry Andric       if (!HandlerMapXData)
8240b57cec5SDimitry Andric         continue;
8250b57cec5SDimitry Andric       // HandlerType {
8260b57cec5SDimitry Andric       //   int32_t         Adjectives;
8270b57cec5SDimitry Andric       //   TypeDescriptor *Type;
8280b57cec5SDimitry Andric       //   int32_t         CatchObjOffset;
8290b57cec5SDimitry Andric       //   void          (*Handler)();
8300b57cec5SDimitry Andric       //   int32_t         ParentFrameOffset; // x64 and AArch64 only
8310b57cec5SDimitry Andric       // };
8320b57cec5SDimitry Andric       OS.EmitLabel(HandlerMapXData);
8330b57cec5SDimitry Andric       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
8340b57cec5SDimitry Andric         // Get the frame escape label with the offset of the catch object. If
8350b57cec5SDimitry Andric         // the index is INT_MAX, then there is no catch object, and we should
8360b57cec5SDimitry Andric         // emit an offset of zero, indicating that no copy will occur.
8370b57cec5SDimitry Andric         const MCExpr *FrameAllocOffsetRef = nullptr;
8380b57cec5SDimitry Andric         if (HT.CatchObj.FrameIndex != INT_MAX) {
8390b57cec5SDimitry Andric           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
8400b57cec5SDimitry Andric           assert(Offset != 0 && "Illegal offset for catch object!");
8410b57cec5SDimitry Andric           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
8420b57cec5SDimitry Andric         } else {
8430b57cec5SDimitry Andric           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
8440b57cec5SDimitry Andric         }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric         MCSymbol *HandlerSym =
8470b57cec5SDimitry Andric             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric         AddComment("Adjectives");
8500b57cec5SDimitry Andric         OS.EmitIntValue(HT.Adjectives, 4);
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric         AddComment("Type");
8530b57cec5SDimitry Andric         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric         AddComment("CatchObjOffset");
8560b57cec5SDimitry Andric         OS.EmitValue(FrameAllocOffsetRef, 4);
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric         AddComment("Handler");
8590b57cec5SDimitry Andric         OS.EmitValue(create32bitRef(HandlerSym), 4);
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric         if (shouldEmitPersonality) {
8620b57cec5SDimitry Andric           AddComment("ParentFrameOffset");
8630b57cec5SDimitry Andric           OS.EmitIntValue(ParentFrameOffset, 4);
8640b57cec5SDimitry Andric         }
8650b57cec5SDimitry Andric       }
8660b57cec5SDimitry Andric     }
8670b57cec5SDimitry Andric   }
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   // IPToStateMapEntry {
8700b57cec5SDimitry Andric   //   void   *IP;
8710b57cec5SDimitry Andric   //   int32_t State;
8720b57cec5SDimitry Andric   // };
8730b57cec5SDimitry Andric   if (IPToStateXData) {
8740b57cec5SDimitry Andric     OS.EmitLabel(IPToStateXData);
8750b57cec5SDimitry Andric     for (auto &IPStatePair : IPToStateTable) {
8760b57cec5SDimitry Andric       AddComment("IP");
8770b57cec5SDimitry Andric       OS.EmitValue(IPStatePair.first, 4);
8780b57cec5SDimitry Andric       AddComment("ToState");
8790b57cec5SDimitry Andric       OS.EmitIntValue(IPStatePair.second, 4);
8800b57cec5SDimitry Andric     }
8810b57cec5SDimitry Andric   }
8820b57cec5SDimitry Andric }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric void WinException::computeIP2StateTable(
8850b57cec5SDimitry Andric     const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
8860b57cec5SDimitry Andric     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
8890b57cec5SDimitry Andric                                        FuncletEnd = MF->begin(),
8900b57cec5SDimitry Andric                                        End = MF->end();
8910b57cec5SDimitry Andric        FuncletStart != End; FuncletStart = FuncletEnd) {
8920b57cec5SDimitry Andric     // Find the end of the funclet
8930b57cec5SDimitry Andric     while (++FuncletEnd != End) {
8940b57cec5SDimitry Andric       if (FuncletEnd->isEHFuncletEntry()) {
8950b57cec5SDimitry Andric         break;
8960b57cec5SDimitry Andric       }
8970b57cec5SDimitry Andric     }
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric     // Don't emit ip2state entries for cleanup funclets. Any interesting
9000b57cec5SDimitry Andric     // exceptional actions in cleanups must be handled in a separate IR
9010b57cec5SDimitry Andric     // function.
9020b57cec5SDimitry Andric     if (FuncletStart->isCleanupFuncletEntry())
9030b57cec5SDimitry Andric       continue;
9040b57cec5SDimitry Andric 
9050b57cec5SDimitry Andric     MCSymbol *StartLabel;
9060b57cec5SDimitry Andric     int BaseState;
9070b57cec5SDimitry Andric     if (FuncletStart == MF->begin()) {
9080b57cec5SDimitry Andric       BaseState = NullState;
9090b57cec5SDimitry Andric       StartLabel = Asm->getFunctionBegin();
9100b57cec5SDimitry Andric     } else {
9110b57cec5SDimitry Andric       auto *FuncletPad =
9120b57cec5SDimitry Andric           cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
9130b57cec5SDimitry Andric       assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
9140b57cec5SDimitry Andric       BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
9150b57cec5SDimitry Andric       StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
9160b57cec5SDimitry Andric     }
9170b57cec5SDimitry Andric     assert(StartLabel && "need local function start label");
9180b57cec5SDimitry Andric     IPToStateTable.push_back(
9190b57cec5SDimitry Andric         std::make_pair(create32bitRef(StartLabel), BaseState));
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric     for (const auto &StateChange : InvokeStateChangeIterator::range(
9220b57cec5SDimitry Andric              FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
9230b57cec5SDimitry Andric       // Compute the label to report as the start of this entry; use the EH
9240b57cec5SDimitry Andric       // start label for the invoke if we have one, otherwise (this is a call
9250b57cec5SDimitry Andric       // which may unwind to our caller and does not have an EH start label, so)
9260b57cec5SDimitry Andric       // use the previous end label.
9270b57cec5SDimitry Andric       const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
9280b57cec5SDimitry Andric       if (!ChangeLabel)
9290b57cec5SDimitry Andric         ChangeLabel = StateChange.PreviousEndLabel;
9300b57cec5SDimitry Andric       // Emit an entry indicating that PCs after 'Label' have this EH state.
9310b57cec5SDimitry Andric       IPToStateTable.push_back(
9320b57cec5SDimitry Andric           std::make_pair(getLabel(ChangeLabel), StateChange.NewState));
9330b57cec5SDimitry Andric       // FIXME: assert that NewState is between CatchLow and CatchHigh.
9340b57cec5SDimitry Andric     }
9350b57cec5SDimitry Andric   }
9360b57cec5SDimitry Andric }
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
9390b57cec5SDimitry Andric                                                  StringRef FLinkageName) {
9400b57cec5SDimitry Andric   // Outlined helpers called by the EH runtime need to know the offset of the EH
9410b57cec5SDimitry Andric   // registration in order to recover the parent frame pointer. Now that we know
9420b57cec5SDimitry Andric   // we've code generated the parent, we can emit the label assignment that
9430b57cec5SDimitry Andric   // those helpers use to get the offset of the registration node.
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric   // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
9460b57cec5SDimitry Andric   // after optimization all the invokes were eliminated. We still need to emit
9470b57cec5SDimitry Andric   // the parent frame offset label, but it should be garbage and should never be
9480b57cec5SDimitry Andric   // used.
9490b57cec5SDimitry Andric   int64_t Offset = 0;
9500b57cec5SDimitry Andric   int FI = FuncInfo.EHRegNodeFrameIndex;
9510b57cec5SDimitry Andric   if (FI != INT_MAX) {
9520b57cec5SDimitry Andric     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
9530b57cec5SDimitry Andric     Offset = TFI->getNonLocalFrameIndexReference(*Asm->MF, FI);
9540b57cec5SDimitry Andric   }
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
9570b57cec5SDimitry Andric   MCSymbol *ParentFrameOffset =
9580b57cec5SDimitry Andric       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
9590b57cec5SDimitry Andric   Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
9600b57cec5SDimitry Andric                                    MCConstantExpr::create(Offset, Ctx));
9610b57cec5SDimitry Andric }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric /// Emit the language-specific data that _except_handler3 and 4 expect. This is
9640b57cec5SDimitry Andric /// functionally equivalent to the __C_specific_handler table, except it is
9650b57cec5SDimitry Andric /// indexed by state number instead of IP.
9660b57cec5SDimitry Andric void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
9670b57cec5SDimitry Andric   MCStreamer &OS = *Asm->OutStreamer;
9680b57cec5SDimitry Andric   const Function &F = MF->getFunction();
9690b57cec5SDimitry Andric   StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
9720b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
9730b57cec5SDimitry Andric     if (VerboseAsm)
9740b57cec5SDimitry Andric       OS.AddComment(Comment);
9750b57cec5SDimitry Andric   };
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
9780b57cec5SDimitry Andric   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
9810b57cec5SDimitry Andric   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
9820b57cec5SDimitry Andric   OS.EmitValueToAlignment(4);
9830b57cec5SDimitry Andric   OS.EmitLabel(LSDALabel);
9840b57cec5SDimitry Andric 
985*8bcb0991SDimitry Andric   const auto *Per = cast<Function>(F.getPersonalityFn()->stripPointerCasts());
9860b57cec5SDimitry Andric   StringRef PerName = Per->getName();
9870b57cec5SDimitry Andric   int BaseState = -1;
9880b57cec5SDimitry Andric   if (PerName == "_except_handler4") {
9890b57cec5SDimitry Andric     // The LSDA for _except_handler4 starts with this struct, followed by the
9900b57cec5SDimitry Andric     // scope table:
9910b57cec5SDimitry Andric     //
9920b57cec5SDimitry Andric     // struct EH4ScopeTable {
9930b57cec5SDimitry Andric     //   int32_t GSCookieOffset;
9940b57cec5SDimitry Andric     //   int32_t GSCookieXOROffset;
9950b57cec5SDimitry Andric     //   int32_t EHCookieOffset;
9960b57cec5SDimitry Andric     //   int32_t EHCookieXOROffset;
9970b57cec5SDimitry Andric     //   ScopeTableEntry ScopeRecord[];
9980b57cec5SDimitry Andric     // };
9990b57cec5SDimitry Andric     //
10000b57cec5SDimitry Andric     // Offsets are %ebp relative.
10010b57cec5SDimitry Andric     //
10020b57cec5SDimitry Andric     // The GS cookie is present only if the function needs stack protection.
10030b57cec5SDimitry Andric     // GSCookieOffset = -2 means that GS cookie is not used.
10040b57cec5SDimitry Andric     //
10050b57cec5SDimitry Andric     // The EH cookie is always present.
10060b57cec5SDimitry Andric     //
10070b57cec5SDimitry Andric     // Check is done the following way:
10080b57cec5SDimitry Andric     //    (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric     // Retrieve the Guard Stack slot.
10110b57cec5SDimitry Andric     int GSCookieOffset = -2;
10120b57cec5SDimitry Andric     const MachineFrameInfo &MFI = MF->getFrameInfo();
10130b57cec5SDimitry Andric     if (MFI.hasStackProtectorIndex()) {
10140b57cec5SDimitry Andric       unsigned UnusedReg;
10150b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
10160b57cec5SDimitry Andric       int SSPIdx = MFI.getStackProtectorIndex();
10170b57cec5SDimitry Andric       GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
10180b57cec5SDimitry Andric     }
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric     // Retrieve the EH Guard slot.
10210b57cec5SDimitry Andric     // TODO(etienneb): Get rid of this value and change it for and assertion.
10220b57cec5SDimitry Andric     int EHCookieOffset = 9999;
10230b57cec5SDimitry Andric     if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
10240b57cec5SDimitry Andric       unsigned UnusedReg;
10250b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
10260b57cec5SDimitry Andric       int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
10270b57cec5SDimitry Andric       EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
10280b57cec5SDimitry Andric     }
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric     AddComment("GSCookieOffset");
10310b57cec5SDimitry Andric     OS.EmitIntValue(GSCookieOffset, 4);
10320b57cec5SDimitry Andric     AddComment("GSCookieXOROffset");
10330b57cec5SDimitry Andric     OS.EmitIntValue(0, 4);
10340b57cec5SDimitry Andric     AddComment("EHCookieOffset");
10350b57cec5SDimitry Andric     OS.EmitIntValue(EHCookieOffset, 4);
10360b57cec5SDimitry Andric     AddComment("EHCookieXOROffset");
10370b57cec5SDimitry Andric     OS.EmitIntValue(0, 4);
10380b57cec5SDimitry Andric     BaseState = -2;
10390b57cec5SDimitry Andric   }
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric   assert(!FuncInfo.SEHUnwindMap.empty());
10420b57cec5SDimitry Andric   for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
10430b57cec5SDimitry Andric     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
10440b57cec5SDimitry Andric     const MCSymbol *ExceptOrFinally =
10450b57cec5SDimitry Andric         UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
10460b57cec5SDimitry Andric     // -1 is usually the base state for "unwind to caller", but for
10470b57cec5SDimitry Andric     // _except_handler4 it's -2. Do that replacement here if necessary.
10480b57cec5SDimitry Andric     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
10490b57cec5SDimitry Andric     AddComment("ToState");
10500b57cec5SDimitry Andric     OS.EmitIntValue(ToState, 4);
10510b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "Null" : "FilterFunction");
10520b57cec5SDimitry Andric     OS.EmitValue(create32bitRef(UME.Filter), 4);
10530b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
10540b57cec5SDimitry Andric     OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
10550b57cec5SDimitry Andric   }
10560b57cec5SDimitry Andric }
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
10590b57cec5SDimitry Andric   int Rank = 0;
10600b57cec5SDimitry Andric   while (State != -1) {
10610b57cec5SDimitry Andric     ++Rank;
10620b57cec5SDimitry Andric     State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
10630b57cec5SDimitry Andric   }
10640b57cec5SDimitry Andric   return Rank;
10650b57cec5SDimitry Andric }
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
10680b57cec5SDimitry Andric   int LeftRank = getTryRank(FuncInfo, Left);
10690b57cec5SDimitry Andric   int RightRank = getTryRank(FuncInfo, Right);
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric   while (LeftRank < RightRank) {
10720b57cec5SDimitry Andric     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
10730b57cec5SDimitry Andric     --RightRank;
10740b57cec5SDimitry Andric   }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   while (RightRank < LeftRank) {
10770b57cec5SDimitry Andric     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
10780b57cec5SDimitry Andric     --LeftRank;
10790b57cec5SDimitry Andric   }
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   while (Left != Right) {
10820b57cec5SDimitry Andric     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
10830b57cec5SDimitry Andric     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   return Left;
10870b57cec5SDimitry Andric }
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
10900b57cec5SDimitry Andric   // CLR EH "states" are really just IDs that identify handlers/funclets;
10910b57cec5SDimitry Andric   // states, handlers, and funclets all have 1:1 mappings between them, and a
10920b57cec5SDimitry Andric   // handler/funclet's "state" is its index in the ClrEHUnwindMap.
10930b57cec5SDimitry Andric   MCStreamer &OS = *Asm->OutStreamer;
10940b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
10950b57cec5SDimitry Andric   MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
10960b57cec5SDimitry Andric   MCSymbol *FuncEndSym = Asm->getFunctionEnd();
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric   // A ClrClause describes a protected region.
10990b57cec5SDimitry Andric   struct ClrClause {
11000b57cec5SDimitry Andric     const MCSymbol *StartLabel; // Start of protected region
11010b57cec5SDimitry Andric     const MCSymbol *EndLabel;   // End of protected region
11020b57cec5SDimitry Andric     int State;          // Index of handler protecting the protected region
11030b57cec5SDimitry Andric     int EnclosingState; // Index of funclet enclosing the protected region
11040b57cec5SDimitry Andric   };
11050b57cec5SDimitry Andric   SmallVector<ClrClause, 8> Clauses;
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric   // Build a map from handler MBBs to their corresponding states (i.e. their
11080b57cec5SDimitry Andric   // indices in the ClrEHUnwindMap).
11090b57cec5SDimitry Andric   int NumStates = FuncInfo.ClrEHUnwindMap.size();
11100b57cec5SDimitry Andric   assert(NumStates > 0 && "Don't need exception table!");
11110b57cec5SDimitry Andric   DenseMap<const MachineBasicBlock *, int> HandlerStates;
11120b57cec5SDimitry Andric   for (int State = 0; State < NumStates; ++State) {
11130b57cec5SDimitry Andric     MachineBasicBlock *HandlerBlock =
11140b57cec5SDimitry Andric         FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
11150b57cec5SDimitry Andric     HandlerStates[HandlerBlock] = State;
11160b57cec5SDimitry Andric     // Use this loop through all handlers to verify our assumption (used in
11170b57cec5SDimitry Andric     // the MinEnclosingState computation) that enclosing funclets have lower
11180b57cec5SDimitry Andric     // state numbers than their enclosed funclets.
11190b57cec5SDimitry Andric     assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
11200b57cec5SDimitry Andric            "ill-formed state numbering");
11210b57cec5SDimitry Andric   }
11220b57cec5SDimitry Andric   // Map the main function to the NullState.
11230b57cec5SDimitry Andric   HandlerStates[&MF->front()] = NullState;
11240b57cec5SDimitry Andric 
11250b57cec5SDimitry Andric   // Write out a sentinel indicating the end of the standard (Windows) xdata
11260b57cec5SDimitry Andric   // and the start of the additional (CLR) info.
11270b57cec5SDimitry Andric   OS.EmitIntValue(0xffffffff, 4);
11280b57cec5SDimitry Andric   // Write out the number of funclets
11290b57cec5SDimitry Andric   OS.EmitIntValue(NumStates, 4);
11300b57cec5SDimitry Andric 
11310b57cec5SDimitry Andric   // Walk the machine blocks/instrs, computing and emitting a few things:
11320b57cec5SDimitry Andric   // 1. Emit a list of the offsets to each handler entry, in lexical order.
11330b57cec5SDimitry Andric   // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
11340b57cec5SDimitry Andric   // 3. Compute the list of ClrClauses, in the required order (inner before
11350b57cec5SDimitry Andric   //    outer, earlier before later; the order by which a forward scan with
11360b57cec5SDimitry Andric   //    early termination will find the innermost enclosing clause covering
11370b57cec5SDimitry Andric   //    a given address).
11380b57cec5SDimitry Andric   // 4. A map (MinClauseMap) from each handler index to the index of the
11390b57cec5SDimitry Andric   //    outermost funclet/function which contains a try clause targeting the
11400b57cec5SDimitry Andric   //    key handler.  This will be used to determine IsDuplicate-ness when
11410b57cec5SDimitry Andric   //    emitting ClrClauses.  The NullState value is used to indicate that the
11420b57cec5SDimitry Andric   //    top-level function contains a try clause targeting the key handler.
11430b57cec5SDimitry Andric   // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
11440b57cec5SDimitry Andric   // try regions we entered before entering the PendingState try but which
11450b57cec5SDimitry Andric   // we haven't yet exited.
11460b57cec5SDimitry Andric   SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
11470b57cec5SDimitry Andric   // EndSymbolMap and MinClauseMap are maps described above.
11480b57cec5SDimitry Andric   std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
11490b57cec5SDimitry Andric   SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric   // Visit the root function and each funclet.
11520b57cec5SDimitry Andric   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
11530b57cec5SDimitry Andric                                        FuncletEnd = MF->begin(),
11540b57cec5SDimitry Andric                                        End = MF->end();
11550b57cec5SDimitry Andric        FuncletStart != End; FuncletStart = FuncletEnd) {
11560b57cec5SDimitry Andric     int FuncletState = HandlerStates[&*FuncletStart];
11570b57cec5SDimitry Andric     // Find the end of the funclet
11580b57cec5SDimitry Andric     MCSymbol *EndSymbol = FuncEndSym;
11590b57cec5SDimitry Andric     while (++FuncletEnd != End) {
11600b57cec5SDimitry Andric       if (FuncletEnd->isEHFuncletEntry()) {
11610b57cec5SDimitry Andric         EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
11620b57cec5SDimitry Andric         break;
11630b57cec5SDimitry Andric       }
11640b57cec5SDimitry Andric     }
11650b57cec5SDimitry Andric     // Emit the function/funclet end and, if this is a funclet (and not the
11660b57cec5SDimitry Andric     // root function), record it in the EndSymbolMap.
11670b57cec5SDimitry Andric     OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
11680b57cec5SDimitry Andric     if (FuncletState != NullState) {
11690b57cec5SDimitry Andric       // Record the end of the handler.
11700b57cec5SDimitry Andric       EndSymbolMap[FuncletState] = EndSymbol;
11710b57cec5SDimitry Andric     }
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric     // Walk the state changes in this function/funclet and compute its clauses.
11740b57cec5SDimitry Andric     // Funclets always start in the null state.
11750b57cec5SDimitry Andric     const MCSymbol *CurrentStartLabel = nullptr;
11760b57cec5SDimitry Andric     int CurrentState = NullState;
11770b57cec5SDimitry Andric     assert(HandlerStack.empty());
11780b57cec5SDimitry Andric     for (const auto &StateChange :
11790b57cec5SDimitry Andric          InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
11800b57cec5SDimitry Andric       // Close any try regions we're not still under
11810b57cec5SDimitry Andric       int StillPendingState =
11820b57cec5SDimitry Andric           getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
11830b57cec5SDimitry Andric       while (CurrentState != StillPendingState) {
11840b57cec5SDimitry Andric         assert(CurrentState != NullState &&
11850b57cec5SDimitry Andric                "Failed to find still-pending state!");
11860b57cec5SDimitry Andric         // Close the pending clause
11870b57cec5SDimitry Andric         Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
11880b57cec5SDimitry Andric                            CurrentState, FuncletState});
11890b57cec5SDimitry Andric         // Now the next-outer try region is current
11900b57cec5SDimitry Andric         CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
11910b57cec5SDimitry Andric         // Pop the new start label from the handler stack if we've exited all
11920b57cec5SDimitry Andric         // inner try regions of the corresponding try region.
11930b57cec5SDimitry Andric         if (HandlerStack.back().second == CurrentState)
11940b57cec5SDimitry Andric           CurrentStartLabel = HandlerStack.pop_back_val().first;
11950b57cec5SDimitry Andric       }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric       if (StateChange.NewState != CurrentState) {
11980b57cec5SDimitry Andric         // For each clause we're starting, update the MinClauseMap so we can
11990b57cec5SDimitry Andric         // know which is the topmost funclet containing a clause targeting
12000b57cec5SDimitry Andric         // it.
12010b57cec5SDimitry Andric         for (int EnteredState = StateChange.NewState;
12020b57cec5SDimitry Andric              EnteredState != CurrentState;
12030b57cec5SDimitry Andric              EnteredState =
12040b57cec5SDimitry Andric                  FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
12050b57cec5SDimitry Andric           int &MinEnclosingState = MinClauseMap[EnteredState];
12060b57cec5SDimitry Andric           if (FuncletState < MinEnclosingState)
12070b57cec5SDimitry Andric             MinEnclosingState = FuncletState;
12080b57cec5SDimitry Andric         }
12090b57cec5SDimitry Andric         // Save the previous current start/label on the stack and update to
12100b57cec5SDimitry Andric         // the newly-current start/state.
12110b57cec5SDimitry Andric         HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
12120b57cec5SDimitry Andric         CurrentStartLabel = StateChange.NewStartLabel;
12130b57cec5SDimitry Andric         CurrentState = StateChange.NewState;
12140b57cec5SDimitry Andric       }
12150b57cec5SDimitry Andric     }
12160b57cec5SDimitry Andric     assert(HandlerStack.empty());
12170b57cec5SDimitry Andric   }
12180b57cec5SDimitry Andric 
12190b57cec5SDimitry Andric   // Now emit the clause info, starting with the number of clauses.
12200b57cec5SDimitry Andric   OS.EmitIntValue(Clauses.size(), 4);
12210b57cec5SDimitry Andric   for (ClrClause &Clause : Clauses) {
12220b57cec5SDimitry Andric     // Emit a CORINFO_EH_CLAUSE :
12230b57cec5SDimitry Andric     /*
12240b57cec5SDimitry Andric       struct CORINFO_EH_CLAUSE
12250b57cec5SDimitry Andric       {
12260b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FLAGS Flags;         // actually a CorExceptionFlag
12270b57cec5SDimitry Andric           DWORD                   TryOffset;
12280b57cec5SDimitry Andric           DWORD                   TryLength;     // actually TryEndOffset
12290b57cec5SDimitry Andric           DWORD                   HandlerOffset;
12300b57cec5SDimitry Andric           DWORD                   HandlerLength; // actually HandlerEndOffset
12310b57cec5SDimitry Andric           union
12320b57cec5SDimitry Andric           {
12330b57cec5SDimitry Andric               DWORD               ClassToken;   // use for catch clauses
12340b57cec5SDimitry Andric               DWORD               FilterOffset; // use for filter clauses
12350b57cec5SDimitry Andric           };
12360b57cec5SDimitry Andric       };
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric       enum CORINFO_EH_CLAUSE_FLAGS
12390b57cec5SDimitry Andric       {
12400b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_NONE    = 0,
12410b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FILTER  = 0x0001, // This clause is for a filter
12420b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
12430b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FAULT   = 0x0004, // This clause is a fault clause
12440b57cec5SDimitry Andric       };
12450b57cec5SDimitry Andric       typedef enum CorExceptionFlag
12460b57cec5SDimitry Andric       {
12470b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_NONE,
12480b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FILTER  = 0x0001, // This is a filter clause
12490b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
12500b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004,   // This is a fault clause
12510b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
12520b57cec5SDimitry Andric                                                       // clause was duplicated
12530b57cec5SDimitry Andric                                                       // to a funclet which was
12540b57cec5SDimitry Andric                                                       // pulled out of line
12550b57cec5SDimitry Andric       } CorExceptionFlag;
12560b57cec5SDimitry Andric     */
12570b57cec5SDimitry Andric     // Add 1 to the start/end of the EH clause; the IP associated with a
12580b57cec5SDimitry Andric     // call when the runtime does its scan is the IP of the next instruction
12590b57cec5SDimitry Andric     // (the one to which control will return after the call), so we need
12600b57cec5SDimitry Andric     // to add 1 to the end of the clause to cover that offset.  We also add
12610b57cec5SDimitry Andric     // 1 to the start of the clause to make sure that the ranges reported
12620b57cec5SDimitry Andric     // for all clauses are disjoint.  Note that we'll need some additional
12630b57cec5SDimitry Andric     // logic when machine traps are supported, since in that case the IP
12640b57cec5SDimitry Andric     // that the runtime uses is the offset of the faulting instruction
12650b57cec5SDimitry Andric     // itself; if such an instruction immediately follows a call but the
12660b57cec5SDimitry Andric     // two belong to different clauses, we'll need to insert a nop between
12670b57cec5SDimitry Andric     // them so the runtime can distinguish the point to which the call will
12680b57cec5SDimitry Andric     // return from the point at which the fault occurs.
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric     const MCExpr *ClauseBegin =
12710b57cec5SDimitry Andric         getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
12720b57cec5SDimitry Andric     const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric     const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
12750b57cec5SDimitry Andric     MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
12760b57cec5SDimitry Andric     MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
12770b57cec5SDimitry Andric     const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
12780b57cec5SDimitry Andric     MCSymbol *EndSym = EndSymbolMap[Clause.State];
12790b57cec5SDimitry Andric     const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric     uint32_t Flags = 0;
12820b57cec5SDimitry Andric     switch (Entry.HandlerType) {
12830b57cec5SDimitry Andric     case ClrHandlerType::Catch:
12840b57cec5SDimitry Andric       // Leaving bits 0-2 clear indicates catch.
12850b57cec5SDimitry Andric       break;
12860b57cec5SDimitry Andric     case ClrHandlerType::Filter:
12870b57cec5SDimitry Andric       Flags |= 1;
12880b57cec5SDimitry Andric       break;
12890b57cec5SDimitry Andric     case ClrHandlerType::Finally:
12900b57cec5SDimitry Andric       Flags |= 2;
12910b57cec5SDimitry Andric       break;
12920b57cec5SDimitry Andric     case ClrHandlerType::Fault:
12930b57cec5SDimitry Andric       Flags |= 4;
12940b57cec5SDimitry Andric       break;
12950b57cec5SDimitry Andric     }
12960b57cec5SDimitry Andric     if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
12970b57cec5SDimitry Andric       // This is a "duplicate" clause; the handler needs to be entered from a
12980b57cec5SDimitry Andric       // frame above the one holding the invoke.
12990b57cec5SDimitry Andric       assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
13000b57cec5SDimitry Andric       Flags |= 8;
13010b57cec5SDimitry Andric     }
13020b57cec5SDimitry Andric     OS.EmitIntValue(Flags, 4);
13030b57cec5SDimitry Andric 
13040b57cec5SDimitry Andric     // Write the clause start/end
13050b57cec5SDimitry Andric     OS.EmitValue(ClauseBegin, 4);
13060b57cec5SDimitry Andric     OS.EmitValue(ClauseEnd, 4);
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric     // Write out the handler start/end
13090b57cec5SDimitry Andric     OS.EmitValue(HandlerBegin, 4);
13100b57cec5SDimitry Andric     OS.EmitValue(HandlerEnd, 4);
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric     // Write out the type token or filter offset
13130b57cec5SDimitry Andric     assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
13140b57cec5SDimitry Andric     OS.EmitIntValue(Entry.TypeToken, 4);
13150b57cec5SDimitry Andric   }
13160b57cec5SDimitry Andric }
1317