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