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