197bc6c73SDimitry Andric //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
297bc6c73SDimitry Andric //
397bc6c73SDimitry Andric //                     The LLVM Compiler Infrastructure
497bc6c73SDimitry Andric //
597bc6c73SDimitry Andric // This file is distributed under the University of Illinois Open Source
697bc6c73SDimitry Andric // License. See LICENSE.TXT for details.
797bc6c73SDimitry Andric //
897bc6c73SDimitry Andric //===----------------------------------------------------------------------===//
997bc6c73SDimitry Andric //
1097bc6c73SDimitry Andric // This file contains support for writing Win64 exception info into asm files.
1197bc6c73SDimitry Andric //
1297bc6c73SDimitry Andric //===----------------------------------------------------------------------===//
1397bc6c73SDimitry Andric 
1497bc6c73SDimitry Andric #include "WinException.h"
1597bc6c73SDimitry Andric #include "llvm/ADT/Twine.h"
16db17bf38SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
17db17bf38SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
1897bc6c73SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
1997bc6c73SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
2097bc6c73SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
2197bc6c73SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
222cab237bSDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
232cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
242cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
2597bc6c73SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
2697bc6c73SDimitry Andric #include "llvm/IR/DataLayout.h"
2797bc6c73SDimitry Andric #include "llvm/IR/Mangler.h"
2897bc6c73SDimitry Andric #include "llvm/IR/Module.h"
2997bc6c73SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
3097bc6c73SDimitry Andric #include "llvm/MC/MCContext.h"
3197bc6c73SDimitry Andric #include "llvm/MC/MCExpr.h"
3297bc6c73SDimitry Andric #include "llvm/MC/MCSection.h"
3397bc6c73SDimitry Andric #include "llvm/MC/MCStreamer.h"
3497bc6c73SDimitry Andric #include "llvm/MC/MCSymbol.h"
3597bc6c73SDimitry Andric #include "llvm/Support/ErrorHandling.h"
3697bc6c73SDimitry Andric #include "llvm/Support/FormattedStream.h"
374ba319b5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
3897bc6c73SDimitry Andric #include "llvm/Target/TargetOptions.h"
3997bc6c73SDimitry Andric using namespace llvm;
4097bc6c73SDimitry Andric 
WinException(AsmPrinter * A)4197bc6c73SDimitry Andric WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
4297bc6c73SDimitry Andric   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
4397bc6c73SDimitry Andric   // platforms use an imagerel32 relocation to refer to symbols.
4497bc6c73SDimitry Andric   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
45*b5893f02SDimitry Andric   isAArch64 = Asm->TM.getTargetTriple().isAArch64();
4697bc6c73SDimitry Andric }
4797bc6c73SDimitry Andric 
~WinException()4897bc6c73SDimitry Andric WinException::~WinException() {}
4997bc6c73SDimitry Andric 
5097bc6c73SDimitry Andric /// endModule - Emit all exception information that should come after the
5197bc6c73SDimitry Andric /// content.
endModule()5297bc6c73SDimitry Andric void WinException::endModule() {
538f0fd8f6SDimitry Andric   auto &OS = *Asm->OutStreamer;
548f0fd8f6SDimitry Andric   const Module *M = MMI->getModule();
558f0fd8f6SDimitry Andric   for (const Function &F : *M)
568f0fd8f6SDimitry Andric     if (F.hasFnAttribute("safeseh"))
578f0fd8f6SDimitry Andric       OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
5897bc6c73SDimitry Andric }
5997bc6c73SDimitry Andric 
beginFunction(const MachineFunction * MF)6097bc6c73SDimitry Andric void WinException::beginFunction(const MachineFunction *MF) {
6197bc6c73SDimitry Andric   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
6297bc6c73SDimitry Andric 
6397bc6c73SDimitry Andric   // If any landing pads survive, we need an EH table.
64d88c1a5aSDimitry Andric   bool hasLandingPads = !MF->getLandingPads().empty();
65d88c1a5aSDimitry Andric   bool hasEHFunclets = MF->hasEHFunclets();
6697bc6c73SDimitry Andric 
672cab237bSDimitry Andric   const Function &F = MF->getFunction();
6897bc6c73SDimitry Andric 
697a7e6055SDimitry Andric   shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
7097bc6c73SDimitry Andric 
7197bc6c73SDimitry Andric   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
7297bc6c73SDimitry Andric   unsigned PerEncoding = TLOF.getPersonalityEncoding();
7397bc6c73SDimitry Andric 
74d88c1a5aSDimitry Andric   EHPersonality Per = EHPersonality::Unknown;
75d88c1a5aSDimitry Andric   const Function *PerFn = nullptr;
762cab237bSDimitry Andric   if (F.hasPersonalityFn()) {
772cab237bSDimitry Andric     PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
78d88c1a5aSDimitry Andric     Per = classifyEHPersonality(PerFn);
79d88c1a5aSDimitry Andric   }
80d88c1a5aSDimitry Andric 
812cab237bSDimitry Andric   bool forceEmitPersonality = F.hasPersonalityFn() &&
82d88c1a5aSDimitry Andric                               !isNoOpWithoutInvoke(Per) &&
832cab237bSDimitry Andric                               F.needsUnwindTableEntry();
84875ed548SDimitry Andric 
857d523365SDimitry Andric   shouldEmitPersonality =
867d523365SDimitry Andric       forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
87d88c1a5aSDimitry Andric                                PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
8897bc6c73SDimitry Andric 
8997bc6c73SDimitry Andric   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
9097bc6c73SDimitry Andric   shouldEmitLSDA = shouldEmitPersonality &&
9197bc6c73SDimitry Andric     LSDAEncoding != dwarf::DW_EH_PE_omit;
9297bc6c73SDimitry Andric 
937d523365SDimitry Andric   // If we're not using CFI, we don't want the CFI or the personality, but we
947d523365SDimitry Andric   // might want EH tables if we had EH pads.
957a7e6055SDimitry Andric   if (!Asm->MAI->usesWindowsCFI()) {
96d88c1a5aSDimitry Andric     if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
97d88c1a5aSDimitry Andric       // If this is 32-bit SEH and we don't have any funclets (really invokes),
98d88c1a5aSDimitry Andric       // make sure we emit the parent offset label. Some unreferenced filter
99d88c1a5aSDimitry Andric       // functions may still refer to it.
100d88c1a5aSDimitry Andric       const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
101d88c1a5aSDimitry Andric       StringRef FLinkageName =
1022cab237bSDimitry Andric           GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
103d88c1a5aSDimitry Andric       emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
104d88c1a5aSDimitry Andric     }
1057d523365SDimitry Andric     shouldEmitLSDA = hasEHFunclets;
10697bc6c73SDimitry Andric     shouldEmitPersonality = false;
10797bc6c73SDimitry Andric     return;
10897bc6c73SDimitry Andric   }
10997bc6c73SDimitry Andric 
1107d523365SDimitry Andric   beginFunclet(MF->front(), Asm->CurrentFnSym);
11197bc6c73SDimitry Andric }
11297bc6c73SDimitry Andric 
11397bc6c73SDimitry Andric /// endFunction - Gather and emit post-function exception information.
11497bc6c73SDimitry Andric ///
endFunction(const MachineFunction * MF)11597bc6c73SDimitry Andric void WinException::endFunction(const MachineFunction *MF) {
11697bc6c73SDimitry Andric   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
11797bc6c73SDimitry Andric     return;
11897bc6c73SDimitry Andric 
1192cab237bSDimitry Andric   const Function &F = MF->getFunction();
120875ed548SDimitry Andric   EHPersonality Per = EHPersonality::Unknown;
1212cab237bSDimitry Andric   if (F.hasPersonalityFn())
1222cab237bSDimitry Andric     Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
12397bc6c73SDimitry Andric 
1247d523365SDimitry Andric   // Get rid of any dead landing pads if we're not using funclets. In funclet
1257d523365SDimitry Andric   // schemes, the landing pad is not actually reachable. It only exists so
1267d523365SDimitry Andric   // that we can emit the right table data.
127d88c1a5aSDimitry Andric   if (!isFuncletEHPersonality(Per)) {
128d88c1a5aSDimitry Andric     MachineFunction *NonConstMF = const_cast<MachineFunction*>(MF);
129d88c1a5aSDimitry Andric     NonConstMF->tidyLandingPads();
130d88c1a5aSDimitry Andric   }
13197bc6c73SDimitry Andric 
1327d523365SDimitry Andric   endFunclet();
1337d523365SDimitry Andric 
1347d523365SDimitry Andric   // endFunclet will emit the necessary .xdata tables for x64 SEH.
135d88c1a5aSDimitry Andric   if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets())
1367d523365SDimitry Andric     return;
1377d523365SDimitry Andric 
13897bc6c73SDimitry Andric   if (shouldEmitPersonality || shouldEmitLSDA) {
13997bc6c73SDimitry Andric     Asm->OutStreamer->PushSection();
14097bc6c73SDimitry Andric 
1413ca95b02SDimitry Andric     // Just switch sections to the right xdata section.
1423ca95b02SDimitry Andric     MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
1433ca95b02SDimitry Andric         Asm->OutStreamer->getCurrentSectionOnly());
14497bc6c73SDimitry Andric     Asm->OutStreamer->SwitchSection(XData);
14597bc6c73SDimitry Andric 
14697bc6c73SDimitry Andric     // Emit the tables appropriate to the personality function in use. If we
14797bc6c73SDimitry Andric     // don't recognize the personality, assume it uses an Itanium-style LSDA.
14897bc6c73SDimitry Andric     if (Per == EHPersonality::MSVC_Win64SEH)
1497d523365SDimitry Andric       emitCSpecificHandlerTable(MF);
15097bc6c73SDimitry Andric     else if (Per == EHPersonality::MSVC_X86SEH)
1518f0fd8f6SDimitry Andric       emitExceptHandlerTable(MF);
15297bc6c73SDimitry Andric     else if (Per == EHPersonality::MSVC_CXX)
15397bc6c73SDimitry Andric       emitCXXFrameHandler3Table(MF);
1547d523365SDimitry Andric     else if (Per == EHPersonality::CoreCLR)
1557d523365SDimitry Andric       emitCLRExceptionTable(MF);
15697bc6c73SDimitry Andric     else
15797bc6c73SDimitry Andric       emitExceptionTable();
15897bc6c73SDimitry Andric 
15997bc6c73SDimitry Andric     Asm->OutStreamer->PopSection();
16097bc6c73SDimitry Andric   }
1617d523365SDimitry Andric }
16297bc6c73SDimitry Andric 
163d88c1a5aSDimitry Andric /// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
getMCSymbolForMBB(AsmPrinter * Asm,const MachineBasicBlock * MBB)1647d523365SDimitry Andric static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
1657d523365SDimitry Andric                                    const MachineBasicBlock *MBB) {
1667d523365SDimitry Andric   if (!MBB)
1677d523365SDimitry Andric     return nullptr;
1687d523365SDimitry Andric 
1697d523365SDimitry Andric   assert(MBB->isEHFuncletEntry());
1707d523365SDimitry Andric 
1717d523365SDimitry Andric   // Give catches and cleanups a name based off of their parent function and
1727d523365SDimitry Andric   // their funclet entry block's number.
1737d523365SDimitry Andric   const MachineFunction *MF = MBB->getParent();
1742cab237bSDimitry Andric   const Function &F = MF->getFunction();
1752cab237bSDimitry Andric   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
1767d523365SDimitry Andric   MCContext &Ctx = MF->getContext();
1777d523365SDimitry Andric   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
1787d523365SDimitry Andric   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
1797d523365SDimitry Andric                                Twine(MBB->getNumber()) + "@?0?" +
1807d523365SDimitry Andric                                FuncLinkageName + "@4HA");
1817d523365SDimitry Andric }
1827d523365SDimitry Andric 
beginFunclet(const MachineBasicBlock & MBB,MCSymbol * Sym)1837d523365SDimitry Andric void WinException::beginFunclet(const MachineBasicBlock &MBB,
1847d523365SDimitry Andric                                 MCSymbol *Sym) {
1857d523365SDimitry Andric   CurrentFuncletEntry = &MBB;
1867d523365SDimitry Andric 
1872cab237bSDimitry Andric   const Function &F = Asm->MF->getFunction();
1887d523365SDimitry Andric   // If a symbol was not provided for the funclet, invent one.
1897d523365SDimitry Andric   if (!Sym) {
1907d523365SDimitry Andric     Sym = getMCSymbolForMBB(Asm, &MBB);
1917d523365SDimitry Andric 
1927d523365SDimitry Andric     // Describe our funclet symbol as a function with internal linkage.
1937d523365SDimitry Andric     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
1947d523365SDimitry Andric     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
1957d523365SDimitry Andric     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
1967d523365SDimitry Andric                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
1977d523365SDimitry Andric     Asm->OutStreamer->EndCOFFSymbolDef();
1987d523365SDimitry Andric 
1997d523365SDimitry Andric     // We want our funclet's entry point to be aligned such that no nops will be
2007d523365SDimitry Andric     // present after the label.
2017d523365SDimitry Andric     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
2022cab237bSDimitry Andric                        &F);
2037d523365SDimitry Andric 
2047d523365SDimitry Andric     // Now that we've emitted the alignment directive, point at our funclet.
2057d523365SDimitry Andric     Asm->OutStreamer->EmitLabel(Sym);
2067d523365SDimitry Andric   }
2077d523365SDimitry Andric 
2087d523365SDimitry Andric   // Mark 'Sym' as starting our funclet.
209d88c1a5aSDimitry Andric   if (shouldEmitMoves || shouldEmitPersonality) {
210d88c1a5aSDimitry Andric     CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
2117d523365SDimitry Andric     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
212d88c1a5aSDimitry Andric   }
2137d523365SDimitry Andric 
2147d523365SDimitry Andric   if (shouldEmitPersonality) {
2157d523365SDimitry Andric     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2167d523365SDimitry Andric     const Function *PerFn = nullptr;
2177d523365SDimitry Andric 
2187d523365SDimitry Andric     // Determine which personality routine we are using for this funclet.
2192cab237bSDimitry Andric     if (F.hasPersonalityFn())
2202cab237bSDimitry Andric       PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2217d523365SDimitry Andric     const MCSymbol *PersHandlerSym =
222d88c1a5aSDimitry Andric         TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
2237d523365SDimitry Andric 
224d88c1a5aSDimitry Andric     // Do not emit a .seh_handler directives for cleanup funclets.
225d88c1a5aSDimitry Andric     // FIXME: This means cleanup funclets cannot handle exceptions. Given that
226d88c1a5aSDimitry Andric     // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
227d88c1a5aSDimitry Andric     // inliner doesn't allow inlining them, this isn't a major problem in
228d88c1a5aSDimitry Andric     // practice.
229d88c1a5aSDimitry Andric     if (!CurrentFuncletEntry->isCleanupFuncletEntry())
2307d523365SDimitry Andric       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
2317d523365SDimitry Andric   }
2327d523365SDimitry Andric }
2337d523365SDimitry Andric 
endFunclet()2347d523365SDimitry Andric void WinException::endFunclet() {
2357d523365SDimitry Andric   // No funclet to process?  Great, we have nothing to do.
2367d523365SDimitry Andric   if (!CurrentFuncletEntry)
2377d523365SDimitry Andric     return;
2387d523365SDimitry Andric 
239d88c1a5aSDimitry Andric   const MachineFunction *MF = Asm->MF;
2407d523365SDimitry Andric   if (shouldEmitMoves || shouldEmitPersonality) {
2412cab237bSDimitry Andric     const Function &F = MF->getFunction();
2427d523365SDimitry Andric     EHPersonality Per = EHPersonality::Unknown;
2432cab237bSDimitry Andric     if (F.hasPersonalityFn())
2442cab237bSDimitry Andric       Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
2457d523365SDimitry Andric 
246*b5893f02SDimitry Andric     // On funclet exit, we emit a fake "function" end marker, so that the call
247*b5893f02SDimitry Andric     // to EmitWinEHHandlerData below can calculate the size of the funclet or
248*b5893f02SDimitry Andric     // function.
249*b5893f02SDimitry Andric     if (isAArch64) {
250*b5893f02SDimitry Andric       Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
251*b5893f02SDimitry Andric       Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
252*b5893f02SDimitry Andric       MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
253*b5893f02SDimitry Andric           Asm->OutStreamer->getCurrentSectionOnly());
254*b5893f02SDimitry Andric       Asm->OutStreamer->SwitchSection(XData);
255*b5893f02SDimitry Andric     }
256*b5893f02SDimitry Andric 
2577d523365SDimitry Andric     // Emit an UNWIND_INFO struct describing the prologue.
2587d523365SDimitry Andric     Asm->OutStreamer->EmitWinEHHandlerData();
2597d523365SDimitry Andric 
2607d523365SDimitry Andric     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
2617d523365SDimitry Andric         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
2627d523365SDimitry Andric       // If this is a C++ catch funclet (or the parent function),
2637d523365SDimitry Andric       // emit a reference to the LSDA for the parent function.
2642cab237bSDimitry Andric       StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
2657d523365SDimitry Andric       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
2667d523365SDimitry Andric           Twine("$cppxdata$", FuncLinkageName));
2677d523365SDimitry Andric       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
268d88c1a5aSDimitry Andric     } else if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets() &&
2697d523365SDimitry Andric                !CurrentFuncletEntry->isEHFuncletEntry()) {
2707d523365SDimitry Andric       // If this is the parent function in Win64 SEH, emit the LSDA immediately
2717d523365SDimitry Andric       // following .seh_handlerdata.
272d88c1a5aSDimitry Andric       emitCSpecificHandlerTable(MF);
2737d523365SDimitry Andric     }
2747d523365SDimitry Andric 
275d88c1a5aSDimitry Andric     // Switch back to the funclet start .text section now that we are done
276d88c1a5aSDimitry Andric     // writing to .xdata, and emit an .seh_endproc directive to mark the end of
277d88c1a5aSDimitry Andric     // the function.
278d88c1a5aSDimitry Andric     Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
27997bc6c73SDimitry Andric     Asm->OutStreamer->EmitWinCFIEndProc();
28097bc6c73SDimitry Andric   }
28197bc6c73SDimitry Andric 
2827d523365SDimitry Andric   // Let's make sure we don't try to end the same funclet twice.
2837d523365SDimitry Andric   CurrentFuncletEntry = nullptr;
2847d523365SDimitry Andric }
2857d523365SDimitry Andric 
create32bitRef(const MCSymbol * Value)28697bc6c73SDimitry Andric const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
28797bc6c73SDimitry Andric   if (!Value)
28897bc6c73SDimitry Andric     return MCConstantExpr::create(0, Asm->OutContext);
28997bc6c73SDimitry Andric   return MCSymbolRefExpr::create(Value, useImageRel32
29097bc6c73SDimitry Andric                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
29197bc6c73SDimitry Andric                                             : MCSymbolRefExpr::VK_None,
29297bc6c73SDimitry Andric                                  Asm->OutContext);
29397bc6c73SDimitry Andric }
29497bc6c73SDimitry Andric 
create32bitRef(const GlobalValue * GV)29597bc6c73SDimitry Andric const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
29697bc6c73SDimitry Andric   if (!GV)
29797bc6c73SDimitry Andric     return MCConstantExpr::create(0, Asm->OutContext);
29897bc6c73SDimitry Andric   return create32bitRef(Asm->getSymbol(GV));
29997bc6c73SDimitry Andric }
30097bc6c73SDimitry Andric 
getLabel(const MCSymbol * Label)301*b5893f02SDimitry Andric const MCExpr *WinException::getLabel(const MCSymbol *Label) {
302*b5893f02SDimitry Andric   if (isAArch64)
303*b5893f02SDimitry Andric     return MCSymbolRefExpr::create(Label, MCSymbolRefExpr::VK_COFF_IMGREL32,
304*b5893f02SDimitry Andric                                    Asm->OutContext);
3057d523365SDimitry Andric   return MCBinaryExpr::createAdd(create32bitRef(Label),
3067d523365SDimitry Andric                                  MCConstantExpr::create(1, Asm->OutContext),
3077d523365SDimitry Andric                                  Asm->OutContext);
3087d523365SDimitry Andric }
3097d523365SDimitry Andric 
getOffset(const MCSymbol * OffsetOf,const MCSymbol * OffsetFrom)3107d523365SDimitry Andric const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
3117d523365SDimitry Andric                                       const MCSymbol *OffsetFrom) {
3127d523365SDimitry Andric   return MCBinaryExpr::createSub(
3137d523365SDimitry Andric       MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
3147d523365SDimitry Andric       MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
3157d523365SDimitry Andric }
3167d523365SDimitry Andric 
getOffsetPlusOne(const MCSymbol * OffsetOf,const MCSymbol * OffsetFrom)3177d523365SDimitry Andric const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
3187d523365SDimitry Andric                                              const MCSymbol *OffsetFrom) {
3197d523365SDimitry Andric   return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
3207d523365SDimitry Andric                                  MCConstantExpr::create(1, Asm->OutContext),
3217d523365SDimitry Andric                                  Asm->OutContext);
3227d523365SDimitry Andric }
3237d523365SDimitry Andric 
getFrameIndexOffset(int FrameIndex,const WinEHFuncInfo & FuncInfo)3247d523365SDimitry Andric int WinException::getFrameIndexOffset(int FrameIndex,
3257d523365SDimitry Andric                                       const WinEHFuncInfo &FuncInfo) {
3267d523365SDimitry Andric   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
3277d523365SDimitry Andric   unsigned UnusedReg;
3283ca95b02SDimitry Andric   if (Asm->MAI->usesWindowsCFI()) {
3293ca95b02SDimitry Andric     int Offset =
3303ca95b02SDimitry Andric         TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
3313ca95b02SDimitry Andric                                            /*IgnoreSPUpdates*/ true);
3323ca95b02SDimitry Andric     assert(UnusedReg ==
3333ca95b02SDimitry Andric            Asm->MF->getSubtarget()
3343ca95b02SDimitry Andric                .getTargetLowering()
3353ca95b02SDimitry Andric                ->getStackPointerRegisterToSaveRestore());
3363ca95b02SDimitry Andric     return Offset;
3373ca95b02SDimitry Andric   }
3383ca95b02SDimitry Andric 
3397d523365SDimitry Andric   // For 32-bit, offsets should be relative to the end of the EH registration
3407d523365SDimitry Andric   // node. For 64-bit, it's relative to SP at the end of the prologue.
3417d523365SDimitry Andric   assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
3427d523365SDimitry Andric   int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
3437d523365SDimitry Andric   Offset += FuncInfo.EHRegNodeEndOffset;
3447d523365SDimitry Andric   return Offset;
3457d523365SDimitry Andric }
3467d523365SDimitry Andric 
3477d523365SDimitry Andric namespace {
3487d523365SDimitry Andric 
3497d523365SDimitry Andric /// Top-level state used to represent unwind to caller
3507d523365SDimitry Andric const int NullState = -1;
3517d523365SDimitry Andric 
3527d523365SDimitry Andric struct InvokeStateChange {
3537d523365SDimitry Andric   /// EH Label immediately after the last invoke in the previous state, or
3547d523365SDimitry Andric   /// nullptr if the previous state was the null state.
3557d523365SDimitry Andric   const MCSymbol *PreviousEndLabel;
3567d523365SDimitry Andric 
3577d523365SDimitry Andric   /// EH label immediately before the first invoke in the new state, or nullptr
3587d523365SDimitry Andric   /// if the new state is the null state.
3597d523365SDimitry Andric   const MCSymbol *NewStartLabel;
3607d523365SDimitry Andric 
3617d523365SDimitry Andric   /// State of the invoke following NewStartLabel, or NullState to indicate
3627d523365SDimitry Andric   /// the presence of calls which may unwind to caller.
3637d523365SDimitry Andric   int NewState;
3647d523365SDimitry Andric };
3657d523365SDimitry Andric 
3667d523365SDimitry Andric /// Iterator that reports all the invoke state changes in a range of machine
3677d523365SDimitry Andric /// basic blocks.  Changes to the null state are reported whenever a call that
3687d523365SDimitry Andric /// may unwind to caller is encountered.  The MBB range is expected to be an
3697d523365SDimitry Andric /// entire function or funclet, and the start and end of the range are treated
3707d523365SDimitry Andric /// as being in the NullState even if there's not an unwind-to-caller call
3717d523365SDimitry Andric /// before the first invoke or after the last one (i.e., the first state change
3727d523365SDimitry Andric /// reported is the first change to something other than NullState, and a
3737d523365SDimitry Andric /// change back to NullState is always reported at the end of iteration).
3747d523365SDimitry Andric class InvokeStateChangeIterator {
InvokeStateChangeIterator(const WinEHFuncInfo & EHInfo,MachineFunction::const_iterator MFI,MachineFunction::const_iterator MFE,MachineBasicBlock::const_iterator MBBI,int BaseState)3757d523365SDimitry Andric   InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
3767d523365SDimitry Andric                             MachineFunction::const_iterator MFI,
3777d523365SDimitry Andric                             MachineFunction::const_iterator MFE,
3787d523365SDimitry Andric                             MachineBasicBlock::const_iterator MBBI,
3797d523365SDimitry Andric                             int BaseState)
3807d523365SDimitry Andric       : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
3817d523365SDimitry Andric     LastStateChange.PreviousEndLabel = nullptr;
3827d523365SDimitry Andric     LastStateChange.NewStartLabel = nullptr;
3837d523365SDimitry Andric     LastStateChange.NewState = BaseState;
3847d523365SDimitry Andric     scan();
3857d523365SDimitry Andric   }
3867d523365SDimitry Andric 
3877d523365SDimitry Andric public:
3887d523365SDimitry Andric   static iterator_range<InvokeStateChangeIterator>
range(const WinEHFuncInfo & EHInfo,MachineFunction::const_iterator Begin,MachineFunction::const_iterator End,int BaseState=NullState)3897d523365SDimitry Andric   range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
3907d523365SDimitry Andric         MachineFunction::const_iterator End, int BaseState = NullState) {
3917d523365SDimitry Andric     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
3927d523365SDimitry Andric     // the end of the last block.
3937d523365SDimitry Andric     assert(Begin != End);
3947d523365SDimitry Andric     auto BlockBegin = Begin->begin();
3957d523365SDimitry Andric     auto BlockEnd = std::prev(End)->end();
3967d523365SDimitry Andric     return make_range(
3977d523365SDimitry Andric         InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
3987d523365SDimitry Andric         InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
3997d523365SDimitry Andric   }
4007d523365SDimitry Andric 
4017d523365SDimitry Andric   // Iterator methods.
operator ==(const InvokeStateChangeIterator & O) const4027d523365SDimitry Andric   bool operator==(const InvokeStateChangeIterator &O) const {
4037d523365SDimitry Andric     assert(BaseState == O.BaseState);
4047d523365SDimitry Andric     // Must be visiting same block.
4057d523365SDimitry Andric     if (MFI != O.MFI)
4067d523365SDimitry Andric       return false;
4077d523365SDimitry Andric     // Must be visiting same isntr.
4087d523365SDimitry Andric     if (MBBI != O.MBBI)
4097d523365SDimitry Andric       return false;
4107d523365SDimitry Andric     // At end of block/instr iteration, we can still have two distinct states:
4117d523365SDimitry Andric     // one to report the final EndLabel, and another indicating the end of the
4127d523365SDimitry Andric     // state change iteration.  Check for CurrentEndLabel equality to
4137d523365SDimitry Andric     // distinguish these.
4147d523365SDimitry Andric     return CurrentEndLabel == O.CurrentEndLabel;
4157d523365SDimitry Andric   }
4167d523365SDimitry Andric 
operator !=(const InvokeStateChangeIterator & O) const4177d523365SDimitry Andric   bool operator!=(const InvokeStateChangeIterator &O) const {
4187d523365SDimitry Andric     return !operator==(O);
4197d523365SDimitry Andric   }
operator *()4207d523365SDimitry Andric   InvokeStateChange &operator*() { return LastStateChange; }
operator ->()4217d523365SDimitry Andric   InvokeStateChange *operator->() { return &LastStateChange; }
operator ++()4227d523365SDimitry Andric   InvokeStateChangeIterator &operator++() { return scan(); }
4237d523365SDimitry Andric 
4247d523365SDimitry Andric private:
4257d523365SDimitry Andric   InvokeStateChangeIterator &scan();
4267d523365SDimitry Andric 
4277d523365SDimitry Andric   const WinEHFuncInfo &EHInfo;
4287d523365SDimitry Andric   const MCSymbol *CurrentEndLabel = nullptr;
4297d523365SDimitry Andric   MachineFunction::const_iterator MFI;
4307d523365SDimitry Andric   MachineFunction::const_iterator MFE;
4317d523365SDimitry Andric   MachineBasicBlock::const_iterator MBBI;
4327d523365SDimitry Andric   InvokeStateChange LastStateChange;
4337d523365SDimitry Andric   bool VisitingInvoke = false;
4347d523365SDimitry Andric   int BaseState;
4357d523365SDimitry Andric };
4367d523365SDimitry Andric 
4377d523365SDimitry Andric } // end anonymous namespace
4387d523365SDimitry Andric 
scan()4397d523365SDimitry Andric InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
4407d523365SDimitry Andric   bool IsNewBlock = false;
4417d523365SDimitry Andric   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
4427d523365SDimitry Andric     if (IsNewBlock)
4437d523365SDimitry Andric       MBBI = MFI->begin();
4447d523365SDimitry Andric     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
4457d523365SDimitry Andric       const MachineInstr &MI = *MBBI;
4467d523365SDimitry Andric       if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
4477d523365SDimitry Andric           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
4487d523365SDimitry Andric         // Indicate a change of state to the null state.  We don't have
4497d523365SDimitry Andric         // start/end EH labels handy but the caller won't expect them for
4507d523365SDimitry Andric         // null state regions.
4517d523365SDimitry Andric         LastStateChange.PreviousEndLabel = CurrentEndLabel;
4527d523365SDimitry Andric         LastStateChange.NewStartLabel = nullptr;
4537d523365SDimitry Andric         LastStateChange.NewState = BaseState;
4547d523365SDimitry Andric         CurrentEndLabel = nullptr;
4557d523365SDimitry Andric         // Don't re-visit this instr on the next scan
4567d523365SDimitry Andric         ++MBBI;
4577d523365SDimitry Andric         return *this;
4587d523365SDimitry Andric       }
4597d523365SDimitry Andric 
4607d523365SDimitry Andric       // All other state changes are at EH labels before/after invokes.
4617d523365SDimitry Andric       if (!MI.isEHLabel())
4627d523365SDimitry Andric         continue;
4637d523365SDimitry Andric       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
4647d523365SDimitry Andric       if (Label == CurrentEndLabel) {
4657d523365SDimitry Andric         VisitingInvoke = false;
4667d523365SDimitry Andric         continue;
4677d523365SDimitry Andric       }
4687d523365SDimitry Andric       auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
4697d523365SDimitry Andric       // Ignore EH labels that aren't the ones inserted before an invoke
4707d523365SDimitry Andric       if (InvokeMapIter == EHInfo.LabelToStateMap.end())
4717d523365SDimitry Andric         continue;
4727d523365SDimitry Andric       auto &StateAndEnd = InvokeMapIter->second;
4737d523365SDimitry Andric       int NewState = StateAndEnd.first;
4747d523365SDimitry Andric       // Keep track of the fact that we're between EH start/end labels so
4757d523365SDimitry Andric       // we know not to treat the inoke we'll see as unwinding to caller.
4767d523365SDimitry Andric       VisitingInvoke = true;
4777d523365SDimitry Andric       if (NewState == LastStateChange.NewState) {
4787d523365SDimitry Andric         // The state isn't actually changing here.  Record the new end and
4797d523365SDimitry Andric         // keep going.
4807d523365SDimitry Andric         CurrentEndLabel = StateAndEnd.second;
4817d523365SDimitry Andric         continue;
4827d523365SDimitry Andric       }
4837d523365SDimitry Andric       // Found a state change to report
4847d523365SDimitry Andric       LastStateChange.PreviousEndLabel = CurrentEndLabel;
4857d523365SDimitry Andric       LastStateChange.NewStartLabel = Label;
4867d523365SDimitry Andric       LastStateChange.NewState = NewState;
4877d523365SDimitry Andric       // Start keeping track of the new current end
4887d523365SDimitry Andric       CurrentEndLabel = StateAndEnd.second;
4897d523365SDimitry Andric       // Don't re-visit this instr on the next scan
4907d523365SDimitry Andric       ++MBBI;
4917d523365SDimitry Andric       return *this;
4927d523365SDimitry Andric     }
4937d523365SDimitry Andric   }
4947d523365SDimitry Andric   // Iteration hit the end of the block range.
4957d523365SDimitry Andric   if (LastStateChange.NewState != BaseState) {
4967d523365SDimitry Andric     // Report the end of the last new state
4977d523365SDimitry Andric     LastStateChange.PreviousEndLabel = CurrentEndLabel;
4987d523365SDimitry Andric     LastStateChange.NewStartLabel = nullptr;
4997d523365SDimitry Andric     LastStateChange.NewState = BaseState;
5007d523365SDimitry Andric     // Leave CurrentEndLabel non-null to distinguish this state from end.
5017d523365SDimitry Andric     assert(CurrentEndLabel != nullptr);
5027d523365SDimitry Andric     return *this;
5037d523365SDimitry Andric   }
5047d523365SDimitry Andric   // We've reported all state changes and hit the end state.
5057d523365SDimitry Andric   CurrentEndLabel = nullptr;
5067d523365SDimitry Andric   return *this;
5077d523365SDimitry Andric }
5087d523365SDimitry Andric 
50997bc6c73SDimitry Andric /// Emit the language-specific data that __C_specific_handler expects.  This
51097bc6c73SDimitry Andric /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
51197bc6c73SDimitry Andric /// up after faults with __try, __except, and __finally.  The typeinfo values
51297bc6c73SDimitry Andric /// are not really RTTI data, but pointers to filter functions that return an
51397bc6c73SDimitry Andric /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
51497bc6c73SDimitry Andric /// blocks and other cleanups, the landing pad label is zero, and the filter
51597bc6c73SDimitry Andric /// function is actually a cleanup handler with the same prototype.  A catch-all
51697bc6c73SDimitry Andric /// entry is modeled with a null filter function field and a non-zero landing
51797bc6c73SDimitry Andric /// pad label.
51897bc6c73SDimitry Andric ///
51997bc6c73SDimitry Andric /// Possible filter function return values:
52097bc6c73SDimitry Andric ///   EXCEPTION_EXECUTE_HANDLER (1):
52197bc6c73SDimitry Andric ///     Jump to the landing pad label after cleanups.
52297bc6c73SDimitry Andric ///   EXCEPTION_CONTINUE_SEARCH (0):
52397bc6c73SDimitry Andric ///     Continue searching this table or continue unwinding.
52497bc6c73SDimitry Andric ///   EXCEPTION_CONTINUE_EXECUTION (-1):
52597bc6c73SDimitry Andric ///     Resume execution at the trapping PC.
52697bc6c73SDimitry Andric ///
52797bc6c73SDimitry Andric /// Inferred table structure:
52897bc6c73SDimitry Andric ///   struct Table {
52997bc6c73SDimitry Andric ///     int NumEntries;
53097bc6c73SDimitry Andric ///     struct Entry {
53197bc6c73SDimitry Andric ///       imagerel32 LabelStart;
53297bc6c73SDimitry Andric ///       imagerel32 LabelEnd;
53397bc6c73SDimitry Andric ///       imagerel32 FilterOrFinally;  // One means catch-all.
53497bc6c73SDimitry Andric ///       imagerel32 LabelLPad;        // Zero means __finally.
53597bc6c73SDimitry Andric ///     } Entries[NumEntries];
53697bc6c73SDimitry Andric ///   };
emitCSpecificHandlerTable(const MachineFunction * MF)5377d523365SDimitry Andric void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
5387d523365SDimitry Andric   auto &OS = *Asm->OutStreamer;
5397d523365SDimitry Andric   MCContext &Ctx = Asm->OutContext;
5407d523365SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
54197bc6c73SDimitry Andric 
5427d523365SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
5437d523365SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
5447d523365SDimitry Andric     if (VerboseAsm)
5457d523365SDimitry Andric       OS.AddComment(Comment);
5467d523365SDimitry Andric   };
54797bc6c73SDimitry Andric 
548*b5893f02SDimitry Andric   if (!isAArch64) {
5497d523365SDimitry Andric     // Emit a label assignment with the SEH frame offset so we can use it for
550*b5893f02SDimitry Andric     // llvm.eh.recoverfp.
5517d523365SDimitry Andric     StringRef FLinkageName =
5522cab237bSDimitry Andric         GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
5537d523365SDimitry Andric     MCSymbol *ParentFrameOffset =
5547d523365SDimitry Andric         Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
5557d523365SDimitry Andric     const MCExpr *MCOffset =
5567d523365SDimitry Andric         MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
5577d523365SDimitry Andric     Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
558*b5893f02SDimitry Andric   }
55997bc6c73SDimitry Andric 
5607d523365SDimitry Andric   // Use the assembler to compute the number of table entries through label
5617d523365SDimitry Andric   // difference and division.
5627d523365SDimitry Andric   MCSymbol *TableBegin =
5637d523365SDimitry Andric       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
5647d523365SDimitry Andric   MCSymbol *TableEnd =
5657d523365SDimitry Andric       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
5667d523365SDimitry Andric   const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
5677d523365SDimitry Andric   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
5687d523365SDimitry Andric   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
5697d523365SDimitry Andric   AddComment("Number of call sites");
5707d523365SDimitry Andric   OS.EmitValue(EntryCount, 4);
57197bc6c73SDimitry Andric 
5727d523365SDimitry Andric   OS.EmitLabel(TableBegin);
57397bc6c73SDimitry Andric 
5747d523365SDimitry Andric   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
5757d523365SDimitry Andric   // models exceptions from invokes. LLVM also allows arbitrary reordering of
5767d523365SDimitry Andric   // the code, so our tables end up looking a bit different. Rather than
5777d523365SDimitry Andric   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
5787d523365SDimitry Andric   // each range of invokes in the same state, we emit table entries for all
5797d523365SDimitry Andric   // the actions that would be taken in that state. This means our tables are
5807d523365SDimitry Andric   // slightly bigger, which is OK.
5817d523365SDimitry Andric   const MCSymbol *LastStartLabel = nullptr;
5827d523365SDimitry Andric   int LastEHState = -1;
5837d523365SDimitry Andric   // Break out before we enter into a finally funclet.
5847d523365SDimitry Andric   // FIXME: We need to emit separate EH tables for cleanups.
5857d523365SDimitry Andric   MachineFunction::const_iterator End = MF->end();
5867d523365SDimitry Andric   MachineFunction::const_iterator Stop = std::next(MF->begin());
5877d523365SDimitry Andric   while (Stop != End && !Stop->isEHFuncletEntry())
5887d523365SDimitry Andric     ++Stop;
5897d523365SDimitry Andric   for (const auto &StateChange :
5907d523365SDimitry Andric        InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
5917d523365SDimitry Andric     // Emit all the actions for the state we just transitioned out of
5927d523365SDimitry Andric     // if it was not the null state
5937d523365SDimitry Andric     if (LastEHState != -1)
5947d523365SDimitry Andric       emitSEHActionsForRange(FuncInfo, LastStartLabel,
5957d523365SDimitry Andric                              StateChange.PreviousEndLabel, LastEHState);
5967d523365SDimitry Andric     LastStartLabel = StateChange.NewStartLabel;
5977d523365SDimitry Andric     LastEHState = StateChange.NewState;
59897bc6c73SDimitry Andric   }
59997bc6c73SDimitry Andric 
6007d523365SDimitry Andric   OS.EmitLabel(TableEnd);
6017d523365SDimitry Andric }
60297bc6c73SDimitry Andric 
emitSEHActionsForRange(const WinEHFuncInfo & FuncInfo,const MCSymbol * BeginLabel,const MCSymbol * EndLabel,int State)6037d523365SDimitry Andric void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
6047d523365SDimitry Andric                                           const MCSymbol *BeginLabel,
6057d523365SDimitry Andric                                           const MCSymbol *EndLabel, int State) {
6067d523365SDimitry Andric   auto &OS = *Asm->OutStreamer;
6077d523365SDimitry Andric   MCContext &Ctx = Asm->OutContext;
6087d523365SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
6097d523365SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
6107d523365SDimitry Andric     if (VerboseAsm)
6117d523365SDimitry Andric       OS.AddComment(Comment);
6127d523365SDimitry Andric   };
6137d523365SDimitry Andric 
6147d523365SDimitry Andric   assert(BeginLabel && EndLabel);
6157d523365SDimitry Andric   while (State != -1) {
6167d523365SDimitry Andric     const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
6177d523365SDimitry Andric     const MCExpr *FilterOrFinally;
6187d523365SDimitry Andric     const MCExpr *ExceptOrNull;
6197d523365SDimitry Andric     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
6207d523365SDimitry Andric     if (UME.IsFinally) {
6217d523365SDimitry Andric       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
6227d523365SDimitry Andric       ExceptOrNull = MCConstantExpr::create(0, Ctx);
62397bc6c73SDimitry Andric     } else {
6247d523365SDimitry Andric       // For an except, the filter can be 1 (catch-all) or a function
6257d523365SDimitry Andric       // label.
6267d523365SDimitry Andric       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
6277d523365SDimitry Andric                                    : MCConstantExpr::create(1, Ctx);
6287d523365SDimitry Andric       ExceptOrNull = create32bitRef(Handler->getSymbol());
62997bc6c73SDimitry Andric     }
63097bc6c73SDimitry Andric 
6317d523365SDimitry Andric     AddComment("LabelStart");
632*b5893f02SDimitry Andric     OS.EmitValue(getLabel(BeginLabel), 4);
6337d523365SDimitry Andric     AddComment("LabelEnd");
634*b5893f02SDimitry Andric     OS.EmitValue(getLabel(EndLabel), 4);
6357d523365SDimitry Andric     AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
6367d523365SDimitry Andric                                                              : "CatchAll");
6377d523365SDimitry Andric     OS.EmitValue(FilterOrFinally, 4);
6387d523365SDimitry Andric     AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
6397d523365SDimitry Andric     OS.EmitValue(ExceptOrNull, 4);
64097bc6c73SDimitry Andric 
6417d523365SDimitry Andric     assert(UME.ToState < State && "states should decrease");
6427d523365SDimitry Andric     State = UME.ToState;
64397bc6c73SDimitry Andric   }
64497bc6c73SDimitry Andric }
64597bc6c73SDimitry Andric 
emitCXXFrameHandler3Table(const MachineFunction * MF)64697bc6c73SDimitry Andric void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
6472cab237bSDimitry Andric   const Function &F = MF->getFunction();
64897bc6c73SDimitry Andric   auto &OS = *Asm->OutStreamer;
6497d523365SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
65097bc6c73SDimitry Andric 
6512cab237bSDimitry Andric   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
65297bc6c73SDimitry Andric 
6537d523365SDimitry Andric   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
65497bc6c73SDimitry Andric   MCSymbol *FuncInfoXData = nullptr;
65597bc6c73SDimitry Andric   if (shouldEmitPersonality) {
6567d523365SDimitry Andric     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
6577d523365SDimitry Andric     // IPs to state numbers.
6587d523365SDimitry Andric     FuncInfoXData =
6597d523365SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
6607d523365SDimitry Andric     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
66197bc6c73SDimitry Andric   } else {
6627d523365SDimitry Andric     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
66397bc6c73SDimitry Andric   }
66497bc6c73SDimitry Andric 
6657d523365SDimitry Andric   int UnwindHelpOffset = 0;
6667d523365SDimitry Andric   if (Asm->MAI->usesWindowsCFI())
6677d523365SDimitry Andric     UnwindHelpOffset =
6687d523365SDimitry Andric         getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
6697d523365SDimitry Andric 
67097bc6c73SDimitry Andric   MCSymbol *UnwindMapXData = nullptr;
67197bc6c73SDimitry Andric   MCSymbol *TryBlockMapXData = nullptr;
67297bc6c73SDimitry Andric   MCSymbol *IPToStateXData = nullptr;
6737d523365SDimitry Andric   if (!FuncInfo.CxxUnwindMap.empty())
67497bc6c73SDimitry Andric     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
6757d523365SDimitry Andric         Twine("$stateUnwindMap$", FuncLinkageName));
67697bc6c73SDimitry Andric   if (!FuncInfo.TryBlockMap.empty())
6777d523365SDimitry Andric     TryBlockMapXData =
6787d523365SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
6797d523365SDimitry Andric   if (!IPToStateTable.empty())
6807d523365SDimitry Andric     IPToStateXData =
6817d523365SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
6827d523365SDimitry Andric 
6837d523365SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
6847d523365SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
6857d523365SDimitry Andric     if (VerboseAsm)
6867d523365SDimitry Andric       OS.AddComment(Comment);
6877d523365SDimitry Andric   };
68897bc6c73SDimitry Andric 
68997bc6c73SDimitry Andric   // FuncInfo {
69097bc6c73SDimitry Andric   //   uint32_t           MagicNumber
69197bc6c73SDimitry Andric   //   int32_t            MaxState;
69297bc6c73SDimitry Andric   //   UnwindMapEntry    *UnwindMap;
69397bc6c73SDimitry Andric   //   uint32_t           NumTryBlocks;
69497bc6c73SDimitry Andric   //   TryBlockMapEntry  *TryBlockMap;
69597bc6c73SDimitry Andric   //   uint32_t           IPMapEntries; // always 0 for x86
69697bc6c73SDimitry Andric   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
69797bc6c73SDimitry Andric   //   uint32_t           UnwindHelp;   // non-x86 only
69897bc6c73SDimitry Andric   //   ESTypeList        *ESTypeList;
69997bc6c73SDimitry Andric   //   int32_t            EHFlags;
70097bc6c73SDimitry Andric   // }
70197bc6c73SDimitry Andric   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
70297bc6c73SDimitry Andric   // EHFlags & 2 -> ???
70397bc6c73SDimitry Andric   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
704875ed548SDimitry Andric   OS.EmitValueToAlignment(4);
70597bc6c73SDimitry Andric   OS.EmitLabel(FuncInfoXData);
7067d523365SDimitry Andric 
7077d523365SDimitry Andric   AddComment("MagicNumber");
7087d523365SDimitry Andric   OS.EmitIntValue(0x19930522, 4);
7097d523365SDimitry Andric 
7107d523365SDimitry Andric   AddComment("MaxState");
7117d523365SDimitry Andric   OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
7127d523365SDimitry Andric 
7137d523365SDimitry Andric   AddComment("UnwindMap");
7147d523365SDimitry Andric   OS.EmitValue(create32bitRef(UnwindMapXData), 4);
7157d523365SDimitry Andric 
7167d523365SDimitry Andric   AddComment("NumTryBlocks");
7177d523365SDimitry Andric   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
7187d523365SDimitry Andric 
7197d523365SDimitry Andric   AddComment("TryBlockMap");
7207d523365SDimitry Andric   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
7217d523365SDimitry Andric 
7227d523365SDimitry Andric   AddComment("IPMapEntries");
7237d523365SDimitry Andric   OS.EmitIntValue(IPToStateTable.size(), 4);
7247d523365SDimitry Andric 
7257d523365SDimitry Andric   AddComment("IPToStateXData");
7267d523365SDimitry Andric   OS.EmitValue(create32bitRef(IPToStateXData), 4);
7277d523365SDimitry Andric 
7287d523365SDimitry Andric   if (Asm->MAI->usesWindowsCFI()) {
7297d523365SDimitry Andric     AddComment("UnwindHelp");
7307d523365SDimitry Andric     OS.EmitIntValue(UnwindHelpOffset, 4);
7317d523365SDimitry Andric   }
7327d523365SDimitry Andric 
7337d523365SDimitry Andric   AddComment("ESTypeList");
7347d523365SDimitry Andric   OS.EmitIntValue(0, 4);
7357d523365SDimitry Andric 
7367d523365SDimitry Andric   AddComment("EHFlags");
7377d523365SDimitry Andric   OS.EmitIntValue(1, 4);
73897bc6c73SDimitry Andric 
73997bc6c73SDimitry Andric   // UnwindMapEntry {
74097bc6c73SDimitry Andric   //   int32_t ToState;
74197bc6c73SDimitry Andric   //   void  (*Action)();
74297bc6c73SDimitry Andric   // };
74397bc6c73SDimitry Andric   if (UnwindMapXData) {
74497bc6c73SDimitry Andric     OS.EmitLabel(UnwindMapXData);
7457d523365SDimitry Andric     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
7467d523365SDimitry Andric       MCSymbol *CleanupSym =
7477d523365SDimitry Andric           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
7487d523365SDimitry Andric       AddComment("ToState");
7497d523365SDimitry Andric       OS.EmitIntValue(UME.ToState, 4);
7507d523365SDimitry Andric 
7517d523365SDimitry Andric       AddComment("Action");
7527d523365SDimitry Andric       OS.EmitValue(create32bitRef(CleanupSym), 4);
75397bc6c73SDimitry Andric     }
75497bc6c73SDimitry Andric   }
75597bc6c73SDimitry Andric 
75697bc6c73SDimitry Andric   // TryBlockMap {
75797bc6c73SDimitry Andric   //   int32_t      TryLow;
75897bc6c73SDimitry Andric   //   int32_t      TryHigh;
75997bc6c73SDimitry Andric   //   int32_t      CatchHigh;
76097bc6c73SDimitry Andric   //   int32_t      NumCatches;
76197bc6c73SDimitry Andric   //   HandlerType *HandlerArray;
76297bc6c73SDimitry Andric   // };
76397bc6c73SDimitry Andric   if (TryBlockMapXData) {
76497bc6c73SDimitry Andric     OS.EmitLabel(TryBlockMapXData);
76597bc6c73SDimitry Andric     SmallVector<MCSymbol *, 1> HandlerMaps;
76697bc6c73SDimitry Andric     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
7677d523365SDimitry Andric       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
76897bc6c73SDimitry Andric 
7697d523365SDimitry Andric       MCSymbol *HandlerMapXData = nullptr;
77097bc6c73SDimitry Andric       if (!TBME.HandlerArray.empty())
77197bc6c73SDimitry Andric         HandlerMapXData =
77297bc6c73SDimitry Andric             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
77397bc6c73SDimitry Andric                                                   .concat(Twine(I))
77497bc6c73SDimitry Andric                                                   .concat("$")
7757d523365SDimitry Andric                                                   .concat(FuncLinkageName));
77697bc6c73SDimitry Andric       HandlerMaps.push_back(HandlerMapXData);
77797bc6c73SDimitry Andric 
7787d523365SDimitry Andric       // TBMEs should form intervals.
7797d523365SDimitry Andric       assert(0 <= TBME.TryLow && "bad trymap interval");
7807d523365SDimitry Andric       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
7817d523365SDimitry Andric       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
7827d523365SDimitry Andric       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
7837d523365SDimitry Andric              "bad trymap interval");
78497bc6c73SDimitry Andric 
7857d523365SDimitry Andric       AddComment("TryLow");
7867d523365SDimitry Andric       OS.EmitIntValue(TBME.TryLow, 4);
7877d523365SDimitry Andric 
7887d523365SDimitry Andric       AddComment("TryHigh");
7897d523365SDimitry Andric       OS.EmitIntValue(TBME.TryHigh, 4);
7907d523365SDimitry Andric 
7917d523365SDimitry Andric       AddComment("CatchHigh");
7927d523365SDimitry Andric       OS.EmitIntValue(TBME.CatchHigh, 4);
7937d523365SDimitry Andric 
7947d523365SDimitry Andric       AddComment("NumCatches");
7957d523365SDimitry Andric       OS.EmitIntValue(TBME.HandlerArray.size(), 4);
7967d523365SDimitry Andric 
7977d523365SDimitry Andric       AddComment("HandlerArray");
7987d523365SDimitry Andric       OS.EmitValue(create32bitRef(HandlerMapXData), 4);
7997d523365SDimitry Andric     }
8007d523365SDimitry Andric 
8017d523365SDimitry Andric     // All funclets use the same parent frame offset currently.
8027d523365SDimitry Andric     unsigned ParentFrameOffset = 0;
8037d523365SDimitry Andric     if (shouldEmitPersonality) {
8047d523365SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
8057d523365SDimitry Andric       ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
80697bc6c73SDimitry Andric     }
80797bc6c73SDimitry Andric 
80897bc6c73SDimitry Andric     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
8097d523365SDimitry Andric       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
81097bc6c73SDimitry Andric       MCSymbol *HandlerMapXData = HandlerMaps[I];
81197bc6c73SDimitry Andric       if (!HandlerMapXData)
81297bc6c73SDimitry Andric         continue;
81397bc6c73SDimitry Andric       // HandlerType {
81497bc6c73SDimitry Andric       //   int32_t         Adjectives;
81597bc6c73SDimitry Andric       //   TypeDescriptor *Type;
81697bc6c73SDimitry Andric       //   int32_t         CatchObjOffset;
81797bc6c73SDimitry Andric       //   void          (*Handler)();
818*b5893f02SDimitry Andric       //   int32_t         ParentFrameOffset; // x64 and AArch64 only
81997bc6c73SDimitry Andric       // };
82097bc6c73SDimitry Andric       OS.EmitLabel(HandlerMapXData);
82197bc6c73SDimitry Andric       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
82297bc6c73SDimitry Andric         // Get the frame escape label with the offset of the catch object. If
8237d523365SDimitry Andric         // the index is INT_MAX, then there is no catch object, and we should
8247d523365SDimitry Andric         // emit an offset of zero, indicating that no copy will occur.
82597bc6c73SDimitry Andric         const MCExpr *FrameAllocOffsetRef = nullptr;
8267d523365SDimitry Andric         if (HT.CatchObj.FrameIndex != INT_MAX) {
8277d523365SDimitry Andric           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
8283ca95b02SDimitry Andric           assert(Offset != 0 && "Illegal offset for catch object!");
8297d523365SDimitry Andric           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
83097bc6c73SDimitry Andric         } else {
83197bc6c73SDimitry Andric           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
83297bc6c73SDimitry Andric         }
83397bc6c73SDimitry Andric 
8347d523365SDimitry Andric         MCSymbol *HandlerSym =
8357d523365SDimitry Andric             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
8367d523365SDimitry Andric 
8377d523365SDimitry Andric         AddComment("Adjectives");
8387d523365SDimitry Andric         OS.EmitIntValue(HT.Adjectives, 4);
8397d523365SDimitry Andric 
8407d523365SDimitry Andric         AddComment("Type");
8417d523365SDimitry Andric         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
8427d523365SDimitry Andric 
8437d523365SDimitry Andric         AddComment("CatchObjOffset");
8447d523365SDimitry Andric         OS.EmitValue(FrameAllocOffsetRef, 4);
8457d523365SDimitry Andric 
8467d523365SDimitry Andric         AddComment("Handler");
8477d523365SDimitry Andric         OS.EmitValue(create32bitRef(HandlerSym), 4);
84897bc6c73SDimitry Andric 
84997bc6c73SDimitry Andric         if (shouldEmitPersonality) {
8507d523365SDimitry Andric           AddComment("ParentFrameOffset");
8517d523365SDimitry Andric           OS.EmitIntValue(ParentFrameOffset, 4);
85297bc6c73SDimitry Andric         }
85397bc6c73SDimitry Andric       }
85497bc6c73SDimitry Andric     }
85597bc6c73SDimitry Andric   }
85697bc6c73SDimitry Andric 
85797bc6c73SDimitry Andric   // IPToStateMapEntry {
85897bc6c73SDimitry Andric   //   void   *IP;
85997bc6c73SDimitry Andric   //   int32_t State;
86097bc6c73SDimitry Andric   // };
86197bc6c73SDimitry Andric   if (IPToStateXData) {
86297bc6c73SDimitry Andric     OS.EmitLabel(IPToStateXData);
8637d523365SDimitry Andric     for (auto &IPStatePair : IPToStateTable) {
8647d523365SDimitry Andric       AddComment("IP");
8657d523365SDimitry Andric       OS.EmitValue(IPStatePair.first, 4);
8667d523365SDimitry Andric       AddComment("ToState");
8677d523365SDimitry Andric       OS.EmitIntValue(IPStatePair.second, 4);
86897bc6c73SDimitry Andric     }
86997bc6c73SDimitry Andric   }
87097bc6c73SDimitry Andric }
87197bc6c73SDimitry Andric 
computeIP2StateTable(const MachineFunction * MF,const WinEHFuncInfo & FuncInfo,SmallVectorImpl<std::pair<const MCExpr *,int>> & IPToStateTable)8727d523365SDimitry Andric void WinException::computeIP2StateTable(
8737d523365SDimitry Andric     const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
8747d523365SDimitry Andric     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
87597bc6c73SDimitry Andric 
8767d523365SDimitry Andric   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
8777d523365SDimitry Andric                                        FuncletEnd = MF->begin(),
8787d523365SDimitry Andric                                        End = MF->end();
8797d523365SDimitry Andric        FuncletStart != End; FuncletStart = FuncletEnd) {
8807d523365SDimitry Andric     // Find the end of the funclet
8817d523365SDimitry Andric     while (++FuncletEnd != End) {
8827d523365SDimitry Andric       if (FuncletEnd->isEHFuncletEntry()) {
8837d523365SDimitry Andric         break;
88497bc6c73SDimitry Andric       }
88597bc6c73SDimitry Andric     }
88697bc6c73SDimitry Andric 
8877d523365SDimitry Andric     // Don't emit ip2state entries for cleanup funclets. Any interesting
8887d523365SDimitry Andric     // exceptional actions in cleanups must be handled in a separate IR
8897d523365SDimitry Andric     // function.
8907d523365SDimitry Andric     if (FuncletStart->isCleanupFuncletEntry())
89197bc6c73SDimitry Andric       continue;
89297bc6c73SDimitry Andric 
8937d523365SDimitry Andric     MCSymbol *StartLabel;
8947d523365SDimitry Andric     int BaseState;
8957d523365SDimitry Andric     if (FuncletStart == MF->begin()) {
8967d523365SDimitry Andric       BaseState = NullState;
8977d523365SDimitry Andric       StartLabel = Asm->getFunctionBegin();
8987d523365SDimitry Andric     } else {
8997d523365SDimitry Andric       auto *FuncletPad =
9007d523365SDimitry Andric           cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
9017d523365SDimitry Andric       assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
9027d523365SDimitry Andric       BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
9037d523365SDimitry Andric       StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
90497bc6c73SDimitry Andric     }
9057d523365SDimitry Andric     assert(StartLabel && "need local function start label");
9067d523365SDimitry Andric     IPToStateTable.push_back(
9077d523365SDimitry Andric         std::make_pair(create32bitRef(StartLabel), BaseState));
90897bc6c73SDimitry Andric 
9097d523365SDimitry Andric     for (const auto &StateChange : InvokeStateChangeIterator::range(
9107d523365SDimitry Andric              FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
9117d523365SDimitry Andric       // Compute the label to report as the start of this entry; use the EH
9127d523365SDimitry Andric       // start label for the invoke if we have one, otherwise (this is a call
9137d523365SDimitry Andric       // which may unwind to our caller and does not have an EH start label, so)
9147d523365SDimitry Andric       // use the previous end label.
9157d523365SDimitry Andric       const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
9167d523365SDimitry Andric       if (!ChangeLabel)
9177d523365SDimitry Andric         ChangeLabel = StateChange.PreviousEndLabel;
9187d523365SDimitry Andric       // Emit an entry indicating that PCs after 'Label' have this EH state.
9197d523365SDimitry Andric       IPToStateTable.push_back(
920*b5893f02SDimitry Andric           std::make_pair(getLabel(ChangeLabel), StateChange.NewState));
9217d523365SDimitry Andric       // FIXME: assert that NewState is between CatchLow and CatchHigh.
92297bc6c73SDimitry Andric     }
92397bc6c73SDimitry Andric   }
92497bc6c73SDimitry Andric }
9258f0fd8f6SDimitry Andric 
emitEHRegistrationOffsetLabel(const WinEHFuncInfo & FuncInfo,StringRef FLinkageName)9263dac3a9bSDimitry Andric void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
9273dac3a9bSDimitry Andric                                                  StringRef FLinkageName) {
9283dac3a9bSDimitry Andric   // Outlined helpers called by the EH runtime need to know the offset of the EH
9293dac3a9bSDimitry Andric   // registration in order to recover the parent frame pointer. Now that we know
9303dac3a9bSDimitry Andric   // we've code generated the parent, we can emit the label assignment that
9313dac3a9bSDimitry Andric   // those helpers use to get the offset of the registration node.
932d88c1a5aSDimitry Andric 
933d88c1a5aSDimitry Andric   // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
934d88c1a5aSDimitry Andric   // after optimization all the invokes were eliminated. We still need to emit
935d88c1a5aSDimitry Andric   // the parent frame offset label, but it should be garbage and should never be
936d88c1a5aSDimitry Andric   // used.
937d88c1a5aSDimitry Andric   int64_t Offset = 0;
938d88c1a5aSDimitry Andric   int FI = FuncInfo.EHRegNodeFrameIndex;
939d88c1a5aSDimitry Andric   if (FI != INT_MAX) {
940d88c1a5aSDimitry Andric     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
941d88c1a5aSDimitry Andric     unsigned UnusedReg;
942*b5893f02SDimitry Andric     // FIXME: getFrameIndexReference needs to match the behavior of
943*b5893f02SDimitry Andric     // AArch64RegisterInfo::hasBasePointer in which one of the scenarios where
944*b5893f02SDimitry Andric     // SP is used is if frame size >= 256.
945d88c1a5aSDimitry Andric     Offset = TFI->getFrameIndexReference(*Asm->MF, FI, UnusedReg);
946d88c1a5aSDimitry Andric   }
947d88c1a5aSDimitry Andric 
9487d523365SDimitry Andric   MCContext &Ctx = Asm->OutContext;
9493dac3a9bSDimitry Andric   MCSymbol *ParentFrameOffset =
9507d523365SDimitry Andric       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
951d88c1a5aSDimitry Andric   Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
952d88c1a5aSDimitry Andric                                    MCConstantExpr::create(Offset, Ctx));
9533dac3a9bSDimitry Andric }
9543dac3a9bSDimitry Andric 
9558f0fd8f6SDimitry Andric /// Emit the language-specific data that _except_handler3 and 4 expect. This is
9568f0fd8f6SDimitry Andric /// functionally equivalent to the __C_specific_handler table, except it is
9578f0fd8f6SDimitry Andric /// indexed by state number instead of IP.
emitExceptHandlerTable(const MachineFunction * MF)9588f0fd8f6SDimitry Andric void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
9598f0fd8f6SDimitry Andric   MCStreamer &OS = *Asm->OutStreamer;
9602cab237bSDimitry Andric   const Function &F = MF->getFunction();
9612cab237bSDimitry Andric   StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
9623dac3a9bSDimitry Andric 
9637d523365SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
9647d523365SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
9657d523365SDimitry Andric     if (VerboseAsm)
9667d523365SDimitry Andric       OS.AddComment(Comment);
9677d523365SDimitry Andric   };
9687d523365SDimitry Andric 
9697d523365SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
9703dac3a9bSDimitry Andric   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
9718f0fd8f6SDimitry Andric 
9728f0fd8f6SDimitry Andric   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
9738f0fd8f6SDimitry Andric   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
974875ed548SDimitry Andric   OS.EmitValueToAlignment(4);
9758f0fd8f6SDimitry Andric   OS.EmitLabel(LSDALabel);
9768f0fd8f6SDimitry Andric 
977875ed548SDimitry Andric   const Function *Per =
9782cab237bSDimitry Andric       dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
9798f0fd8f6SDimitry Andric   StringRef PerName = Per->getName();
9808f0fd8f6SDimitry Andric   int BaseState = -1;
9818f0fd8f6SDimitry Andric   if (PerName == "_except_handler4") {
9828f0fd8f6SDimitry Andric     // The LSDA for _except_handler4 starts with this struct, followed by the
9838f0fd8f6SDimitry Andric     // scope table:
9848f0fd8f6SDimitry Andric     //
9858f0fd8f6SDimitry Andric     // struct EH4ScopeTable {
9868f0fd8f6SDimitry Andric     //   int32_t GSCookieOffset;
9878f0fd8f6SDimitry Andric     //   int32_t GSCookieXOROffset;
9888f0fd8f6SDimitry Andric     //   int32_t EHCookieOffset;
9898f0fd8f6SDimitry Andric     //   int32_t EHCookieXOROffset;
9908f0fd8f6SDimitry Andric     //   ScopeTableEntry ScopeRecord[];
9918f0fd8f6SDimitry Andric     // };
9928f0fd8f6SDimitry Andric     //
9933ca95b02SDimitry Andric     // Offsets are %ebp relative.
9943ca95b02SDimitry Andric     //
9953ca95b02SDimitry Andric     // The GS cookie is present only if the function needs stack protection.
9963ca95b02SDimitry Andric     // GSCookieOffset = -2 means that GS cookie is not used.
9973ca95b02SDimitry Andric     //
9983ca95b02SDimitry Andric     // The EH cookie is always present.
9993ca95b02SDimitry Andric     //
10003ca95b02SDimitry Andric     // Check is done the following way:
10013ca95b02SDimitry Andric     //    (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
10023ca95b02SDimitry Andric 
10033ca95b02SDimitry Andric     // Retrieve the Guard Stack slot.
10043ca95b02SDimitry Andric     int GSCookieOffset = -2;
1005d88c1a5aSDimitry Andric     const MachineFrameInfo &MFI = MF->getFrameInfo();
1006d88c1a5aSDimitry Andric     if (MFI.hasStackProtectorIndex()) {
10073ca95b02SDimitry Andric       unsigned UnusedReg;
10083ca95b02SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1009d88c1a5aSDimitry Andric       int SSPIdx = MFI.getStackProtectorIndex();
10103ca95b02SDimitry Andric       GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
10113ca95b02SDimitry Andric     }
10123ca95b02SDimitry Andric 
10133ca95b02SDimitry Andric     // Retrieve the EH Guard slot.
10143ca95b02SDimitry Andric     // TODO(etienneb): Get rid of this value and change it for and assertion.
10153ca95b02SDimitry Andric     int EHCookieOffset = 9999;
10163ca95b02SDimitry Andric     if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
10173ca95b02SDimitry Andric       unsigned UnusedReg;
10183ca95b02SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
10193ca95b02SDimitry Andric       int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
10203ca95b02SDimitry Andric       EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
10213ca95b02SDimitry Andric     }
10223ca95b02SDimitry Andric 
10237d523365SDimitry Andric     AddComment("GSCookieOffset");
10243ca95b02SDimitry Andric     OS.EmitIntValue(GSCookieOffset, 4);
10257d523365SDimitry Andric     AddComment("GSCookieXOROffset");
10268f0fd8f6SDimitry Andric     OS.EmitIntValue(0, 4);
10277d523365SDimitry Andric     AddComment("EHCookieOffset");
10283ca95b02SDimitry Andric     OS.EmitIntValue(EHCookieOffset, 4);
10297d523365SDimitry Andric     AddComment("EHCookieXOROffset");
10308f0fd8f6SDimitry Andric     OS.EmitIntValue(0, 4);
10318f0fd8f6SDimitry Andric     BaseState = -2;
10328f0fd8f6SDimitry Andric   }
10338f0fd8f6SDimitry Andric 
10347d523365SDimitry Andric   assert(!FuncInfo.SEHUnwindMap.empty());
10357d523365SDimitry Andric   for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
10367d523365SDimitry Andric     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
10377d523365SDimitry Andric     const MCSymbol *ExceptOrFinally =
10387d523365SDimitry Andric         UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
10397d523365SDimitry Andric     // -1 is usually the base state for "unwind to caller", but for
10407d523365SDimitry Andric     // _except_handler4 it's -2. Do that replacement here if necessary.
10417d523365SDimitry Andric     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
10427d523365SDimitry Andric     AddComment("ToState");
10437d523365SDimitry Andric     OS.EmitIntValue(ToState, 4);
10447d523365SDimitry Andric     AddComment(UME.IsFinally ? "Null" : "FilterFunction");
10457d523365SDimitry Andric     OS.EmitValue(create32bitRef(UME.Filter), 4);
10467d523365SDimitry Andric     AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
10477d523365SDimitry Andric     OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
10488f0fd8f6SDimitry Andric   }
10498f0fd8f6SDimitry Andric }
10507d523365SDimitry Andric 
getTryRank(const WinEHFuncInfo & FuncInfo,int State)10514d0b32cdSDimitry Andric static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
10527d523365SDimitry Andric   int Rank = 0;
10537d523365SDimitry Andric   while (State != -1) {
10547d523365SDimitry Andric     ++Rank;
10554d0b32cdSDimitry Andric     State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
10567d523365SDimitry Andric   }
10577d523365SDimitry Andric   return Rank;
10587d523365SDimitry Andric }
10597d523365SDimitry Andric 
getTryAncestor(const WinEHFuncInfo & FuncInfo,int Left,int Right)10604d0b32cdSDimitry Andric static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
10614d0b32cdSDimitry Andric   int LeftRank = getTryRank(FuncInfo, Left);
10624d0b32cdSDimitry Andric   int RightRank = getTryRank(FuncInfo, Right);
10637d523365SDimitry Andric 
10647d523365SDimitry Andric   while (LeftRank < RightRank) {
10654d0b32cdSDimitry Andric     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
10667d523365SDimitry Andric     --RightRank;
10677d523365SDimitry Andric   }
10687d523365SDimitry Andric 
10697d523365SDimitry Andric   while (RightRank < LeftRank) {
10704d0b32cdSDimitry Andric     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
10717d523365SDimitry Andric     --LeftRank;
10727d523365SDimitry Andric   }
10737d523365SDimitry Andric 
10747d523365SDimitry Andric   while (Left != Right) {
10754d0b32cdSDimitry Andric     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
10764d0b32cdSDimitry Andric     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
10777d523365SDimitry Andric   }
10787d523365SDimitry Andric 
10797d523365SDimitry Andric   return Left;
10807d523365SDimitry Andric }
10817d523365SDimitry Andric 
emitCLRExceptionTable(const MachineFunction * MF)10827d523365SDimitry Andric void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
10837d523365SDimitry Andric   // CLR EH "states" are really just IDs that identify handlers/funclets;
10847d523365SDimitry Andric   // states, handlers, and funclets all have 1:1 mappings between them, and a
10857d523365SDimitry Andric   // handler/funclet's "state" is its index in the ClrEHUnwindMap.
10867d523365SDimitry Andric   MCStreamer &OS = *Asm->OutStreamer;
10877d523365SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
10887d523365SDimitry Andric   MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
10897d523365SDimitry Andric   MCSymbol *FuncEndSym = Asm->getFunctionEnd();
10907d523365SDimitry Andric 
10917d523365SDimitry Andric   // A ClrClause describes a protected region.
10927d523365SDimitry Andric   struct ClrClause {
10937d523365SDimitry Andric     const MCSymbol *StartLabel; // Start of protected region
10947d523365SDimitry Andric     const MCSymbol *EndLabel;   // End of protected region
10957d523365SDimitry Andric     int State;          // Index of handler protecting the protected region
10967d523365SDimitry Andric     int EnclosingState; // Index of funclet enclosing the protected region
10977d523365SDimitry Andric   };
10987d523365SDimitry Andric   SmallVector<ClrClause, 8> Clauses;
10997d523365SDimitry Andric 
11007d523365SDimitry Andric   // Build a map from handler MBBs to their corresponding states (i.e. their
11017d523365SDimitry Andric   // indices in the ClrEHUnwindMap).
11027d523365SDimitry Andric   int NumStates = FuncInfo.ClrEHUnwindMap.size();
11037d523365SDimitry Andric   assert(NumStates > 0 && "Don't need exception table!");
11047d523365SDimitry Andric   DenseMap<const MachineBasicBlock *, int> HandlerStates;
11057d523365SDimitry Andric   for (int State = 0; State < NumStates; ++State) {
11067d523365SDimitry Andric     MachineBasicBlock *HandlerBlock =
11077d523365SDimitry Andric         FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
11087d523365SDimitry Andric     HandlerStates[HandlerBlock] = State;
11097d523365SDimitry Andric     // Use this loop through all handlers to verify our assumption (used in
11104d0b32cdSDimitry Andric     // the MinEnclosingState computation) that enclosing funclets have lower
11114d0b32cdSDimitry Andric     // state numbers than their enclosed funclets.
11124d0b32cdSDimitry Andric     assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
11137d523365SDimitry Andric            "ill-formed state numbering");
11147d523365SDimitry Andric   }
11157d523365SDimitry Andric   // Map the main function to the NullState.
11167d523365SDimitry Andric   HandlerStates[&MF->front()] = NullState;
11177d523365SDimitry Andric 
11187d523365SDimitry Andric   // Write out a sentinel indicating the end of the standard (Windows) xdata
11197d523365SDimitry Andric   // and the start of the additional (CLR) info.
11207d523365SDimitry Andric   OS.EmitIntValue(0xffffffff, 4);
11217d523365SDimitry Andric   // Write out the number of funclets
11227d523365SDimitry Andric   OS.EmitIntValue(NumStates, 4);
11237d523365SDimitry Andric 
11247d523365SDimitry Andric   // Walk the machine blocks/instrs, computing and emitting a few things:
11257d523365SDimitry Andric   // 1. Emit a list of the offsets to each handler entry, in lexical order.
11267d523365SDimitry Andric   // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
11277d523365SDimitry Andric   // 3. Compute the list of ClrClauses, in the required order (inner before
11287d523365SDimitry Andric   //    outer, earlier before later; the order by which a forward scan with
11297d523365SDimitry Andric   //    early termination will find the innermost enclosing clause covering
11307d523365SDimitry Andric   //    a given address).
11317d523365SDimitry Andric   // 4. A map (MinClauseMap) from each handler index to the index of the
11327d523365SDimitry Andric   //    outermost funclet/function which contains a try clause targeting the
11337d523365SDimitry Andric   //    key handler.  This will be used to determine IsDuplicate-ness when
11347d523365SDimitry Andric   //    emitting ClrClauses.  The NullState value is used to indicate that the
11357d523365SDimitry Andric   //    top-level function contains a try clause targeting the key handler.
11367d523365SDimitry Andric   // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
11377d523365SDimitry Andric   // try regions we entered before entering the PendingState try but which
11387d523365SDimitry Andric   // we haven't yet exited.
11397d523365SDimitry Andric   SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
11407d523365SDimitry Andric   // EndSymbolMap and MinClauseMap are maps described above.
11417d523365SDimitry Andric   std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
11427d523365SDimitry Andric   SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
11437d523365SDimitry Andric 
11447d523365SDimitry Andric   // Visit the root function and each funclet.
11457d523365SDimitry Andric   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
11467d523365SDimitry Andric                                        FuncletEnd = MF->begin(),
11477d523365SDimitry Andric                                        End = MF->end();
11487d523365SDimitry Andric        FuncletStart != End; FuncletStart = FuncletEnd) {
11497d523365SDimitry Andric     int FuncletState = HandlerStates[&*FuncletStart];
11507d523365SDimitry Andric     // Find the end of the funclet
11517d523365SDimitry Andric     MCSymbol *EndSymbol = FuncEndSym;
11527d523365SDimitry Andric     while (++FuncletEnd != End) {
11537d523365SDimitry Andric       if (FuncletEnd->isEHFuncletEntry()) {
11547d523365SDimitry Andric         EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
11557d523365SDimitry Andric         break;
11567d523365SDimitry Andric       }
11577d523365SDimitry Andric     }
11587d523365SDimitry Andric     // Emit the function/funclet end and, if this is a funclet (and not the
11597d523365SDimitry Andric     // root function), record it in the EndSymbolMap.
11607d523365SDimitry Andric     OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
11617d523365SDimitry Andric     if (FuncletState != NullState) {
11627d523365SDimitry Andric       // Record the end of the handler.
11637d523365SDimitry Andric       EndSymbolMap[FuncletState] = EndSymbol;
11647d523365SDimitry Andric     }
11657d523365SDimitry Andric 
11667d523365SDimitry Andric     // Walk the state changes in this function/funclet and compute its clauses.
11677d523365SDimitry Andric     // Funclets always start in the null state.
11687d523365SDimitry Andric     const MCSymbol *CurrentStartLabel = nullptr;
11697d523365SDimitry Andric     int CurrentState = NullState;
11707d523365SDimitry Andric     assert(HandlerStack.empty());
11717d523365SDimitry Andric     for (const auto &StateChange :
11727d523365SDimitry Andric          InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
11737d523365SDimitry Andric       // Close any try regions we're not still under
11744d0b32cdSDimitry Andric       int StillPendingState =
11754d0b32cdSDimitry Andric           getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
11764d0b32cdSDimitry Andric       while (CurrentState != StillPendingState) {
11774d0b32cdSDimitry Andric         assert(CurrentState != NullState &&
11784d0b32cdSDimitry Andric                "Failed to find still-pending state!");
11797d523365SDimitry Andric         // Close the pending clause
11807d523365SDimitry Andric         Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
11817d523365SDimitry Andric                            CurrentState, FuncletState});
11824d0b32cdSDimitry Andric         // Now the next-outer try region is current
11834d0b32cdSDimitry Andric         CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
11847d523365SDimitry Andric         // Pop the new start label from the handler stack if we've exited all
11854d0b32cdSDimitry Andric         // inner try regions of the corresponding try region.
11867d523365SDimitry Andric         if (HandlerStack.back().second == CurrentState)
11877d523365SDimitry Andric           CurrentStartLabel = HandlerStack.pop_back_val().first;
11887d523365SDimitry Andric       }
11897d523365SDimitry Andric 
11907d523365SDimitry Andric       if (StateChange.NewState != CurrentState) {
11917d523365SDimitry Andric         // For each clause we're starting, update the MinClauseMap so we can
11927d523365SDimitry Andric         // know which is the topmost funclet containing a clause targeting
11937d523365SDimitry Andric         // it.
11947d523365SDimitry Andric         for (int EnteredState = StateChange.NewState;
11957d523365SDimitry Andric              EnteredState != CurrentState;
11964d0b32cdSDimitry Andric              EnteredState =
11974d0b32cdSDimitry Andric                  FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
11987d523365SDimitry Andric           int &MinEnclosingState = MinClauseMap[EnteredState];
11997d523365SDimitry Andric           if (FuncletState < MinEnclosingState)
12007d523365SDimitry Andric             MinEnclosingState = FuncletState;
12017d523365SDimitry Andric         }
12027d523365SDimitry Andric         // Save the previous current start/label on the stack and update to
12037d523365SDimitry Andric         // the newly-current start/state.
12047d523365SDimitry Andric         HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
12057d523365SDimitry Andric         CurrentStartLabel = StateChange.NewStartLabel;
12067d523365SDimitry Andric         CurrentState = StateChange.NewState;
12077d523365SDimitry Andric       }
12087d523365SDimitry Andric     }
12097d523365SDimitry Andric     assert(HandlerStack.empty());
12107d523365SDimitry Andric   }
12117d523365SDimitry Andric 
12127d523365SDimitry Andric   // Now emit the clause info, starting with the number of clauses.
12137d523365SDimitry Andric   OS.EmitIntValue(Clauses.size(), 4);
12147d523365SDimitry Andric   for (ClrClause &Clause : Clauses) {
12157d523365SDimitry Andric     // Emit a CORINFO_EH_CLAUSE :
12167d523365SDimitry Andric     /*
12177d523365SDimitry Andric       struct CORINFO_EH_CLAUSE
12187d523365SDimitry Andric       {
12197d523365SDimitry Andric           CORINFO_EH_CLAUSE_FLAGS Flags;         // actually a CorExceptionFlag
12207d523365SDimitry Andric           DWORD                   TryOffset;
12217d523365SDimitry Andric           DWORD                   TryLength;     // actually TryEndOffset
12227d523365SDimitry Andric           DWORD                   HandlerOffset;
12237d523365SDimitry Andric           DWORD                   HandlerLength; // actually HandlerEndOffset
12247d523365SDimitry Andric           union
12257d523365SDimitry Andric           {
12267d523365SDimitry Andric               DWORD               ClassToken;   // use for catch clauses
12277d523365SDimitry Andric               DWORD               FilterOffset; // use for filter clauses
12287d523365SDimitry Andric           };
12297d523365SDimitry Andric       };
12307d523365SDimitry Andric 
12317d523365SDimitry Andric       enum CORINFO_EH_CLAUSE_FLAGS
12327d523365SDimitry Andric       {
12337d523365SDimitry Andric           CORINFO_EH_CLAUSE_NONE    = 0,
12347d523365SDimitry Andric           CORINFO_EH_CLAUSE_FILTER  = 0x0001, // This clause is for a filter
12357d523365SDimitry Andric           CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
12367d523365SDimitry Andric           CORINFO_EH_CLAUSE_FAULT   = 0x0004, // This clause is a fault clause
12377d523365SDimitry Andric       };
12387d523365SDimitry Andric       typedef enum CorExceptionFlag
12397d523365SDimitry Andric       {
12407d523365SDimitry Andric           COR_ILEXCEPTION_CLAUSE_NONE,
12417d523365SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FILTER  = 0x0001, // This is a filter clause
12427d523365SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
12437d523365SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004,   // This is a fault clause
12447d523365SDimitry Andric           COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
12457d523365SDimitry Andric                                                       // clause was duplicated
12467d523365SDimitry Andric                                                       // to a funclet which was
12477d523365SDimitry Andric                                                       // pulled out of line
12487d523365SDimitry Andric       } CorExceptionFlag;
12497d523365SDimitry Andric     */
12507d523365SDimitry Andric     // Add 1 to the start/end of the EH clause; the IP associated with a
12517d523365SDimitry Andric     // call when the runtime does its scan is the IP of the next instruction
12527d523365SDimitry Andric     // (the one to which control will return after the call), so we need
12537d523365SDimitry Andric     // to add 1 to the end of the clause to cover that offset.  We also add
12547d523365SDimitry Andric     // 1 to the start of the clause to make sure that the ranges reported
12557d523365SDimitry Andric     // for all clauses are disjoint.  Note that we'll need some additional
12567d523365SDimitry Andric     // logic when machine traps are supported, since in that case the IP
12577d523365SDimitry Andric     // that the runtime uses is the offset of the faulting instruction
12587d523365SDimitry Andric     // itself; if such an instruction immediately follows a call but the
12597d523365SDimitry Andric     // two belong to different clauses, we'll need to insert a nop between
12607d523365SDimitry Andric     // them so the runtime can distinguish the point to which the call will
12617d523365SDimitry Andric     // return from the point at which the fault occurs.
12627d523365SDimitry Andric 
12637d523365SDimitry Andric     const MCExpr *ClauseBegin =
12647d523365SDimitry Andric         getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
12657d523365SDimitry Andric     const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
12667d523365SDimitry Andric 
12677d523365SDimitry Andric     const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
12687d523365SDimitry Andric     MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
12697d523365SDimitry Andric     MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
12707d523365SDimitry Andric     const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
12717d523365SDimitry Andric     MCSymbol *EndSym = EndSymbolMap[Clause.State];
12727d523365SDimitry Andric     const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
12737d523365SDimitry Andric 
12747d523365SDimitry Andric     uint32_t Flags = 0;
12757d523365SDimitry Andric     switch (Entry.HandlerType) {
12767d523365SDimitry Andric     case ClrHandlerType::Catch:
12777d523365SDimitry Andric       // Leaving bits 0-2 clear indicates catch.
12787d523365SDimitry Andric       break;
12797d523365SDimitry Andric     case ClrHandlerType::Filter:
12807d523365SDimitry Andric       Flags |= 1;
12817d523365SDimitry Andric       break;
12827d523365SDimitry Andric     case ClrHandlerType::Finally:
12837d523365SDimitry Andric       Flags |= 2;
12847d523365SDimitry Andric       break;
12857d523365SDimitry Andric     case ClrHandlerType::Fault:
12867d523365SDimitry Andric       Flags |= 4;
12877d523365SDimitry Andric       break;
12887d523365SDimitry Andric     }
12897d523365SDimitry Andric     if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
12907d523365SDimitry Andric       // This is a "duplicate" clause; the handler needs to be entered from a
12917d523365SDimitry Andric       // frame above the one holding the invoke.
12927d523365SDimitry Andric       assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
12937d523365SDimitry Andric       Flags |= 8;
12947d523365SDimitry Andric     }
12957d523365SDimitry Andric     OS.EmitIntValue(Flags, 4);
12967d523365SDimitry Andric 
12977d523365SDimitry Andric     // Write the clause start/end
12987d523365SDimitry Andric     OS.EmitValue(ClauseBegin, 4);
12997d523365SDimitry Andric     OS.EmitValue(ClauseEnd, 4);
13007d523365SDimitry Andric 
13017d523365SDimitry Andric     // Write out the handler start/end
13027d523365SDimitry Andric     OS.EmitValue(HandlerBegin, 4);
13037d523365SDimitry Andric     OS.EmitValue(HandlerEnd, 4);
13047d523365SDimitry Andric 
13057d523365SDimitry Andric     // Write out the type token or filter offset
13067d523365SDimitry Andric     assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
13077d523365SDimitry Andric     OS.EmitIntValue(Entry.TypeToken, 4);
13087d523365SDimitry Andric   }
13098f0fd8f6SDimitry Andric }
1310