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