xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/WinException.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file contains support for writing Win64 exception info into asm files.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "WinException.h"
14*0b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
15*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
16*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
17*0b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
18*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
19*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
20*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
21*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
22*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
23*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
24*0b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
25*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
26*0b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
27*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
28*0b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
29*0b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
30*0b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
31*0b57cec5SDimitry Andric #include "llvm/MC/MCSection.h"
32*0b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
33*0b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
34*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
35*0b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
36*0b57cec5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
37*0b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
38*0b57cec5SDimitry Andric using namespace llvm;
39*0b57cec5SDimitry Andric 
40*0b57cec5SDimitry Andric WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
41*0b57cec5SDimitry Andric   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
42*0b57cec5SDimitry Andric   // platforms use an imagerel32 relocation to refer to symbols.
43*0b57cec5SDimitry Andric   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
44*0b57cec5SDimitry Andric   isAArch64 = Asm->TM.getTargetTriple().isAArch64();
45*0b57cec5SDimitry Andric }
46*0b57cec5SDimitry Andric 
47*0b57cec5SDimitry Andric WinException::~WinException() {}
48*0b57cec5SDimitry Andric 
49*0b57cec5SDimitry Andric /// endModule - Emit all exception information that should come after the
50*0b57cec5SDimitry Andric /// content.
51*0b57cec5SDimitry Andric void WinException::endModule() {
52*0b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
53*0b57cec5SDimitry Andric   const Module *M = MMI->getModule();
54*0b57cec5SDimitry Andric   for (const Function &F : *M)
55*0b57cec5SDimitry Andric     if (F.hasFnAttribute("safeseh"))
56*0b57cec5SDimitry Andric       OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
57*0b57cec5SDimitry Andric }
58*0b57cec5SDimitry Andric 
59*0b57cec5SDimitry Andric void WinException::beginFunction(const MachineFunction *MF) {
60*0b57cec5SDimitry Andric   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
61*0b57cec5SDimitry Andric 
62*0b57cec5SDimitry Andric   // If any landing pads survive, we need an EH table.
63*0b57cec5SDimitry Andric   bool hasLandingPads = !MF->getLandingPads().empty();
64*0b57cec5SDimitry Andric   bool hasEHFunclets = MF->hasEHFunclets();
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric   const Function &F = MF->getFunction();
67*0b57cec5SDimitry Andric 
68*0b57cec5SDimitry Andric   shouldEmitMoves = Asm->needsSEHMoves() && MF->hasWinCFI();
69*0b57cec5SDimitry Andric 
70*0b57cec5SDimitry Andric   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
71*0b57cec5SDimitry Andric   unsigned PerEncoding = TLOF.getPersonalityEncoding();
72*0b57cec5SDimitry Andric 
73*0b57cec5SDimitry Andric   EHPersonality Per = EHPersonality::Unknown;
74*0b57cec5SDimitry Andric   const Function *PerFn = nullptr;
75*0b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
76*0b57cec5SDimitry Andric     PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
77*0b57cec5SDimitry Andric     Per = classifyEHPersonality(PerFn);
78*0b57cec5SDimitry Andric   }
79*0b57cec5SDimitry Andric 
80*0b57cec5SDimitry Andric   bool forceEmitPersonality = F.hasPersonalityFn() &&
81*0b57cec5SDimitry Andric                               !isNoOpWithoutInvoke(Per) &&
82*0b57cec5SDimitry Andric                               F.needsUnwindTableEntry();
83*0b57cec5SDimitry Andric 
84*0b57cec5SDimitry Andric   shouldEmitPersonality =
85*0b57cec5SDimitry Andric       forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
86*0b57cec5SDimitry Andric                                PerEncoding != dwarf::DW_EH_PE_omit && PerFn);
87*0b57cec5SDimitry Andric 
88*0b57cec5SDimitry Andric   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
89*0b57cec5SDimitry Andric   shouldEmitLSDA = shouldEmitPersonality &&
90*0b57cec5SDimitry Andric     LSDAEncoding != dwarf::DW_EH_PE_omit;
91*0b57cec5SDimitry Andric 
92*0b57cec5SDimitry Andric   // If we're not using CFI, we don't want the CFI or the personality, but we
93*0b57cec5SDimitry Andric   // might want EH tables if we had EH pads.
94*0b57cec5SDimitry Andric   if (!Asm->MAI->usesWindowsCFI()) {
95*0b57cec5SDimitry Andric     if (Per == EHPersonality::MSVC_X86SEH && !hasEHFunclets) {
96*0b57cec5SDimitry Andric       // If this is 32-bit SEH and we don't have any funclets (really invokes),
97*0b57cec5SDimitry Andric       // make sure we emit the parent offset label. Some unreferenced filter
98*0b57cec5SDimitry Andric       // functions may still refer to it.
99*0b57cec5SDimitry Andric       const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
100*0b57cec5SDimitry Andric       StringRef FLinkageName =
101*0b57cec5SDimitry Andric           GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
102*0b57cec5SDimitry Andric       emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
103*0b57cec5SDimitry Andric     }
104*0b57cec5SDimitry Andric     shouldEmitLSDA = hasEHFunclets;
105*0b57cec5SDimitry Andric     shouldEmitPersonality = false;
106*0b57cec5SDimitry Andric     return;
107*0b57cec5SDimitry Andric   }
108*0b57cec5SDimitry Andric 
109*0b57cec5SDimitry Andric   beginFunclet(MF->front(), Asm->CurrentFnSym);
110*0b57cec5SDimitry Andric }
111*0b57cec5SDimitry Andric 
112*0b57cec5SDimitry Andric void WinException::markFunctionEnd() {
113*0b57cec5SDimitry Andric   if (isAArch64 && CurrentFuncletEntry &&
114*0b57cec5SDimitry Andric       (shouldEmitMoves || shouldEmitPersonality))
115*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
116*0b57cec5SDimitry Andric }
117*0b57cec5SDimitry Andric 
118*0b57cec5SDimitry Andric /// endFunction - Gather and emit post-function exception information.
119*0b57cec5SDimitry Andric ///
120*0b57cec5SDimitry Andric void WinException::endFunction(const MachineFunction *MF) {
121*0b57cec5SDimitry Andric   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
122*0b57cec5SDimitry Andric     return;
123*0b57cec5SDimitry Andric 
124*0b57cec5SDimitry Andric   const Function &F = MF->getFunction();
125*0b57cec5SDimitry Andric   EHPersonality Per = EHPersonality::Unknown;
126*0b57cec5SDimitry Andric   if (F.hasPersonalityFn())
127*0b57cec5SDimitry Andric     Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric   // Get rid of any dead landing pads if we're not using funclets. In funclet
130*0b57cec5SDimitry Andric   // schemes, the landing pad is not actually reachable. It only exists so
131*0b57cec5SDimitry Andric   // that we can emit the right table data.
132*0b57cec5SDimitry Andric   if (!isFuncletEHPersonality(Per)) {
133*0b57cec5SDimitry Andric     MachineFunction *NonConstMF = const_cast<MachineFunction*>(MF);
134*0b57cec5SDimitry Andric     NonConstMF->tidyLandingPads();
135*0b57cec5SDimitry Andric   }
136*0b57cec5SDimitry Andric 
137*0b57cec5SDimitry Andric   endFuncletImpl();
138*0b57cec5SDimitry Andric 
139*0b57cec5SDimitry Andric   // endFunclet will emit the necessary .xdata tables for x64 SEH.
140*0b57cec5SDimitry Andric   if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets())
141*0b57cec5SDimitry Andric     return;
142*0b57cec5SDimitry Andric 
143*0b57cec5SDimitry Andric   if (shouldEmitPersonality || shouldEmitLSDA) {
144*0b57cec5SDimitry Andric     Asm->OutStreamer->PushSection();
145*0b57cec5SDimitry Andric 
146*0b57cec5SDimitry Andric     // Just switch sections to the right xdata section.
147*0b57cec5SDimitry Andric     MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
148*0b57cec5SDimitry Andric         Asm->OutStreamer->getCurrentSectionOnly());
149*0b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(XData);
150*0b57cec5SDimitry Andric 
151*0b57cec5SDimitry Andric     // Emit the tables appropriate to the personality function in use. If we
152*0b57cec5SDimitry Andric     // don't recognize the personality, assume it uses an Itanium-style LSDA.
153*0b57cec5SDimitry Andric     if (Per == EHPersonality::MSVC_Win64SEH)
154*0b57cec5SDimitry Andric       emitCSpecificHandlerTable(MF);
155*0b57cec5SDimitry Andric     else if (Per == EHPersonality::MSVC_X86SEH)
156*0b57cec5SDimitry Andric       emitExceptHandlerTable(MF);
157*0b57cec5SDimitry Andric     else if (Per == EHPersonality::MSVC_CXX)
158*0b57cec5SDimitry Andric       emitCXXFrameHandler3Table(MF);
159*0b57cec5SDimitry Andric     else if (Per == EHPersonality::CoreCLR)
160*0b57cec5SDimitry Andric       emitCLRExceptionTable(MF);
161*0b57cec5SDimitry Andric     else
162*0b57cec5SDimitry Andric       emitExceptionTable();
163*0b57cec5SDimitry Andric 
164*0b57cec5SDimitry Andric     Asm->OutStreamer->PopSection();
165*0b57cec5SDimitry Andric   }
166*0b57cec5SDimitry Andric }
167*0b57cec5SDimitry Andric 
168*0b57cec5SDimitry Andric /// Retrieve the MCSymbol for a GlobalValue or MachineBasicBlock.
169*0b57cec5SDimitry Andric static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
170*0b57cec5SDimitry Andric                                    const MachineBasicBlock *MBB) {
171*0b57cec5SDimitry Andric   if (!MBB)
172*0b57cec5SDimitry Andric     return nullptr;
173*0b57cec5SDimitry Andric 
174*0b57cec5SDimitry Andric   assert(MBB->isEHFuncletEntry());
175*0b57cec5SDimitry Andric 
176*0b57cec5SDimitry Andric   // Give catches and cleanups a name based off of their parent function and
177*0b57cec5SDimitry Andric   // their funclet entry block's number.
178*0b57cec5SDimitry Andric   const MachineFunction *MF = MBB->getParent();
179*0b57cec5SDimitry Andric   const Function &F = MF->getFunction();
180*0b57cec5SDimitry Andric   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
181*0b57cec5SDimitry Andric   MCContext &Ctx = MF->getContext();
182*0b57cec5SDimitry Andric   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
183*0b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
184*0b57cec5SDimitry Andric                                Twine(MBB->getNumber()) + "@?0?" +
185*0b57cec5SDimitry Andric                                FuncLinkageName + "@4HA");
186*0b57cec5SDimitry Andric }
187*0b57cec5SDimitry Andric 
188*0b57cec5SDimitry Andric void WinException::beginFunclet(const MachineBasicBlock &MBB,
189*0b57cec5SDimitry Andric                                 MCSymbol *Sym) {
190*0b57cec5SDimitry Andric   CurrentFuncletEntry = &MBB;
191*0b57cec5SDimitry Andric 
192*0b57cec5SDimitry Andric   const Function &F = Asm->MF->getFunction();
193*0b57cec5SDimitry Andric   // If a symbol was not provided for the funclet, invent one.
194*0b57cec5SDimitry Andric   if (!Sym) {
195*0b57cec5SDimitry Andric     Sym = getMCSymbolForMBB(Asm, &MBB);
196*0b57cec5SDimitry Andric 
197*0b57cec5SDimitry Andric     // Describe our funclet symbol as a function with internal linkage.
198*0b57cec5SDimitry Andric     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
199*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
200*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
201*0b57cec5SDimitry Andric                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
202*0b57cec5SDimitry Andric     Asm->OutStreamer->EndCOFFSymbolDef();
203*0b57cec5SDimitry Andric 
204*0b57cec5SDimitry Andric     // We want our funclet's entry point to be aligned such that no nops will be
205*0b57cec5SDimitry Andric     // present after the label.
206*0b57cec5SDimitry Andric     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
207*0b57cec5SDimitry Andric                        &F);
208*0b57cec5SDimitry Andric 
209*0b57cec5SDimitry Andric     // Now that we've emitted the alignment directive, point at our funclet.
210*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitLabel(Sym);
211*0b57cec5SDimitry Andric   }
212*0b57cec5SDimitry Andric 
213*0b57cec5SDimitry Andric   // Mark 'Sym' as starting our funclet.
214*0b57cec5SDimitry Andric   if (shouldEmitMoves || shouldEmitPersonality) {
215*0b57cec5SDimitry Andric     CurrentFuncletTextSection = Asm->OutStreamer->getCurrentSectionOnly();
216*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
217*0b57cec5SDimitry Andric   }
218*0b57cec5SDimitry Andric 
219*0b57cec5SDimitry Andric   if (shouldEmitPersonality) {
220*0b57cec5SDimitry Andric     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
221*0b57cec5SDimitry Andric     const Function *PerFn = nullptr;
222*0b57cec5SDimitry Andric 
223*0b57cec5SDimitry Andric     // Determine which personality routine we are using for this funclet.
224*0b57cec5SDimitry Andric     if (F.hasPersonalityFn())
225*0b57cec5SDimitry Andric       PerFn = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
226*0b57cec5SDimitry Andric     const MCSymbol *PersHandlerSym =
227*0b57cec5SDimitry Andric         TLOF.getCFIPersonalitySymbol(PerFn, Asm->TM, MMI);
228*0b57cec5SDimitry Andric 
229*0b57cec5SDimitry Andric     // Do not emit a .seh_handler directives for cleanup funclets.
230*0b57cec5SDimitry Andric     // FIXME: This means cleanup funclets cannot handle exceptions. Given that
231*0b57cec5SDimitry Andric     // Clang doesn't produce EH constructs inside cleanup funclets and LLVM's
232*0b57cec5SDimitry Andric     // inliner doesn't allow inlining them, this isn't a major problem in
233*0b57cec5SDimitry Andric     // practice.
234*0b57cec5SDimitry Andric     if (!CurrentFuncletEntry->isCleanupFuncletEntry())
235*0b57cec5SDimitry Andric       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
236*0b57cec5SDimitry Andric   }
237*0b57cec5SDimitry Andric }
238*0b57cec5SDimitry Andric 
239*0b57cec5SDimitry Andric void WinException::endFunclet() {
240*0b57cec5SDimitry Andric   if (isAArch64 && CurrentFuncletEntry &&
241*0b57cec5SDimitry Andric       (shouldEmitMoves || shouldEmitPersonality)) {
242*0b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
243*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIFuncletOrFuncEnd();
244*0b57cec5SDimitry Andric   }
245*0b57cec5SDimitry Andric   endFuncletImpl();
246*0b57cec5SDimitry Andric }
247*0b57cec5SDimitry Andric 
248*0b57cec5SDimitry Andric void WinException::endFuncletImpl() {
249*0b57cec5SDimitry Andric   // No funclet to process?  Great, we have nothing to do.
250*0b57cec5SDimitry Andric   if (!CurrentFuncletEntry)
251*0b57cec5SDimitry Andric     return;
252*0b57cec5SDimitry Andric 
253*0b57cec5SDimitry Andric   const MachineFunction *MF = Asm->MF;
254*0b57cec5SDimitry Andric   if (shouldEmitMoves || shouldEmitPersonality) {
255*0b57cec5SDimitry Andric     const Function &F = MF->getFunction();
256*0b57cec5SDimitry Andric     EHPersonality Per = EHPersonality::Unknown;
257*0b57cec5SDimitry Andric     if (F.hasPersonalityFn())
258*0b57cec5SDimitry Andric       Per = classifyEHPersonality(F.getPersonalityFn()->stripPointerCasts());
259*0b57cec5SDimitry Andric 
260*0b57cec5SDimitry Andric     // On funclet exit, we emit a fake "function" end marker, so that the call
261*0b57cec5SDimitry Andric     // to EmitWinEHHandlerData below can calculate the size of the funclet or
262*0b57cec5SDimitry Andric     // function.
263*0b57cec5SDimitry Andric     if (isAArch64) {
264*0b57cec5SDimitry Andric       MCSection *XData = Asm->OutStreamer->getAssociatedXDataSection(
265*0b57cec5SDimitry Andric           Asm->OutStreamer->getCurrentSectionOnly());
266*0b57cec5SDimitry Andric       Asm->OutStreamer->SwitchSection(XData);
267*0b57cec5SDimitry Andric     }
268*0b57cec5SDimitry Andric 
269*0b57cec5SDimitry Andric     // Emit an UNWIND_INFO struct describing the prologue.
270*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinEHHandlerData();
271*0b57cec5SDimitry Andric 
272*0b57cec5SDimitry Andric     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
273*0b57cec5SDimitry Andric         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
274*0b57cec5SDimitry Andric       // If this is a C++ catch funclet (or the parent function),
275*0b57cec5SDimitry Andric       // emit a reference to the LSDA for the parent function.
276*0b57cec5SDimitry Andric       StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
277*0b57cec5SDimitry Andric       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
278*0b57cec5SDimitry Andric           Twine("$cppxdata$", FuncLinkageName));
279*0b57cec5SDimitry Andric       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
280*0b57cec5SDimitry Andric     } else if (Per == EHPersonality::MSVC_Win64SEH && MF->hasEHFunclets() &&
281*0b57cec5SDimitry Andric                !CurrentFuncletEntry->isEHFuncletEntry()) {
282*0b57cec5SDimitry Andric       // If this is the parent function in Win64 SEH, emit the LSDA immediately
283*0b57cec5SDimitry Andric       // following .seh_handlerdata.
284*0b57cec5SDimitry Andric       emitCSpecificHandlerTable(MF);
285*0b57cec5SDimitry Andric     }
286*0b57cec5SDimitry Andric 
287*0b57cec5SDimitry Andric     // Switch back to the funclet start .text section now that we are done
288*0b57cec5SDimitry Andric     // writing to .xdata, and emit an .seh_endproc directive to mark the end of
289*0b57cec5SDimitry Andric     // the function.
290*0b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(CurrentFuncletTextSection);
291*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitWinCFIEndProc();
292*0b57cec5SDimitry Andric   }
293*0b57cec5SDimitry Andric 
294*0b57cec5SDimitry Andric   // Let's make sure we don't try to end the same funclet twice.
295*0b57cec5SDimitry Andric   CurrentFuncletEntry = nullptr;
296*0b57cec5SDimitry Andric }
297*0b57cec5SDimitry Andric 
298*0b57cec5SDimitry Andric const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
299*0b57cec5SDimitry Andric   if (!Value)
300*0b57cec5SDimitry Andric     return MCConstantExpr::create(0, Asm->OutContext);
301*0b57cec5SDimitry Andric   return MCSymbolRefExpr::create(Value, useImageRel32
302*0b57cec5SDimitry Andric                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
303*0b57cec5SDimitry Andric                                             : MCSymbolRefExpr::VK_None,
304*0b57cec5SDimitry Andric                                  Asm->OutContext);
305*0b57cec5SDimitry Andric }
306*0b57cec5SDimitry Andric 
307*0b57cec5SDimitry Andric const MCExpr *WinException::create32bitRef(const GlobalValue *GV) {
308*0b57cec5SDimitry Andric   if (!GV)
309*0b57cec5SDimitry Andric     return MCConstantExpr::create(0, Asm->OutContext);
310*0b57cec5SDimitry Andric   return create32bitRef(Asm->getSymbol(GV));
311*0b57cec5SDimitry Andric }
312*0b57cec5SDimitry Andric 
313*0b57cec5SDimitry Andric const MCExpr *WinException::getLabel(const MCSymbol *Label) {
314*0b57cec5SDimitry Andric   if (isAArch64)
315*0b57cec5SDimitry Andric     return MCSymbolRefExpr::create(Label, MCSymbolRefExpr::VK_COFF_IMGREL32,
316*0b57cec5SDimitry Andric                                    Asm->OutContext);
317*0b57cec5SDimitry Andric   return MCBinaryExpr::createAdd(create32bitRef(Label),
318*0b57cec5SDimitry Andric                                  MCConstantExpr::create(1, Asm->OutContext),
319*0b57cec5SDimitry Andric                                  Asm->OutContext);
320*0b57cec5SDimitry Andric }
321*0b57cec5SDimitry Andric 
322*0b57cec5SDimitry Andric const MCExpr *WinException::getOffset(const MCSymbol *OffsetOf,
323*0b57cec5SDimitry Andric                                       const MCSymbol *OffsetFrom) {
324*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
325*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(OffsetOf, Asm->OutContext),
326*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(OffsetFrom, Asm->OutContext), Asm->OutContext);
327*0b57cec5SDimitry Andric }
328*0b57cec5SDimitry Andric 
329*0b57cec5SDimitry Andric const MCExpr *WinException::getOffsetPlusOne(const MCSymbol *OffsetOf,
330*0b57cec5SDimitry Andric                                              const MCSymbol *OffsetFrom) {
331*0b57cec5SDimitry Andric   return MCBinaryExpr::createAdd(getOffset(OffsetOf, OffsetFrom),
332*0b57cec5SDimitry Andric                                  MCConstantExpr::create(1, Asm->OutContext),
333*0b57cec5SDimitry Andric                                  Asm->OutContext);
334*0b57cec5SDimitry Andric }
335*0b57cec5SDimitry Andric 
336*0b57cec5SDimitry Andric int WinException::getFrameIndexOffset(int FrameIndex,
337*0b57cec5SDimitry Andric                                       const WinEHFuncInfo &FuncInfo) {
338*0b57cec5SDimitry Andric   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
339*0b57cec5SDimitry Andric   unsigned UnusedReg;
340*0b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI()) {
341*0b57cec5SDimitry Andric     int Offset =
342*0b57cec5SDimitry Andric         TFI.getFrameIndexReferencePreferSP(*Asm->MF, FrameIndex, UnusedReg,
343*0b57cec5SDimitry Andric                                            /*IgnoreSPUpdates*/ true);
344*0b57cec5SDimitry Andric     assert(UnusedReg ==
345*0b57cec5SDimitry Andric            Asm->MF->getSubtarget()
346*0b57cec5SDimitry Andric                .getTargetLowering()
347*0b57cec5SDimitry Andric                ->getStackPointerRegisterToSaveRestore());
348*0b57cec5SDimitry Andric     return Offset;
349*0b57cec5SDimitry Andric   }
350*0b57cec5SDimitry Andric 
351*0b57cec5SDimitry Andric   // For 32-bit, offsets should be relative to the end of the EH registration
352*0b57cec5SDimitry Andric   // node. For 64-bit, it's relative to SP at the end of the prologue.
353*0b57cec5SDimitry Andric   assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
354*0b57cec5SDimitry Andric   int Offset = TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
355*0b57cec5SDimitry Andric   Offset += FuncInfo.EHRegNodeEndOffset;
356*0b57cec5SDimitry Andric   return Offset;
357*0b57cec5SDimitry Andric }
358*0b57cec5SDimitry Andric 
359*0b57cec5SDimitry Andric namespace {
360*0b57cec5SDimitry Andric 
361*0b57cec5SDimitry Andric /// Top-level state used to represent unwind to caller
362*0b57cec5SDimitry Andric const int NullState = -1;
363*0b57cec5SDimitry Andric 
364*0b57cec5SDimitry Andric struct InvokeStateChange {
365*0b57cec5SDimitry Andric   /// EH Label immediately after the last invoke in the previous state, or
366*0b57cec5SDimitry Andric   /// nullptr if the previous state was the null state.
367*0b57cec5SDimitry Andric   const MCSymbol *PreviousEndLabel;
368*0b57cec5SDimitry Andric 
369*0b57cec5SDimitry Andric   /// EH label immediately before the first invoke in the new state, or nullptr
370*0b57cec5SDimitry Andric   /// if the new state is the null state.
371*0b57cec5SDimitry Andric   const MCSymbol *NewStartLabel;
372*0b57cec5SDimitry Andric 
373*0b57cec5SDimitry Andric   /// State of the invoke following NewStartLabel, or NullState to indicate
374*0b57cec5SDimitry Andric   /// the presence of calls which may unwind to caller.
375*0b57cec5SDimitry Andric   int NewState;
376*0b57cec5SDimitry Andric };
377*0b57cec5SDimitry Andric 
378*0b57cec5SDimitry Andric /// Iterator that reports all the invoke state changes in a range of machine
379*0b57cec5SDimitry Andric /// basic blocks.  Changes to the null state are reported whenever a call that
380*0b57cec5SDimitry Andric /// may unwind to caller is encountered.  The MBB range is expected to be an
381*0b57cec5SDimitry Andric /// entire function or funclet, and the start and end of the range are treated
382*0b57cec5SDimitry Andric /// as being in the NullState even if there's not an unwind-to-caller call
383*0b57cec5SDimitry Andric /// before the first invoke or after the last one (i.e., the first state change
384*0b57cec5SDimitry Andric /// reported is the first change to something other than NullState, and a
385*0b57cec5SDimitry Andric /// change back to NullState is always reported at the end of iteration).
386*0b57cec5SDimitry Andric class InvokeStateChangeIterator {
387*0b57cec5SDimitry Andric   InvokeStateChangeIterator(const WinEHFuncInfo &EHInfo,
388*0b57cec5SDimitry Andric                             MachineFunction::const_iterator MFI,
389*0b57cec5SDimitry Andric                             MachineFunction::const_iterator MFE,
390*0b57cec5SDimitry Andric                             MachineBasicBlock::const_iterator MBBI,
391*0b57cec5SDimitry Andric                             int BaseState)
392*0b57cec5SDimitry Andric       : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI), BaseState(BaseState) {
393*0b57cec5SDimitry Andric     LastStateChange.PreviousEndLabel = nullptr;
394*0b57cec5SDimitry Andric     LastStateChange.NewStartLabel = nullptr;
395*0b57cec5SDimitry Andric     LastStateChange.NewState = BaseState;
396*0b57cec5SDimitry Andric     scan();
397*0b57cec5SDimitry Andric   }
398*0b57cec5SDimitry Andric 
399*0b57cec5SDimitry Andric public:
400*0b57cec5SDimitry Andric   static iterator_range<InvokeStateChangeIterator>
401*0b57cec5SDimitry Andric   range(const WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
402*0b57cec5SDimitry Andric         MachineFunction::const_iterator End, int BaseState = NullState) {
403*0b57cec5SDimitry Andric     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
404*0b57cec5SDimitry Andric     // the end of the last block.
405*0b57cec5SDimitry Andric     assert(Begin != End);
406*0b57cec5SDimitry Andric     auto BlockBegin = Begin->begin();
407*0b57cec5SDimitry Andric     auto BlockEnd = std::prev(End)->end();
408*0b57cec5SDimitry Andric     return make_range(
409*0b57cec5SDimitry Andric         InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin, BaseState),
410*0b57cec5SDimitry Andric         InvokeStateChangeIterator(EHInfo, End, End, BlockEnd, BaseState));
411*0b57cec5SDimitry Andric   }
412*0b57cec5SDimitry Andric 
413*0b57cec5SDimitry Andric   // Iterator methods.
414*0b57cec5SDimitry Andric   bool operator==(const InvokeStateChangeIterator &O) const {
415*0b57cec5SDimitry Andric     assert(BaseState == O.BaseState);
416*0b57cec5SDimitry Andric     // Must be visiting same block.
417*0b57cec5SDimitry Andric     if (MFI != O.MFI)
418*0b57cec5SDimitry Andric       return false;
419*0b57cec5SDimitry Andric     // Must be visiting same isntr.
420*0b57cec5SDimitry Andric     if (MBBI != O.MBBI)
421*0b57cec5SDimitry Andric       return false;
422*0b57cec5SDimitry Andric     // At end of block/instr iteration, we can still have two distinct states:
423*0b57cec5SDimitry Andric     // one to report the final EndLabel, and another indicating the end of the
424*0b57cec5SDimitry Andric     // state change iteration.  Check for CurrentEndLabel equality to
425*0b57cec5SDimitry Andric     // distinguish these.
426*0b57cec5SDimitry Andric     return CurrentEndLabel == O.CurrentEndLabel;
427*0b57cec5SDimitry Andric   }
428*0b57cec5SDimitry Andric 
429*0b57cec5SDimitry Andric   bool operator!=(const InvokeStateChangeIterator &O) const {
430*0b57cec5SDimitry Andric     return !operator==(O);
431*0b57cec5SDimitry Andric   }
432*0b57cec5SDimitry Andric   InvokeStateChange &operator*() { return LastStateChange; }
433*0b57cec5SDimitry Andric   InvokeStateChange *operator->() { return &LastStateChange; }
434*0b57cec5SDimitry Andric   InvokeStateChangeIterator &operator++() { return scan(); }
435*0b57cec5SDimitry Andric 
436*0b57cec5SDimitry Andric private:
437*0b57cec5SDimitry Andric   InvokeStateChangeIterator &scan();
438*0b57cec5SDimitry Andric 
439*0b57cec5SDimitry Andric   const WinEHFuncInfo &EHInfo;
440*0b57cec5SDimitry Andric   const MCSymbol *CurrentEndLabel = nullptr;
441*0b57cec5SDimitry Andric   MachineFunction::const_iterator MFI;
442*0b57cec5SDimitry Andric   MachineFunction::const_iterator MFE;
443*0b57cec5SDimitry Andric   MachineBasicBlock::const_iterator MBBI;
444*0b57cec5SDimitry Andric   InvokeStateChange LastStateChange;
445*0b57cec5SDimitry Andric   bool VisitingInvoke = false;
446*0b57cec5SDimitry Andric   int BaseState;
447*0b57cec5SDimitry Andric };
448*0b57cec5SDimitry Andric 
449*0b57cec5SDimitry Andric } // end anonymous namespace
450*0b57cec5SDimitry Andric 
451*0b57cec5SDimitry Andric InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
452*0b57cec5SDimitry Andric   bool IsNewBlock = false;
453*0b57cec5SDimitry Andric   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
454*0b57cec5SDimitry Andric     if (IsNewBlock)
455*0b57cec5SDimitry Andric       MBBI = MFI->begin();
456*0b57cec5SDimitry Andric     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
457*0b57cec5SDimitry Andric       const MachineInstr &MI = *MBBI;
458*0b57cec5SDimitry Andric       if (!VisitingInvoke && LastStateChange.NewState != BaseState &&
459*0b57cec5SDimitry Andric           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
460*0b57cec5SDimitry Andric         // Indicate a change of state to the null state.  We don't have
461*0b57cec5SDimitry Andric         // start/end EH labels handy but the caller won't expect them for
462*0b57cec5SDimitry Andric         // null state regions.
463*0b57cec5SDimitry Andric         LastStateChange.PreviousEndLabel = CurrentEndLabel;
464*0b57cec5SDimitry Andric         LastStateChange.NewStartLabel = nullptr;
465*0b57cec5SDimitry Andric         LastStateChange.NewState = BaseState;
466*0b57cec5SDimitry Andric         CurrentEndLabel = nullptr;
467*0b57cec5SDimitry Andric         // Don't re-visit this instr on the next scan
468*0b57cec5SDimitry Andric         ++MBBI;
469*0b57cec5SDimitry Andric         return *this;
470*0b57cec5SDimitry Andric       }
471*0b57cec5SDimitry Andric 
472*0b57cec5SDimitry Andric       // All other state changes are at EH labels before/after invokes.
473*0b57cec5SDimitry Andric       if (!MI.isEHLabel())
474*0b57cec5SDimitry Andric         continue;
475*0b57cec5SDimitry Andric       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
476*0b57cec5SDimitry Andric       if (Label == CurrentEndLabel) {
477*0b57cec5SDimitry Andric         VisitingInvoke = false;
478*0b57cec5SDimitry Andric         continue;
479*0b57cec5SDimitry Andric       }
480*0b57cec5SDimitry Andric       auto InvokeMapIter = EHInfo.LabelToStateMap.find(Label);
481*0b57cec5SDimitry Andric       // Ignore EH labels that aren't the ones inserted before an invoke
482*0b57cec5SDimitry Andric       if (InvokeMapIter == EHInfo.LabelToStateMap.end())
483*0b57cec5SDimitry Andric         continue;
484*0b57cec5SDimitry Andric       auto &StateAndEnd = InvokeMapIter->second;
485*0b57cec5SDimitry Andric       int NewState = StateAndEnd.first;
486*0b57cec5SDimitry Andric       // Keep track of the fact that we're between EH start/end labels so
487*0b57cec5SDimitry Andric       // we know not to treat the inoke we'll see as unwinding to caller.
488*0b57cec5SDimitry Andric       VisitingInvoke = true;
489*0b57cec5SDimitry Andric       if (NewState == LastStateChange.NewState) {
490*0b57cec5SDimitry Andric         // The state isn't actually changing here.  Record the new end and
491*0b57cec5SDimitry Andric         // keep going.
492*0b57cec5SDimitry Andric         CurrentEndLabel = StateAndEnd.second;
493*0b57cec5SDimitry Andric         continue;
494*0b57cec5SDimitry Andric       }
495*0b57cec5SDimitry Andric       // Found a state change to report
496*0b57cec5SDimitry Andric       LastStateChange.PreviousEndLabel = CurrentEndLabel;
497*0b57cec5SDimitry Andric       LastStateChange.NewStartLabel = Label;
498*0b57cec5SDimitry Andric       LastStateChange.NewState = NewState;
499*0b57cec5SDimitry Andric       // Start keeping track of the new current end
500*0b57cec5SDimitry Andric       CurrentEndLabel = StateAndEnd.second;
501*0b57cec5SDimitry Andric       // Don't re-visit this instr on the next scan
502*0b57cec5SDimitry Andric       ++MBBI;
503*0b57cec5SDimitry Andric       return *this;
504*0b57cec5SDimitry Andric     }
505*0b57cec5SDimitry Andric   }
506*0b57cec5SDimitry Andric   // Iteration hit the end of the block range.
507*0b57cec5SDimitry Andric   if (LastStateChange.NewState != BaseState) {
508*0b57cec5SDimitry Andric     // Report the end of the last new state
509*0b57cec5SDimitry Andric     LastStateChange.PreviousEndLabel = CurrentEndLabel;
510*0b57cec5SDimitry Andric     LastStateChange.NewStartLabel = nullptr;
511*0b57cec5SDimitry Andric     LastStateChange.NewState = BaseState;
512*0b57cec5SDimitry Andric     // Leave CurrentEndLabel non-null to distinguish this state from end.
513*0b57cec5SDimitry Andric     assert(CurrentEndLabel != nullptr);
514*0b57cec5SDimitry Andric     return *this;
515*0b57cec5SDimitry Andric   }
516*0b57cec5SDimitry Andric   // We've reported all state changes and hit the end state.
517*0b57cec5SDimitry Andric   CurrentEndLabel = nullptr;
518*0b57cec5SDimitry Andric   return *this;
519*0b57cec5SDimitry Andric }
520*0b57cec5SDimitry Andric 
521*0b57cec5SDimitry Andric /// Emit the language-specific data that __C_specific_handler expects.  This
522*0b57cec5SDimitry Andric /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
523*0b57cec5SDimitry Andric /// up after faults with __try, __except, and __finally.  The typeinfo values
524*0b57cec5SDimitry Andric /// are not really RTTI data, but pointers to filter functions that return an
525*0b57cec5SDimitry Andric /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
526*0b57cec5SDimitry Andric /// blocks and other cleanups, the landing pad label is zero, and the filter
527*0b57cec5SDimitry Andric /// function is actually a cleanup handler with the same prototype.  A catch-all
528*0b57cec5SDimitry Andric /// entry is modeled with a null filter function field and a non-zero landing
529*0b57cec5SDimitry Andric /// pad label.
530*0b57cec5SDimitry Andric ///
531*0b57cec5SDimitry Andric /// Possible filter function return values:
532*0b57cec5SDimitry Andric ///   EXCEPTION_EXECUTE_HANDLER (1):
533*0b57cec5SDimitry Andric ///     Jump to the landing pad label after cleanups.
534*0b57cec5SDimitry Andric ///   EXCEPTION_CONTINUE_SEARCH (0):
535*0b57cec5SDimitry Andric ///     Continue searching this table or continue unwinding.
536*0b57cec5SDimitry Andric ///   EXCEPTION_CONTINUE_EXECUTION (-1):
537*0b57cec5SDimitry Andric ///     Resume execution at the trapping PC.
538*0b57cec5SDimitry Andric ///
539*0b57cec5SDimitry Andric /// Inferred table structure:
540*0b57cec5SDimitry Andric ///   struct Table {
541*0b57cec5SDimitry Andric ///     int NumEntries;
542*0b57cec5SDimitry Andric ///     struct Entry {
543*0b57cec5SDimitry Andric ///       imagerel32 LabelStart;
544*0b57cec5SDimitry Andric ///       imagerel32 LabelEnd;
545*0b57cec5SDimitry Andric ///       imagerel32 FilterOrFinally;  // One means catch-all.
546*0b57cec5SDimitry Andric ///       imagerel32 LabelLPad;        // Zero means __finally.
547*0b57cec5SDimitry Andric ///     } Entries[NumEntries];
548*0b57cec5SDimitry Andric ///   };
549*0b57cec5SDimitry Andric void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
550*0b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
551*0b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
552*0b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
553*0b57cec5SDimitry Andric 
554*0b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
555*0b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
556*0b57cec5SDimitry Andric     if (VerboseAsm)
557*0b57cec5SDimitry Andric       OS.AddComment(Comment);
558*0b57cec5SDimitry Andric   };
559*0b57cec5SDimitry Andric 
560*0b57cec5SDimitry Andric   if (!isAArch64) {
561*0b57cec5SDimitry Andric     // Emit a label assignment with the SEH frame offset so we can use it for
562*0b57cec5SDimitry Andric     // llvm.eh.recoverfp.
563*0b57cec5SDimitry Andric     StringRef FLinkageName =
564*0b57cec5SDimitry Andric         GlobalValue::dropLLVMManglingEscape(MF->getFunction().getName());
565*0b57cec5SDimitry Andric     MCSymbol *ParentFrameOffset =
566*0b57cec5SDimitry Andric         Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
567*0b57cec5SDimitry Andric     const MCExpr *MCOffset =
568*0b57cec5SDimitry Andric         MCConstantExpr::create(FuncInfo.SEHSetFrameOffset, Ctx);
569*0b57cec5SDimitry Andric     Asm->OutStreamer->EmitAssignment(ParentFrameOffset, MCOffset);
570*0b57cec5SDimitry Andric   }
571*0b57cec5SDimitry Andric 
572*0b57cec5SDimitry Andric   // Use the assembler to compute the number of table entries through label
573*0b57cec5SDimitry Andric   // difference and division.
574*0b57cec5SDimitry Andric   MCSymbol *TableBegin =
575*0b57cec5SDimitry Andric       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
576*0b57cec5SDimitry Andric   MCSymbol *TableEnd =
577*0b57cec5SDimitry Andric       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
578*0b57cec5SDimitry Andric   const MCExpr *LabelDiff = getOffset(TableEnd, TableBegin);
579*0b57cec5SDimitry Andric   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
580*0b57cec5SDimitry Andric   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
581*0b57cec5SDimitry Andric   AddComment("Number of call sites");
582*0b57cec5SDimitry Andric   OS.EmitValue(EntryCount, 4);
583*0b57cec5SDimitry Andric 
584*0b57cec5SDimitry Andric   OS.EmitLabel(TableBegin);
585*0b57cec5SDimitry Andric 
586*0b57cec5SDimitry Andric   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
587*0b57cec5SDimitry Andric   // models exceptions from invokes. LLVM also allows arbitrary reordering of
588*0b57cec5SDimitry Andric   // the code, so our tables end up looking a bit different. Rather than
589*0b57cec5SDimitry Andric   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
590*0b57cec5SDimitry Andric   // each range of invokes in the same state, we emit table entries for all
591*0b57cec5SDimitry Andric   // the actions that would be taken in that state. This means our tables are
592*0b57cec5SDimitry Andric   // slightly bigger, which is OK.
593*0b57cec5SDimitry Andric   const MCSymbol *LastStartLabel = nullptr;
594*0b57cec5SDimitry Andric   int LastEHState = -1;
595*0b57cec5SDimitry Andric   // Break out before we enter into a finally funclet.
596*0b57cec5SDimitry Andric   // FIXME: We need to emit separate EH tables for cleanups.
597*0b57cec5SDimitry Andric   MachineFunction::const_iterator End = MF->end();
598*0b57cec5SDimitry Andric   MachineFunction::const_iterator Stop = std::next(MF->begin());
599*0b57cec5SDimitry Andric   while (Stop != End && !Stop->isEHFuncletEntry())
600*0b57cec5SDimitry Andric     ++Stop;
601*0b57cec5SDimitry Andric   for (const auto &StateChange :
602*0b57cec5SDimitry Andric        InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
603*0b57cec5SDimitry Andric     // Emit all the actions for the state we just transitioned out of
604*0b57cec5SDimitry Andric     // if it was not the null state
605*0b57cec5SDimitry Andric     if (LastEHState != -1)
606*0b57cec5SDimitry Andric       emitSEHActionsForRange(FuncInfo, LastStartLabel,
607*0b57cec5SDimitry Andric                              StateChange.PreviousEndLabel, LastEHState);
608*0b57cec5SDimitry Andric     LastStartLabel = StateChange.NewStartLabel;
609*0b57cec5SDimitry Andric     LastEHState = StateChange.NewState;
610*0b57cec5SDimitry Andric   }
611*0b57cec5SDimitry Andric 
612*0b57cec5SDimitry Andric   OS.EmitLabel(TableEnd);
613*0b57cec5SDimitry Andric }
614*0b57cec5SDimitry Andric 
615*0b57cec5SDimitry Andric void WinException::emitSEHActionsForRange(const WinEHFuncInfo &FuncInfo,
616*0b57cec5SDimitry Andric                                           const MCSymbol *BeginLabel,
617*0b57cec5SDimitry Andric                                           const MCSymbol *EndLabel, int State) {
618*0b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
619*0b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
620*0b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
621*0b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
622*0b57cec5SDimitry Andric     if (VerboseAsm)
623*0b57cec5SDimitry Andric       OS.AddComment(Comment);
624*0b57cec5SDimitry Andric   };
625*0b57cec5SDimitry Andric 
626*0b57cec5SDimitry Andric   assert(BeginLabel && EndLabel);
627*0b57cec5SDimitry Andric   while (State != -1) {
628*0b57cec5SDimitry Andric     const SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
629*0b57cec5SDimitry Andric     const MCExpr *FilterOrFinally;
630*0b57cec5SDimitry Andric     const MCExpr *ExceptOrNull;
631*0b57cec5SDimitry Andric     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
632*0b57cec5SDimitry Andric     if (UME.IsFinally) {
633*0b57cec5SDimitry Andric       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
634*0b57cec5SDimitry Andric       ExceptOrNull = MCConstantExpr::create(0, Ctx);
635*0b57cec5SDimitry Andric     } else {
636*0b57cec5SDimitry Andric       // For an except, the filter can be 1 (catch-all) or a function
637*0b57cec5SDimitry Andric       // label.
638*0b57cec5SDimitry Andric       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
639*0b57cec5SDimitry Andric                                    : MCConstantExpr::create(1, Ctx);
640*0b57cec5SDimitry Andric       ExceptOrNull = create32bitRef(Handler->getSymbol());
641*0b57cec5SDimitry Andric     }
642*0b57cec5SDimitry Andric 
643*0b57cec5SDimitry Andric     AddComment("LabelStart");
644*0b57cec5SDimitry Andric     OS.EmitValue(getLabel(BeginLabel), 4);
645*0b57cec5SDimitry Andric     AddComment("LabelEnd");
646*0b57cec5SDimitry Andric     OS.EmitValue(getLabel(EndLabel), 4);
647*0b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "FinallyFunclet" : UME.Filter ? "FilterFunction"
648*0b57cec5SDimitry Andric                                                              : "CatchAll");
649*0b57cec5SDimitry Andric     OS.EmitValue(FilterOrFinally, 4);
650*0b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "Null" : "ExceptionHandler");
651*0b57cec5SDimitry Andric     OS.EmitValue(ExceptOrNull, 4);
652*0b57cec5SDimitry Andric 
653*0b57cec5SDimitry Andric     assert(UME.ToState < State && "states should decrease");
654*0b57cec5SDimitry Andric     State = UME.ToState;
655*0b57cec5SDimitry Andric   }
656*0b57cec5SDimitry Andric }
657*0b57cec5SDimitry Andric 
658*0b57cec5SDimitry Andric void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
659*0b57cec5SDimitry Andric   const Function &F = MF->getFunction();
660*0b57cec5SDimitry Andric   auto &OS = *Asm->OutStreamer;
661*0b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
662*0b57cec5SDimitry Andric 
663*0b57cec5SDimitry Andric   StringRef FuncLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
664*0b57cec5SDimitry Andric 
665*0b57cec5SDimitry Andric   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
666*0b57cec5SDimitry Andric   MCSymbol *FuncInfoXData = nullptr;
667*0b57cec5SDimitry Andric   if (shouldEmitPersonality) {
668*0b57cec5SDimitry Andric     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
669*0b57cec5SDimitry Andric     // IPs to state numbers.
670*0b57cec5SDimitry Andric     FuncInfoXData =
671*0b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
672*0b57cec5SDimitry Andric     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
673*0b57cec5SDimitry Andric   } else {
674*0b57cec5SDimitry Andric     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
675*0b57cec5SDimitry Andric   }
676*0b57cec5SDimitry Andric 
677*0b57cec5SDimitry Andric   int UnwindHelpOffset = 0;
678*0b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI())
679*0b57cec5SDimitry Andric     UnwindHelpOffset =
680*0b57cec5SDimitry Andric         getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx, FuncInfo);
681*0b57cec5SDimitry Andric 
682*0b57cec5SDimitry Andric   MCSymbol *UnwindMapXData = nullptr;
683*0b57cec5SDimitry Andric   MCSymbol *TryBlockMapXData = nullptr;
684*0b57cec5SDimitry Andric   MCSymbol *IPToStateXData = nullptr;
685*0b57cec5SDimitry Andric   if (!FuncInfo.CxxUnwindMap.empty())
686*0b57cec5SDimitry Andric     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
687*0b57cec5SDimitry Andric         Twine("$stateUnwindMap$", FuncLinkageName));
688*0b57cec5SDimitry Andric   if (!FuncInfo.TryBlockMap.empty())
689*0b57cec5SDimitry Andric     TryBlockMapXData =
690*0b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
691*0b57cec5SDimitry Andric   if (!IPToStateTable.empty())
692*0b57cec5SDimitry Andric     IPToStateXData =
693*0b57cec5SDimitry Andric         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
694*0b57cec5SDimitry Andric 
695*0b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
696*0b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
697*0b57cec5SDimitry Andric     if (VerboseAsm)
698*0b57cec5SDimitry Andric       OS.AddComment(Comment);
699*0b57cec5SDimitry Andric   };
700*0b57cec5SDimitry Andric 
701*0b57cec5SDimitry Andric   // FuncInfo {
702*0b57cec5SDimitry Andric   //   uint32_t           MagicNumber
703*0b57cec5SDimitry Andric   //   int32_t            MaxState;
704*0b57cec5SDimitry Andric   //   UnwindMapEntry    *UnwindMap;
705*0b57cec5SDimitry Andric   //   uint32_t           NumTryBlocks;
706*0b57cec5SDimitry Andric   //   TryBlockMapEntry  *TryBlockMap;
707*0b57cec5SDimitry Andric   //   uint32_t           IPMapEntries; // always 0 for x86
708*0b57cec5SDimitry Andric   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
709*0b57cec5SDimitry Andric   //   uint32_t           UnwindHelp;   // non-x86 only
710*0b57cec5SDimitry Andric   //   ESTypeList        *ESTypeList;
711*0b57cec5SDimitry Andric   //   int32_t            EHFlags;
712*0b57cec5SDimitry Andric   // }
713*0b57cec5SDimitry Andric   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
714*0b57cec5SDimitry Andric   // EHFlags & 2 -> ???
715*0b57cec5SDimitry Andric   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
716*0b57cec5SDimitry Andric   OS.EmitValueToAlignment(4);
717*0b57cec5SDimitry Andric   OS.EmitLabel(FuncInfoXData);
718*0b57cec5SDimitry Andric 
719*0b57cec5SDimitry Andric   AddComment("MagicNumber");
720*0b57cec5SDimitry Andric   OS.EmitIntValue(0x19930522, 4);
721*0b57cec5SDimitry Andric 
722*0b57cec5SDimitry Andric   AddComment("MaxState");
723*0b57cec5SDimitry Andric   OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);
724*0b57cec5SDimitry Andric 
725*0b57cec5SDimitry Andric   AddComment("UnwindMap");
726*0b57cec5SDimitry Andric   OS.EmitValue(create32bitRef(UnwindMapXData), 4);
727*0b57cec5SDimitry Andric 
728*0b57cec5SDimitry Andric   AddComment("NumTryBlocks");
729*0b57cec5SDimitry Andric   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);
730*0b57cec5SDimitry Andric 
731*0b57cec5SDimitry Andric   AddComment("TryBlockMap");
732*0b57cec5SDimitry Andric   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);
733*0b57cec5SDimitry Andric 
734*0b57cec5SDimitry Andric   AddComment("IPMapEntries");
735*0b57cec5SDimitry Andric   OS.EmitIntValue(IPToStateTable.size(), 4);
736*0b57cec5SDimitry Andric 
737*0b57cec5SDimitry Andric   AddComment("IPToStateXData");
738*0b57cec5SDimitry Andric   OS.EmitValue(create32bitRef(IPToStateXData), 4);
739*0b57cec5SDimitry Andric 
740*0b57cec5SDimitry Andric   if (Asm->MAI->usesWindowsCFI()) {
741*0b57cec5SDimitry Andric     AddComment("UnwindHelp");
742*0b57cec5SDimitry Andric     OS.EmitIntValue(UnwindHelpOffset, 4);
743*0b57cec5SDimitry Andric   }
744*0b57cec5SDimitry Andric 
745*0b57cec5SDimitry Andric   AddComment("ESTypeList");
746*0b57cec5SDimitry Andric   OS.EmitIntValue(0, 4);
747*0b57cec5SDimitry Andric 
748*0b57cec5SDimitry Andric   AddComment("EHFlags");
749*0b57cec5SDimitry Andric   OS.EmitIntValue(1, 4);
750*0b57cec5SDimitry Andric 
751*0b57cec5SDimitry Andric   // UnwindMapEntry {
752*0b57cec5SDimitry Andric   //   int32_t ToState;
753*0b57cec5SDimitry Andric   //   void  (*Action)();
754*0b57cec5SDimitry Andric   // };
755*0b57cec5SDimitry Andric   if (UnwindMapXData) {
756*0b57cec5SDimitry Andric     OS.EmitLabel(UnwindMapXData);
757*0b57cec5SDimitry Andric     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
758*0b57cec5SDimitry Andric       MCSymbol *CleanupSym =
759*0b57cec5SDimitry Andric           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
760*0b57cec5SDimitry Andric       AddComment("ToState");
761*0b57cec5SDimitry Andric       OS.EmitIntValue(UME.ToState, 4);
762*0b57cec5SDimitry Andric 
763*0b57cec5SDimitry Andric       AddComment("Action");
764*0b57cec5SDimitry Andric       OS.EmitValue(create32bitRef(CleanupSym), 4);
765*0b57cec5SDimitry Andric     }
766*0b57cec5SDimitry Andric   }
767*0b57cec5SDimitry Andric 
768*0b57cec5SDimitry Andric   // TryBlockMap {
769*0b57cec5SDimitry Andric   //   int32_t      TryLow;
770*0b57cec5SDimitry Andric   //   int32_t      TryHigh;
771*0b57cec5SDimitry Andric   //   int32_t      CatchHigh;
772*0b57cec5SDimitry Andric   //   int32_t      NumCatches;
773*0b57cec5SDimitry Andric   //   HandlerType *HandlerArray;
774*0b57cec5SDimitry Andric   // };
775*0b57cec5SDimitry Andric   if (TryBlockMapXData) {
776*0b57cec5SDimitry Andric     OS.EmitLabel(TryBlockMapXData);
777*0b57cec5SDimitry Andric     SmallVector<MCSymbol *, 1> HandlerMaps;
778*0b57cec5SDimitry Andric     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
779*0b57cec5SDimitry Andric       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
780*0b57cec5SDimitry Andric 
781*0b57cec5SDimitry Andric       MCSymbol *HandlerMapXData = nullptr;
782*0b57cec5SDimitry Andric       if (!TBME.HandlerArray.empty())
783*0b57cec5SDimitry Andric         HandlerMapXData =
784*0b57cec5SDimitry Andric             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
785*0b57cec5SDimitry Andric                                                   .concat(Twine(I))
786*0b57cec5SDimitry Andric                                                   .concat("$")
787*0b57cec5SDimitry Andric                                                   .concat(FuncLinkageName));
788*0b57cec5SDimitry Andric       HandlerMaps.push_back(HandlerMapXData);
789*0b57cec5SDimitry Andric 
790*0b57cec5SDimitry Andric       // TBMEs should form intervals.
791*0b57cec5SDimitry Andric       assert(0 <= TBME.TryLow && "bad trymap interval");
792*0b57cec5SDimitry Andric       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
793*0b57cec5SDimitry Andric       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
794*0b57cec5SDimitry Andric       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
795*0b57cec5SDimitry Andric              "bad trymap interval");
796*0b57cec5SDimitry Andric 
797*0b57cec5SDimitry Andric       AddComment("TryLow");
798*0b57cec5SDimitry Andric       OS.EmitIntValue(TBME.TryLow, 4);
799*0b57cec5SDimitry Andric 
800*0b57cec5SDimitry Andric       AddComment("TryHigh");
801*0b57cec5SDimitry Andric       OS.EmitIntValue(TBME.TryHigh, 4);
802*0b57cec5SDimitry Andric 
803*0b57cec5SDimitry Andric       AddComment("CatchHigh");
804*0b57cec5SDimitry Andric       OS.EmitIntValue(TBME.CatchHigh, 4);
805*0b57cec5SDimitry Andric 
806*0b57cec5SDimitry Andric       AddComment("NumCatches");
807*0b57cec5SDimitry Andric       OS.EmitIntValue(TBME.HandlerArray.size(), 4);
808*0b57cec5SDimitry Andric 
809*0b57cec5SDimitry Andric       AddComment("HandlerArray");
810*0b57cec5SDimitry Andric       OS.EmitValue(create32bitRef(HandlerMapXData), 4);
811*0b57cec5SDimitry Andric     }
812*0b57cec5SDimitry Andric 
813*0b57cec5SDimitry Andric     // All funclets use the same parent frame offset currently.
814*0b57cec5SDimitry Andric     unsigned ParentFrameOffset = 0;
815*0b57cec5SDimitry Andric     if (shouldEmitPersonality) {
816*0b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
817*0b57cec5SDimitry Andric       ParentFrameOffset = TFI->getWinEHParentFrameOffset(*MF);
818*0b57cec5SDimitry Andric     }
819*0b57cec5SDimitry Andric 
820*0b57cec5SDimitry Andric     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
821*0b57cec5SDimitry Andric       const WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
822*0b57cec5SDimitry Andric       MCSymbol *HandlerMapXData = HandlerMaps[I];
823*0b57cec5SDimitry Andric       if (!HandlerMapXData)
824*0b57cec5SDimitry Andric         continue;
825*0b57cec5SDimitry Andric       // HandlerType {
826*0b57cec5SDimitry Andric       //   int32_t         Adjectives;
827*0b57cec5SDimitry Andric       //   TypeDescriptor *Type;
828*0b57cec5SDimitry Andric       //   int32_t         CatchObjOffset;
829*0b57cec5SDimitry Andric       //   void          (*Handler)();
830*0b57cec5SDimitry Andric       //   int32_t         ParentFrameOffset; // x64 and AArch64 only
831*0b57cec5SDimitry Andric       // };
832*0b57cec5SDimitry Andric       OS.EmitLabel(HandlerMapXData);
833*0b57cec5SDimitry Andric       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
834*0b57cec5SDimitry Andric         // Get the frame escape label with the offset of the catch object. If
835*0b57cec5SDimitry Andric         // the index is INT_MAX, then there is no catch object, and we should
836*0b57cec5SDimitry Andric         // emit an offset of zero, indicating that no copy will occur.
837*0b57cec5SDimitry Andric         const MCExpr *FrameAllocOffsetRef = nullptr;
838*0b57cec5SDimitry Andric         if (HT.CatchObj.FrameIndex != INT_MAX) {
839*0b57cec5SDimitry Andric           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex, FuncInfo);
840*0b57cec5SDimitry Andric           assert(Offset != 0 && "Illegal offset for catch object!");
841*0b57cec5SDimitry Andric           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
842*0b57cec5SDimitry Andric         } else {
843*0b57cec5SDimitry Andric           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
844*0b57cec5SDimitry Andric         }
845*0b57cec5SDimitry Andric 
846*0b57cec5SDimitry Andric         MCSymbol *HandlerSym =
847*0b57cec5SDimitry Andric             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
848*0b57cec5SDimitry Andric 
849*0b57cec5SDimitry Andric         AddComment("Adjectives");
850*0b57cec5SDimitry Andric         OS.EmitIntValue(HT.Adjectives, 4);
851*0b57cec5SDimitry Andric 
852*0b57cec5SDimitry Andric         AddComment("Type");
853*0b57cec5SDimitry Andric         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4);
854*0b57cec5SDimitry Andric 
855*0b57cec5SDimitry Andric         AddComment("CatchObjOffset");
856*0b57cec5SDimitry Andric         OS.EmitValue(FrameAllocOffsetRef, 4);
857*0b57cec5SDimitry Andric 
858*0b57cec5SDimitry Andric         AddComment("Handler");
859*0b57cec5SDimitry Andric         OS.EmitValue(create32bitRef(HandlerSym), 4);
860*0b57cec5SDimitry Andric 
861*0b57cec5SDimitry Andric         if (shouldEmitPersonality) {
862*0b57cec5SDimitry Andric           AddComment("ParentFrameOffset");
863*0b57cec5SDimitry Andric           OS.EmitIntValue(ParentFrameOffset, 4);
864*0b57cec5SDimitry Andric         }
865*0b57cec5SDimitry Andric       }
866*0b57cec5SDimitry Andric     }
867*0b57cec5SDimitry Andric   }
868*0b57cec5SDimitry Andric 
869*0b57cec5SDimitry Andric   // IPToStateMapEntry {
870*0b57cec5SDimitry Andric   //   void   *IP;
871*0b57cec5SDimitry Andric   //   int32_t State;
872*0b57cec5SDimitry Andric   // };
873*0b57cec5SDimitry Andric   if (IPToStateXData) {
874*0b57cec5SDimitry Andric     OS.EmitLabel(IPToStateXData);
875*0b57cec5SDimitry Andric     for (auto &IPStatePair : IPToStateTable) {
876*0b57cec5SDimitry Andric       AddComment("IP");
877*0b57cec5SDimitry Andric       OS.EmitValue(IPStatePair.first, 4);
878*0b57cec5SDimitry Andric       AddComment("ToState");
879*0b57cec5SDimitry Andric       OS.EmitIntValue(IPStatePair.second, 4);
880*0b57cec5SDimitry Andric     }
881*0b57cec5SDimitry Andric   }
882*0b57cec5SDimitry Andric }
883*0b57cec5SDimitry Andric 
884*0b57cec5SDimitry Andric void WinException::computeIP2StateTable(
885*0b57cec5SDimitry Andric     const MachineFunction *MF, const WinEHFuncInfo &FuncInfo,
886*0b57cec5SDimitry Andric     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
887*0b57cec5SDimitry Andric 
888*0b57cec5SDimitry Andric   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
889*0b57cec5SDimitry Andric                                        FuncletEnd = MF->begin(),
890*0b57cec5SDimitry Andric                                        End = MF->end();
891*0b57cec5SDimitry Andric        FuncletStart != End; FuncletStart = FuncletEnd) {
892*0b57cec5SDimitry Andric     // Find the end of the funclet
893*0b57cec5SDimitry Andric     while (++FuncletEnd != End) {
894*0b57cec5SDimitry Andric       if (FuncletEnd->isEHFuncletEntry()) {
895*0b57cec5SDimitry Andric         break;
896*0b57cec5SDimitry Andric       }
897*0b57cec5SDimitry Andric     }
898*0b57cec5SDimitry Andric 
899*0b57cec5SDimitry Andric     // Don't emit ip2state entries for cleanup funclets. Any interesting
900*0b57cec5SDimitry Andric     // exceptional actions in cleanups must be handled in a separate IR
901*0b57cec5SDimitry Andric     // function.
902*0b57cec5SDimitry Andric     if (FuncletStart->isCleanupFuncletEntry())
903*0b57cec5SDimitry Andric       continue;
904*0b57cec5SDimitry Andric 
905*0b57cec5SDimitry Andric     MCSymbol *StartLabel;
906*0b57cec5SDimitry Andric     int BaseState;
907*0b57cec5SDimitry Andric     if (FuncletStart == MF->begin()) {
908*0b57cec5SDimitry Andric       BaseState = NullState;
909*0b57cec5SDimitry Andric       StartLabel = Asm->getFunctionBegin();
910*0b57cec5SDimitry Andric     } else {
911*0b57cec5SDimitry Andric       auto *FuncletPad =
912*0b57cec5SDimitry Andric           cast<FuncletPadInst>(FuncletStart->getBasicBlock()->getFirstNonPHI());
913*0b57cec5SDimitry Andric       assert(FuncInfo.FuncletBaseStateMap.count(FuncletPad) != 0);
914*0b57cec5SDimitry Andric       BaseState = FuncInfo.FuncletBaseStateMap.find(FuncletPad)->second;
915*0b57cec5SDimitry Andric       StartLabel = getMCSymbolForMBB(Asm, &*FuncletStart);
916*0b57cec5SDimitry Andric     }
917*0b57cec5SDimitry Andric     assert(StartLabel && "need local function start label");
918*0b57cec5SDimitry Andric     IPToStateTable.push_back(
919*0b57cec5SDimitry Andric         std::make_pair(create32bitRef(StartLabel), BaseState));
920*0b57cec5SDimitry Andric 
921*0b57cec5SDimitry Andric     for (const auto &StateChange : InvokeStateChangeIterator::range(
922*0b57cec5SDimitry Andric              FuncInfo, FuncletStart, FuncletEnd, BaseState)) {
923*0b57cec5SDimitry Andric       // Compute the label to report as the start of this entry; use the EH
924*0b57cec5SDimitry Andric       // start label for the invoke if we have one, otherwise (this is a call
925*0b57cec5SDimitry Andric       // which may unwind to our caller and does not have an EH start label, so)
926*0b57cec5SDimitry Andric       // use the previous end label.
927*0b57cec5SDimitry Andric       const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
928*0b57cec5SDimitry Andric       if (!ChangeLabel)
929*0b57cec5SDimitry Andric         ChangeLabel = StateChange.PreviousEndLabel;
930*0b57cec5SDimitry Andric       // Emit an entry indicating that PCs after 'Label' have this EH state.
931*0b57cec5SDimitry Andric       IPToStateTable.push_back(
932*0b57cec5SDimitry Andric           std::make_pair(getLabel(ChangeLabel), StateChange.NewState));
933*0b57cec5SDimitry Andric       // FIXME: assert that NewState is between CatchLow and CatchHigh.
934*0b57cec5SDimitry Andric     }
935*0b57cec5SDimitry Andric   }
936*0b57cec5SDimitry Andric }
937*0b57cec5SDimitry Andric 
938*0b57cec5SDimitry Andric void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
939*0b57cec5SDimitry Andric                                                  StringRef FLinkageName) {
940*0b57cec5SDimitry Andric   // Outlined helpers called by the EH runtime need to know the offset of the EH
941*0b57cec5SDimitry Andric   // registration in order to recover the parent frame pointer. Now that we know
942*0b57cec5SDimitry Andric   // we've code generated the parent, we can emit the label assignment that
943*0b57cec5SDimitry Andric   // those helpers use to get the offset of the registration node.
944*0b57cec5SDimitry Andric 
945*0b57cec5SDimitry Andric   // Compute the parent frame offset. The EHRegNodeFrameIndex will be invalid if
946*0b57cec5SDimitry Andric   // after optimization all the invokes were eliminated. We still need to emit
947*0b57cec5SDimitry Andric   // the parent frame offset label, but it should be garbage and should never be
948*0b57cec5SDimitry Andric   // used.
949*0b57cec5SDimitry Andric   int64_t Offset = 0;
950*0b57cec5SDimitry Andric   int FI = FuncInfo.EHRegNodeFrameIndex;
951*0b57cec5SDimitry Andric   if (FI != INT_MAX) {
952*0b57cec5SDimitry Andric     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
953*0b57cec5SDimitry Andric     Offset = TFI->getNonLocalFrameIndexReference(*Asm->MF, FI);
954*0b57cec5SDimitry Andric   }
955*0b57cec5SDimitry Andric 
956*0b57cec5SDimitry Andric   MCContext &Ctx = Asm->OutContext;
957*0b57cec5SDimitry Andric   MCSymbol *ParentFrameOffset =
958*0b57cec5SDimitry Andric       Ctx.getOrCreateParentFrameOffsetSymbol(FLinkageName);
959*0b57cec5SDimitry Andric   Asm->OutStreamer->EmitAssignment(ParentFrameOffset,
960*0b57cec5SDimitry Andric                                    MCConstantExpr::create(Offset, Ctx));
961*0b57cec5SDimitry Andric }
962*0b57cec5SDimitry Andric 
963*0b57cec5SDimitry Andric /// Emit the language-specific data that _except_handler3 and 4 expect. This is
964*0b57cec5SDimitry Andric /// functionally equivalent to the __C_specific_handler table, except it is
965*0b57cec5SDimitry Andric /// indexed by state number instead of IP.
966*0b57cec5SDimitry Andric void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
967*0b57cec5SDimitry Andric   MCStreamer &OS = *Asm->OutStreamer;
968*0b57cec5SDimitry Andric   const Function &F = MF->getFunction();
969*0b57cec5SDimitry Andric   StringRef FLinkageName = GlobalValue::dropLLVMManglingEscape(F.getName());
970*0b57cec5SDimitry Andric 
971*0b57cec5SDimitry Andric   bool VerboseAsm = OS.isVerboseAsm();
972*0b57cec5SDimitry Andric   auto AddComment = [&](const Twine &Comment) {
973*0b57cec5SDimitry Andric     if (VerboseAsm)
974*0b57cec5SDimitry Andric       OS.AddComment(Comment);
975*0b57cec5SDimitry Andric   };
976*0b57cec5SDimitry Andric 
977*0b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
978*0b57cec5SDimitry Andric   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
979*0b57cec5SDimitry Andric 
980*0b57cec5SDimitry Andric   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
981*0b57cec5SDimitry Andric   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
982*0b57cec5SDimitry Andric   OS.EmitValueToAlignment(4);
983*0b57cec5SDimitry Andric   OS.EmitLabel(LSDALabel);
984*0b57cec5SDimitry Andric 
985*0b57cec5SDimitry Andric   const Function *Per =
986*0b57cec5SDimitry Andric       dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
987*0b57cec5SDimitry Andric   StringRef PerName = Per->getName();
988*0b57cec5SDimitry Andric   int BaseState = -1;
989*0b57cec5SDimitry Andric   if (PerName == "_except_handler4") {
990*0b57cec5SDimitry Andric     // The LSDA for _except_handler4 starts with this struct, followed by the
991*0b57cec5SDimitry Andric     // scope table:
992*0b57cec5SDimitry Andric     //
993*0b57cec5SDimitry Andric     // struct EH4ScopeTable {
994*0b57cec5SDimitry Andric     //   int32_t GSCookieOffset;
995*0b57cec5SDimitry Andric     //   int32_t GSCookieXOROffset;
996*0b57cec5SDimitry Andric     //   int32_t EHCookieOffset;
997*0b57cec5SDimitry Andric     //   int32_t EHCookieXOROffset;
998*0b57cec5SDimitry Andric     //   ScopeTableEntry ScopeRecord[];
999*0b57cec5SDimitry Andric     // };
1000*0b57cec5SDimitry Andric     //
1001*0b57cec5SDimitry Andric     // Offsets are %ebp relative.
1002*0b57cec5SDimitry Andric     //
1003*0b57cec5SDimitry Andric     // The GS cookie is present only if the function needs stack protection.
1004*0b57cec5SDimitry Andric     // GSCookieOffset = -2 means that GS cookie is not used.
1005*0b57cec5SDimitry Andric     //
1006*0b57cec5SDimitry Andric     // The EH cookie is always present.
1007*0b57cec5SDimitry Andric     //
1008*0b57cec5SDimitry Andric     // Check is done the following way:
1009*0b57cec5SDimitry Andric     //    (ebp+CookieXOROffset) ^ [ebp+CookieOffset] == _security_cookie
1010*0b57cec5SDimitry Andric 
1011*0b57cec5SDimitry Andric     // Retrieve the Guard Stack slot.
1012*0b57cec5SDimitry Andric     int GSCookieOffset = -2;
1013*0b57cec5SDimitry Andric     const MachineFrameInfo &MFI = MF->getFrameInfo();
1014*0b57cec5SDimitry Andric     if (MFI.hasStackProtectorIndex()) {
1015*0b57cec5SDimitry Andric       unsigned UnusedReg;
1016*0b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1017*0b57cec5SDimitry Andric       int SSPIdx = MFI.getStackProtectorIndex();
1018*0b57cec5SDimitry Andric       GSCookieOffset = TFI->getFrameIndexReference(*MF, SSPIdx, UnusedReg);
1019*0b57cec5SDimitry Andric     }
1020*0b57cec5SDimitry Andric 
1021*0b57cec5SDimitry Andric     // Retrieve the EH Guard slot.
1022*0b57cec5SDimitry Andric     // TODO(etienneb): Get rid of this value and change it for and assertion.
1023*0b57cec5SDimitry Andric     int EHCookieOffset = 9999;
1024*0b57cec5SDimitry Andric     if (FuncInfo.EHGuardFrameIndex != INT_MAX) {
1025*0b57cec5SDimitry Andric       unsigned UnusedReg;
1026*0b57cec5SDimitry Andric       const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1027*0b57cec5SDimitry Andric       int EHGuardIdx = FuncInfo.EHGuardFrameIndex;
1028*0b57cec5SDimitry Andric       EHCookieOffset = TFI->getFrameIndexReference(*MF, EHGuardIdx, UnusedReg);
1029*0b57cec5SDimitry Andric     }
1030*0b57cec5SDimitry Andric 
1031*0b57cec5SDimitry Andric     AddComment("GSCookieOffset");
1032*0b57cec5SDimitry Andric     OS.EmitIntValue(GSCookieOffset, 4);
1033*0b57cec5SDimitry Andric     AddComment("GSCookieXOROffset");
1034*0b57cec5SDimitry Andric     OS.EmitIntValue(0, 4);
1035*0b57cec5SDimitry Andric     AddComment("EHCookieOffset");
1036*0b57cec5SDimitry Andric     OS.EmitIntValue(EHCookieOffset, 4);
1037*0b57cec5SDimitry Andric     AddComment("EHCookieXOROffset");
1038*0b57cec5SDimitry Andric     OS.EmitIntValue(0, 4);
1039*0b57cec5SDimitry Andric     BaseState = -2;
1040*0b57cec5SDimitry Andric   }
1041*0b57cec5SDimitry Andric 
1042*0b57cec5SDimitry Andric   assert(!FuncInfo.SEHUnwindMap.empty());
1043*0b57cec5SDimitry Andric   for (const SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
1044*0b57cec5SDimitry Andric     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
1045*0b57cec5SDimitry Andric     const MCSymbol *ExceptOrFinally =
1046*0b57cec5SDimitry Andric         UME.IsFinally ? getMCSymbolForMBB(Asm, Handler) : Handler->getSymbol();
1047*0b57cec5SDimitry Andric     // -1 is usually the base state for "unwind to caller", but for
1048*0b57cec5SDimitry Andric     // _except_handler4 it's -2. Do that replacement here if necessary.
1049*0b57cec5SDimitry Andric     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
1050*0b57cec5SDimitry Andric     AddComment("ToState");
1051*0b57cec5SDimitry Andric     OS.EmitIntValue(ToState, 4);
1052*0b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "Null" : "FilterFunction");
1053*0b57cec5SDimitry Andric     OS.EmitValue(create32bitRef(UME.Filter), 4);
1054*0b57cec5SDimitry Andric     AddComment(UME.IsFinally ? "FinallyFunclet" : "ExceptionHandler");
1055*0b57cec5SDimitry Andric     OS.EmitValue(create32bitRef(ExceptOrFinally), 4);
1056*0b57cec5SDimitry Andric   }
1057*0b57cec5SDimitry Andric }
1058*0b57cec5SDimitry Andric 
1059*0b57cec5SDimitry Andric static int getTryRank(const WinEHFuncInfo &FuncInfo, int State) {
1060*0b57cec5SDimitry Andric   int Rank = 0;
1061*0b57cec5SDimitry Andric   while (State != -1) {
1062*0b57cec5SDimitry Andric     ++Rank;
1063*0b57cec5SDimitry Andric     State = FuncInfo.ClrEHUnwindMap[State].TryParentState;
1064*0b57cec5SDimitry Andric   }
1065*0b57cec5SDimitry Andric   return Rank;
1066*0b57cec5SDimitry Andric }
1067*0b57cec5SDimitry Andric 
1068*0b57cec5SDimitry Andric static int getTryAncestor(const WinEHFuncInfo &FuncInfo, int Left, int Right) {
1069*0b57cec5SDimitry Andric   int LeftRank = getTryRank(FuncInfo, Left);
1070*0b57cec5SDimitry Andric   int RightRank = getTryRank(FuncInfo, Right);
1071*0b57cec5SDimitry Andric 
1072*0b57cec5SDimitry Andric   while (LeftRank < RightRank) {
1073*0b57cec5SDimitry Andric     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
1074*0b57cec5SDimitry Andric     --RightRank;
1075*0b57cec5SDimitry Andric   }
1076*0b57cec5SDimitry Andric 
1077*0b57cec5SDimitry Andric   while (RightRank < LeftRank) {
1078*0b57cec5SDimitry Andric     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1079*0b57cec5SDimitry Andric     --LeftRank;
1080*0b57cec5SDimitry Andric   }
1081*0b57cec5SDimitry Andric 
1082*0b57cec5SDimitry Andric   while (Left != Right) {
1083*0b57cec5SDimitry Andric     Left = FuncInfo.ClrEHUnwindMap[Left].TryParentState;
1084*0b57cec5SDimitry Andric     Right = FuncInfo.ClrEHUnwindMap[Right].TryParentState;
1085*0b57cec5SDimitry Andric   }
1086*0b57cec5SDimitry Andric 
1087*0b57cec5SDimitry Andric   return Left;
1088*0b57cec5SDimitry Andric }
1089*0b57cec5SDimitry Andric 
1090*0b57cec5SDimitry Andric void WinException::emitCLRExceptionTable(const MachineFunction *MF) {
1091*0b57cec5SDimitry Andric   // CLR EH "states" are really just IDs that identify handlers/funclets;
1092*0b57cec5SDimitry Andric   // states, handlers, and funclets all have 1:1 mappings between them, and a
1093*0b57cec5SDimitry Andric   // handler/funclet's "state" is its index in the ClrEHUnwindMap.
1094*0b57cec5SDimitry Andric   MCStreamer &OS = *Asm->OutStreamer;
1095*0b57cec5SDimitry Andric   const WinEHFuncInfo &FuncInfo = *MF->getWinEHFuncInfo();
1096*0b57cec5SDimitry Andric   MCSymbol *FuncBeginSym = Asm->getFunctionBegin();
1097*0b57cec5SDimitry Andric   MCSymbol *FuncEndSym = Asm->getFunctionEnd();
1098*0b57cec5SDimitry Andric 
1099*0b57cec5SDimitry Andric   // A ClrClause describes a protected region.
1100*0b57cec5SDimitry Andric   struct ClrClause {
1101*0b57cec5SDimitry Andric     const MCSymbol *StartLabel; // Start of protected region
1102*0b57cec5SDimitry Andric     const MCSymbol *EndLabel;   // End of protected region
1103*0b57cec5SDimitry Andric     int State;          // Index of handler protecting the protected region
1104*0b57cec5SDimitry Andric     int EnclosingState; // Index of funclet enclosing the protected region
1105*0b57cec5SDimitry Andric   };
1106*0b57cec5SDimitry Andric   SmallVector<ClrClause, 8> Clauses;
1107*0b57cec5SDimitry Andric 
1108*0b57cec5SDimitry Andric   // Build a map from handler MBBs to their corresponding states (i.e. their
1109*0b57cec5SDimitry Andric   // indices in the ClrEHUnwindMap).
1110*0b57cec5SDimitry Andric   int NumStates = FuncInfo.ClrEHUnwindMap.size();
1111*0b57cec5SDimitry Andric   assert(NumStates > 0 && "Don't need exception table!");
1112*0b57cec5SDimitry Andric   DenseMap<const MachineBasicBlock *, int> HandlerStates;
1113*0b57cec5SDimitry Andric   for (int State = 0; State < NumStates; ++State) {
1114*0b57cec5SDimitry Andric     MachineBasicBlock *HandlerBlock =
1115*0b57cec5SDimitry Andric         FuncInfo.ClrEHUnwindMap[State].Handler.get<MachineBasicBlock *>();
1116*0b57cec5SDimitry Andric     HandlerStates[HandlerBlock] = State;
1117*0b57cec5SDimitry Andric     // Use this loop through all handlers to verify our assumption (used in
1118*0b57cec5SDimitry Andric     // the MinEnclosingState computation) that enclosing funclets have lower
1119*0b57cec5SDimitry Andric     // state numbers than their enclosed funclets.
1120*0b57cec5SDimitry Andric     assert(FuncInfo.ClrEHUnwindMap[State].HandlerParentState < State &&
1121*0b57cec5SDimitry Andric            "ill-formed state numbering");
1122*0b57cec5SDimitry Andric   }
1123*0b57cec5SDimitry Andric   // Map the main function to the NullState.
1124*0b57cec5SDimitry Andric   HandlerStates[&MF->front()] = NullState;
1125*0b57cec5SDimitry Andric 
1126*0b57cec5SDimitry Andric   // Write out a sentinel indicating the end of the standard (Windows) xdata
1127*0b57cec5SDimitry Andric   // and the start of the additional (CLR) info.
1128*0b57cec5SDimitry Andric   OS.EmitIntValue(0xffffffff, 4);
1129*0b57cec5SDimitry Andric   // Write out the number of funclets
1130*0b57cec5SDimitry Andric   OS.EmitIntValue(NumStates, 4);
1131*0b57cec5SDimitry Andric 
1132*0b57cec5SDimitry Andric   // Walk the machine blocks/instrs, computing and emitting a few things:
1133*0b57cec5SDimitry Andric   // 1. Emit a list of the offsets to each handler entry, in lexical order.
1134*0b57cec5SDimitry Andric   // 2. Compute a map (EndSymbolMap) from each funclet to the symbol at its end.
1135*0b57cec5SDimitry Andric   // 3. Compute the list of ClrClauses, in the required order (inner before
1136*0b57cec5SDimitry Andric   //    outer, earlier before later; the order by which a forward scan with
1137*0b57cec5SDimitry Andric   //    early termination will find the innermost enclosing clause covering
1138*0b57cec5SDimitry Andric   //    a given address).
1139*0b57cec5SDimitry Andric   // 4. A map (MinClauseMap) from each handler index to the index of the
1140*0b57cec5SDimitry Andric   //    outermost funclet/function which contains a try clause targeting the
1141*0b57cec5SDimitry Andric   //    key handler.  This will be used to determine IsDuplicate-ness when
1142*0b57cec5SDimitry Andric   //    emitting ClrClauses.  The NullState value is used to indicate that the
1143*0b57cec5SDimitry Andric   //    top-level function contains a try clause targeting the key handler.
1144*0b57cec5SDimitry Andric   // HandlerStack is a stack of (PendingStartLabel, PendingState) pairs for
1145*0b57cec5SDimitry Andric   // try regions we entered before entering the PendingState try but which
1146*0b57cec5SDimitry Andric   // we haven't yet exited.
1147*0b57cec5SDimitry Andric   SmallVector<std::pair<const MCSymbol *, int>, 4> HandlerStack;
1148*0b57cec5SDimitry Andric   // EndSymbolMap and MinClauseMap are maps described above.
1149*0b57cec5SDimitry Andric   std::unique_ptr<MCSymbol *[]> EndSymbolMap(new MCSymbol *[NumStates]);
1150*0b57cec5SDimitry Andric   SmallVector<int, 4> MinClauseMap((size_t)NumStates, NumStates);
1151*0b57cec5SDimitry Andric 
1152*0b57cec5SDimitry Andric   // Visit the root function and each funclet.
1153*0b57cec5SDimitry Andric   for (MachineFunction::const_iterator FuncletStart = MF->begin(),
1154*0b57cec5SDimitry Andric                                        FuncletEnd = MF->begin(),
1155*0b57cec5SDimitry Andric                                        End = MF->end();
1156*0b57cec5SDimitry Andric        FuncletStart != End; FuncletStart = FuncletEnd) {
1157*0b57cec5SDimitry Andric     int FuncletState = HandlerStates[&*FuncletStart];
1158*0b57cec5SDimitry Andric     // Find the end of the funclet
1159*0b57cec5SDimitry Andric     MCSymbol *EndSymbol = FuncEndSym;
1160*0b57cec5SDimitry Andric     while (++FuncletEnd != End) {
1161*0b57cec5SDimitry Andric       if (FuncletEnd->isEHFuncletEntry()) {
1162*0b57cec5SDimitry Andric         EndSymbol = getMCSymbolForMBB(Asm, &*FuncletEnd);
1163*0b57cec5SDimitry Andric         break;
1164*0b57cec5SDimitry Andric       }
1165*0b57cec5SDimitry Andric     }
1166*0b57cec5SDimitry Andric     // Emit the function/funclet end and, if this is a funclet (and not the
1167*0b57cec5SDimitry Andric     // root function), record it in the EndSymbolMap.
1168*0b57cec5SDimitry Andric     OS.EmitValue(getOffset(EndSymbol, FuncBeginSym), 4);
1169*0b57cec5SDimitry Andric     if (FuncletState != NullState) {
1170*0b57cec5SDimitry Andric       // Record the end of the handler.
1171*0b57cec5SDimitry Andric       EndSymbolMap[FuncletState] = EndSymbol;
1172*0b57cec5SDimitry Andric     }
1173*0b57cec5SDimitry Andric 
1174*0b57cec5SDimitry Andric     // Walk the state changes in this function/funclet and compute its clauses.
1175*0b57cec5SDimitry Andric     // Funclets always start in the null state.
1176*0b57cec5SDimitry Andric     const MCSymbol *CurrentStartLabel = nullptr;
1177*0b57cec5SDimitry Andric     int CurrentState = NullState;
1178*0b57cec5SDimitry Andric     assert(HandlerStack.empty());
1179*0b57cec5SDimitry Andric     for (const auto &StateChange :
1180*0b57cec5SDimitry Andric          InvokeStateChangeIterator::range(FuncInfo, FuncletStart, FuncletEnd)) {
1181*0b57cec5SDimitry Andric       // Close any try regions we're not still under
1182*0b57cec5SDimitry Andric       int StillPendingState =
1183*0b57cec5SDimitry Andric           getTryAncestor(FuncInfo, CurrentState, StateChange.NewState);
1184*0b57cec5SDimitry Andric       while (CurrentState != StillPendingState) {
1185*0b57cec5SDimitry Andric         assert(CurrentState != NullState &&
1186*0b57cec5SDimitry Andric                "Failed to find still-pending state!");
1187*0b57cec5SDimitry Andric         // Close the pending clause
1188*0b57cec5SDimitry Andric         Clauses.push_back({CurrentStartLabel, StateChange.PreviousEndLabel,
1189*0b57cec5SDimitry Andric                            CurrentState, FuncletState});
1190*0b57cec5SDimitry Andric         // Now the next-outer try region is current
1191*0b57cec5SDimitry Andric         CurrentState = FuncInfo.ClrEHUnwindMap[CurrentState].TryParentState;
1192*0b57cec5SDimitry Andric         // Pop the new start label from the handler stack if we've exited all
1193*0b57cec5SDimitry Andric         // inner try regions of the corresponding try region.
1194*0b57cec5SDimitry Andric         if (HandlerStack.back().second == CurrentState)
1195*0b57cec5SDimitry Andric           CurrentStartLabel = HandlerStack.pop_back_val().first;
1196*0b57cec5SDimitry Andric       }
1197*0b57cec5SDimitry Andric 
1198*0b57cec5SDimitry Andric       if (StateChange.NewState != CurrentState) {
1199*0b57cec5SDimitry Andric         // For each clause we're starting, update the MinClauseMap so we can
1200*0b57cec5SDimitry Andric         // know which is the topmost funclet containing a clause targeting
1201*0b57cec5SDimitry Andric         // it.
1202*0b57cec5SDimitry Andric         for (int EnteredState = StateChange.NewState;
1203*0b57cec5SDimitry Andric              EnteredState != CurrentState;
1204*0b57cec5SDimitry Andric              EnteredState =
1205*0b57cec5SDimitry Andric                  FuncInfo.ClrEHUnwindMap[EnteredState].TryParentState) {
1206*0b57cec5SDimitry Andric           int &MinEnclosingState = MinClauseMap[EnteredState];
1207*0b57cec5SDimitry Andric           if (FuncletState < MinEnclosingState)
1208*0b57cec5SDimitry Andric             MinEnclosingState = FuncletState;
1209*0b57cec5SDimitry Andric         }
1210*0b57cec5SDimitry Andric         // Save the previous current start/label on the stack and update to
1211*0b57cec5SDimitry Andric         // the newly-current start/state.
1212*0b57cec5SDimitry Andric         HandlerStack.emplace_back(CurrentStartLabel, CurrentState);
1213*0b57cec5SDimitry Andric         CurrentStartLabel = StateChange.NewStartLabel;
1214*0b57cec5SDimitry Andric         CurrentState = StateChange.NewState;
1215*0b57cec5SDimitry Andric       }
1216*0b57cec5SDimitry Andric     }
1217*0b57cec5SDimitry Andric     assert(HandlerStack.empty());
1218*0b57cec5SDimitry Andric   }
1219*0b57cec5SDimitry Andric 
1220*0b57cec5SDimitry Andric   // Now emit the clause info, starting with the number of clauses.
1221*0b57cec5SDimitry Andric   OS.EmitIntValue(Clauses.size(), 4);
1222*0b57cec5SDimitry Andric   for (ClrClause &Clause : Clauses) {
1223*0b57cec5SDimitry Andric     // Emit a CORINFO_EH_CLAUSE :
1224*0b57cec5SDimitry Andric     /*
1225*0b57cec5SDimitry Andric       struct CORINFO_EH_CLAUSE
1226*0b57cec5SDimitry Andric       {
1227*0b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FLAGS Flags;         // actually a CorExceptionFlag
1228*0b57cec5SDimitry Andric           DWORD                   TryOffset;
1229*0b57cec5SDimitry Andric           DWORD                   TryLength;     // actually TryEndOffset
1230*0b57cec5SDimitry Andric           DWORD                   HandlerOffset;
1231*0b57cec5SDimitry Andric           DWORD                   HandlerLength; // actually HandlerEndOffset
1232*0b57cec5SDimitry Andric           union
1233*0b57cec5SDimitry Andric           {
1234*0b57cec5SDimitry Andric               DWORD               ClassToken;   // use for catch clauses
1235*0b57cec5SDimitry Andric               DWORD               FilterOffset; // use for filter clauses
1236*0b57cec5SDimitry Andric           };
1237*0b57cec5SDimitry Andric       };
1238*0b57cec5SDimitry Andric 
1239*0b57cec5SDimitry Andric       enum CORINFO_EH_CLAUSE_FLAGS
1240*0b57cec5SDimitry Andric       {
1241*0b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_NONE    = 0,
1242*0b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FILTER  = 0x0001, // This clause is for a filter
1243*0b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
1244*0b57cec5SDimitry Andric           CORINFO_EH_CLAUSE_FAULT   = 0x0004, // This clause is a fault clause
1245*0b57cec5SDimitry Andric       };
1246*0b57cec5SDimitry Andric       typedef enum CorExceptionFlag
1247*0b57cec5SDimitry Andric       {
1248*0b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_NONE,
1249*0b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FILTER  = 0x0001, // This is a filter clause
1250*0b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FINALLY = 0x0002, // This is a finally clause
1251*0b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_FAULT = 0x0004,   // This is a fault clause
1252*0b57cec5SDimitry Andric           COR_ILEXCEPTION_CLAUSE_DUPLICATED = 0x0008, // duplicated clause. This
1253*0b57cec5SDimitry Andric                                                       // clause was duplicated
1254*0b57cec5SDimitry Andric                                                       // to a funclet which was
1255*0b57cec5SDimitry Andric                                                       // pulled out of line
1256*0b57cec5SDimitry Andric       } CorExceptionFlag;
1257*0b57cec5SDimitry Andric     */
1258*0b57cec5SDimitry Andric     // Add 1 to the start/end of the EH clause; the IP associated with a
1259*0b57cec5SDimitry Andric     // call when the runtime does its scan is the IP of the next instruction
1260*0b57cec5SDimitry Andric     // (the one to which control will return after the call), so we need
1261*0b57cec5SDimitry Andric     // to add 1 to the end of the clause to cover that offset.  We also add
1262*0b57cec5SDimitry Andric     // 1 to the start of the clause to make sure that the ranges reported
1263*0b57cec5SDimitry Andric     // for all clauses are disjoint.  Note that we'll need some additional
1264*0b57cec5SDimitry Andric     // logic when machine traps are supported, since in that case the IP
1265*0b57cec5SDimitry Andric     // that the runtime uses is the offset of the faulting instruction
1266*0b57cec5SDimitry Andric     // itself; if such an instruction immediately follows a call but the
1267*0b57cec5SDimitry Andric     // two belong to different clauses, we'll need to insert a nop between
1268*0b57cec5SDimitry Andric     // them so the runtime can distinguish the point to which the call will
1269*0b57cec5SDimitry Andric     // return from the point at which the fault occurs.
1270*0b57cec5SDimitry Andric 
1271*0b57cec5SDimitry Andric     const MCExpr *ClauseBegin =
1272*0b57cec5SDimitry Andric         getOffsetPlusOne(Clause.StartLabel, FuncBeginSym);
1273*0b57cec5SDimitry Andric     const MCExpr *ClauseEnd = getOffsetPlusOne(Clause.EndLabel, FuncBeginSym);
1274*0b57cec5SDimitry Andric 
1275*0b57cec5SDimitry Andric     const ClrEHUnwindMapEntry &Entry = FuncInfo.ClrEHUnwindMap[Clause.State];
1276*0b57cec5SDimitry Andric     MachineBasicBlock *HandlerBlock = Entry.Handler.get<MachineBasicBlock *>();
1277*0b57cec5SDimitry Andric     MCSymbol *BeginSym = getMCSymbolForMBB(Asm, HandlerBlock);
1278*0b57cec5SDimitry Andric     const MCExpr *HandlerBegin = getOffset(BeginSym, FuncBeginSym);
1279*0b57cec5SDimitry Andric     MCSymbol *EndSym = EndSymbolMap[Clause.State];
1280*0b57cec5SDimitry Andric     const MCExpr *HandlerEnd = getOffset(EndSym, FuncBeginSym);
1281*0b57cec5SDimitry Andric 
1282*0b57cec5SDimitry Andric     uint32_t Flags = 0;
1283*0b57cec5SDimitry Andric     switch (Entry.HandlerType) {
1284*0b57cec5SDimitry Andric     case ClrHandlerType::Catch:
1285*0b57cec5SDimitry Andric       // Leaving bits 0-2 clear indicates catch.
1286*0b57cec5SDimitry Andric       break;
1287*0b57cec5SDimitry Andric     case ClrHandlerType::Filter:
1288*0b57cec5SDimitry Andric       Flags |= 1;
1289*0b57cec5SDimitry Andric       break;
1290*0b57cec5SDimitry Andric     case ClrHandlerType::Finally:
1291*0b57cec5SDimitry Andric       Flags |= 2;
1292*0b57cec5SDimitry Andric       break;
1293*0b57cec5SDimitry Andric     case ClrHandlerType::Fault:
1294*0b57cec5SDimitry Andric       Flags |= 4;
1295*0b57cec5SDimitry Andric       break;
1296*0b57cec5SDimitry Andric     }
1297*0b57cec5SDimitry Andric     if (Clause.EnclosingState != MinClauseMap[Clause.State]) {
1298*0b57cec5SDimitry Andric       // This is a "duplicate" clause; the handler needs to be entered from a
1299*0b57cec5SDimitry Andric       // frame above the one holding the invoke.
1300*0b57cec5SDimitry Andric       assert(Clause.EnclosingState > MinClauseMap[Clause.State]);
1301*0b57cec5SDimitry Andric       Flags |= 8;
1302*0b57cec5SDimitry Andric     }
1303*0b57cec5SDimitry Andric     OS.EmitIntValue(Flags, 4);
1304*0b57cec5SDimitry Andric 
1305*0b57cec5SDimitry Andric     // Write the clause start/end
1306*0b57cec5SDimitry Andric     OS.EmitValue(ClauseBegin, 4);
1307*0b57cec5SDimitry Andric     OS.EmitValue(ClauseEnd, 4);
1308*0b57cec5SDimitry Andric 
1309*0b57cec5SDimitry Andric     // Write out the handler start/end
1310*0b57cec5SDimitry Andric     OS.EmitValue(HandlerBegin, 4);
1311*0b57cec5SDimitry Andric     OS.EmitValue(HandlerEnd, 4);
1312*0b57cec5SDimitry Andric 
1313*0b57cec5SDimitry Andric     // Write out the type token or filter offset
1314*0b57cec5SDimitry Andric     assert(Entry.HandlerType != ClrHandlerType::Filter && "NYI: filters");
1315*0b57cec5SDimitry Andric     OS.EmitIntValue(Entry.TypeToken, 4);
1316*0b57cec5SDimitry Andric   }
1317*0b57cec5SDimitry Andric }
1318