Call the correct overload.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / WinException.cpp
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/SmallString.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/WinEHFuncInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Mangler.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCWin64EH.h"
33 #include "llvm/Support/COFF.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Target/TargetFrameLowering.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 using namespace llvm;
42
43 WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
44   // MSVC's EH tables are always composed of 32-bit words.  All known 64-bit
45   // platforms use an imagerel32 relocation to refer to symbols.
46   useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
47 }
48
49 WinException::~WinException() {}
50
51 /// endModule - Emit all exception information that should come after the
52 /// content.
53 void WinException::endModule() {
54   auto &OS = *Asm->OutStreamer;
55   const Module *M = MMI->getModule();
56   for (const Function &F : *M)
57     if (F.hasFnAttribute("safeseh"))
58       OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
59 }
60
61 void WinException::beginFunction(const MachineFunction *MF) {
62   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
63
64   // If any landing pads survive, we need an EH table.
65   bool hasLandingPads = !MMI->getLandingPads().empty();
66   bool hasEHFunclets = MMI->hasEHFunclets();
67
68   const Function *F = MF->getFunction();
69   const Function *ParentF = MMI->getWinEHParent(F);
70
71   shouldEmitMoves = Asm->needsSEHMoves();
72
73   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
74   unsigned PerEncoding = TLOF.getPersonalityEncoding();
75   const Function *Per = nullptr;
76   if (F->hasPersonalityFn())
77     Per = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
78
79   bool forceEmitPersonality =
80     F->hasPersonalityFn() && !isNoOpWithoutInvoke(classifyEHPersonality(Per)) &&
81     F->needsUnwindTableEntry();
82
83   shouldEmitPersonality =
84       forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
85                                PerEncoding != dwarf::DW_EH_PE_omit && Per);
86
87   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
88   shouldEmitLSDA = shouldEmitPersonality &&
89     LSDAEncoding != dwarf::DW_EH_PE_omit;
90
91   // If we're not using CFI, we don't want the CFI or the personality, but we
92   // might want EH tables if we had EH pads.
93   // FIXME: If WinEHPrepare outlined something, we should emit the LSDA. Remove
94   // this once WinEHPrepare stops doing that.
95   if (!Asm->MAI->usesWindowsCFI()) {
96     shouldEmitLSDA =
97         hasEHFunclets || (F->hasFnAttribute("wineh-parent") && F == ParentF);
98     shouldEmitPersonality = false;
99     return;
100   }
101
102   beginFunclet(MF->front(), Asm->CurrentFnSym);
103 }
104
105 /// endFunction - Gather and emit post-function exception information.
106 ///
107 void WinException::endFunction(const MachineFunction *MF) {
108   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
109     return;
110
111   const Function *F = MF->getFunction();
112   EHPersonality Per = EHPersonality::Unknown;
113   if (F->hasPersonalityFn())
114     Per = classifyEHPersonality(F->getPersonalityFn());
115
116   // Get rid of any dead landing pads if we're not using a Windows EH scheme. In
117   // Windows EH schemes, the landing pad is not actually reachable. It only
118   // exists so that we can emit the right table data.
119   if (!isMSVCEHPersonality(Per))
120     MMI->TidyLandingPads();
121
122   endFunclet();
123
124   // endFunclet will emit the necessary .xdata tables for x64 SEH.
125   if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
126     return;
127
128   if (shouldEmitPersonality || shouldEmitLSDA) {
129     Asm->OutStreamer->PushSection();
130
131     // Just switch sections to the right xdata section. This use of CurrentFnSym
132     // assumes that we only emit the LSDA when ending the parent function.
133     MCSection *XData = WinEH::UnwindEmitter::getXDataSection(Asm->CurrentFnSym,
134                                                              Asm->OutContext);
135     Asm->OutStreamer->SwitchSection(XData);
136
137     // Emit the tables appropriate to the personality function in use. If we
138     // don't recognize the personality, assume it uses an Itanium-style LSDA.
139     if (Per == EHPersonality::MSVC_Win64SEH)
140       emitCSpecificHandlerTable(MF);
141     else if (Per == EHPersonality::MSVC_X86SEH)
142       emitExceptHandlerTable(MF);
143     else if (Per == EHPersonality::MSVC_CXX)
144       emitCXXFrameHandler3Table(MF);
145     else
146       emitExceptionTable();
147
148     Asm->OutStreamer->PopSection();
149   }
150 }
151
152 /// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
153 /// are used in the old WinEH scheme, and they will be removed eventually.
154 static MCSymbol *getMCSymbolForMBBOrGV(AsmPrinter *Asm, ValueOrMBB Handler) {
155   if (!Handler)
156     return nullptr;
157   if (Handler.is<const MachineBasicBlock *>()) {
158     auto *MBB = Handler.get<const MachineBasicBlock *>();
159     assert(MBB->isEHFuncletEntry());
160
161     // Give catches and cleanups a name based off of their parent function and
162     // their funclet entry block's number.
163     const MachineFunction *MF = MBB->getParent();
164     const Function *F = MF->getFunction();
165     StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
166     MCContext &Ctx = MF->getContext();
167     StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
168     return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
169                                  Twine(MBB->getNumber()) + "@?0?" +
170                                  FuncLinkageName + "@4HA");
171   }
172   return Asm->getSymbol(cast<GlobalValue>(Handler.get<const Value *>()));
173 }
174
175 void WinException::beginFunclet(const MachineBasicBlock &MBB,
176                                 MCSymbol *Sym) {
177   CurrentFuncletEntry = &MBB;
178
179   const Function *F = Asm->MF->getFunction();
180   // If a symbol was not provided for the funclet, invent one.
181   if (!Sym) {
182     Sym = getMCSymbolForMBBOrGV(Asm, &MBB);
183
184     // Describe our funclet symbol as a function with internal linkage.
185     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
186     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
187     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
188                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
189     Asm->OutStreamer->EndCOFFSymbolDef();
190
191     // We want our funclet's entry point to be aligned such that no nops will be
192     // present after the label.
193     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
194                        F);
195
196     // Now that we've emitted the alignment directive, point at our funclet.
197     Asm->OutStreamer->EmitLabel(Sym);
198   }
199
200   // Mark 'Sym' as starting our funclet.
201   if (shouldEmitMoves || shouldEmitPersonality)
202     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
203
204   if (shouldEmitPersonality) {
205     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
206     const Function *PerFn = nullptr;
207
208     // Determine which personality routine we are using for this funclet.
209     if (F->hasPersonalityFn())
210       PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
211     const MCSymbol *PersHandlerSym =
212         TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
213
214     // Classify the personality routine so that we may reason about it.
215     EHPersonality Per = EHPersonality::Unknown;
216     if (F->hasPersonalityFn())
217       Per = classifyEHPersonality(F->getPersonalityFn());
218
219     // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
220     if (Per != EHPersonality::MSVC_CXX ||
221         !CurrentFuncletEntry->isCleanupFuncletEntry())
222       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
223   }
224 }
225
226 void WinException::endFunclet() {
227   // No funclet to process?  Great, we have nothing to do.
228   if (!CurrentFuncletEntry)
229     return;
230
231   if (shouldEmitMoves || shouldEmitPersonality) {
232     const Function *F = Asm->MF->getFunction();
233     EHPersonality Per = EHPersonality::Unknown;
234     if (F->hasPersonalityFn())
235       Per = classifyEHPersonality(F->getPersonalityFn());
236
237     // The .seh_handlerdata directive implicitly switches section, push the
238     // current section so that we may return to it.
239     Asm->OutStreamer->PushSection();
240
241     // Emit an UNWIND_INFO struct describing the prologue.
242     Asm->OutStreamer->EmitWinEHHandlerData();
243
244     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
245         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
246       // If this is a C++ catch funclet (or the parent function),
247       // emit a reference to the LSDA for the parent function.
248       StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
249       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
250           Twine("$cppxdata$", FuncLinkageName));
251       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
252     } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
253                !CurrentFuncletEntry->isEHFuncletEntry()) {
254       // If this is the parent function in Win64 SEH, emit the LSDA immediately
255       // following .seh_handlerdata.
256       emitCSpecificHandlerTable(Asm->MF);
257     }
258
259     // Switch back to the previous section now that we are done writing to
260     // .xdata.
261     Asm->OutStreamer->PopSection();
262
263     // Emit a .seh_endproc directive to mark the end of the function.
264     Asm->OutStreamer->EmitWinCFIEndProc();
265   }
266
267   // Let's make sure we don't try to end the same funclet twice.
268   CurrentFuncletEntry = nullptr;
269 }
270
271 const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
272   if (!Value)
273     return MCConstantExpr::create(0, Asm->OutContext);
274   return MCSymbolRefExpr::create(Value, useImageRel32
275                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
276                                             : MCSymbolRefExpr::VK_None,
277                                  Asm->OutContext);
278 }
279
280 const MCExpr *WinException::create32bitRef(const Value *V) {
281   if (!V)
282     return MCConstantExpr::create(0, Asm->OutContext);
283   // FIXME: Delete the GlobalValue case once the new IR is fully functional.
284   if (const auto *GV = dyn_cast<GlobalValue>(V))
285     return create32bitRef(Asm->getSymbol(GV));
286   return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
287 }
288
289 const MCExpr *WinException::getLabelPlusOne(MCSymbol *Label) {
290   return MCBinaryExpr::createAdd(create32bitRef(Label),
291                                  MCConstantExpr::create(1, Asm->OutContext),
292                                  Asm->OutContext);
293 }
294
295 /// Information describing an invoke range.
296 struct InvokeRange {
297   MCSymbol *BeginLabel = nullptr;
298   MCSymbol *EndLabel = nullptr;
299   int State = -1;
300
301   /// If we saw a potentially throwing call between this range and the last
302   /// range.
303   bool SawPotentiallyThrowing = false;
304 };
305
306 /// Iterator over the begin/end label pairs of invokes within a basic block.
307 class InvokeLabelIterator {
308 public:
309   InvokeLabelIterator(WinEHFuncInfo &EHInfo,
310                       MachineBasicBlock::const_iterator MBBI,
311                       MachineBasicBlock::const_iterator MBBIEnd)
312       : EHInfo(EHInfo), MBBI(MBBI), MBBIEnd(MBBIEnd) {
313     scan();
314   }
315
316   // Iterator methods.
317   bool operator==(const InvokeLabelIterator &o) const { return MBBI == o.MBBI; }
318   bool operator!=(const InvokeLabelIterator &o) const { return MBBI != o.MBBI; }
319   InvokeRange &operator*() { return CurRange; }
320   InvokeRange *operator->() { return &CurRange; }
321   InvokeLabelIterator &operator++() { return scan(); }
322
323 private:
324   // Scan forward to find the next invoke range, or hit the end iterator.
325   InvokeLabelIterator &scan();
326
327   WinEHFuncInfo &EHInfo;
328   MachineBasicBlock::const_iterator MBBI;
329   MachineBasicBlock::const_iterator MBBIEnd;
330   InvokeRange CurRange;
331 };
332
333 /// Invoke label range iteration logic. Increment MBBI until we find the next
334 /// EH_LABEL pair, and then update MBBI to point after the end label.
335 InvokeLabelIterator &InvokeLabelIterator::scan() {
336   // Reset our state.
337   CurRange = InvokeRange{};
338
339   for (const MachineInstr &MI : make_range(MBBI, MBBIEnd)) {
340     // Remember if we had to cross a potentially throwing call instruction that
341     // must unwind to caller.
342     if (MI.isCall()) {
343       CurRange.SawPotentiallyThrowing |=
344           !EHStreamer::callToNoUnwindFunction(&MI);
345       continue;
346     }
347     // Find the next EH_LABEL instruction.
348     if (!MI.isEHLabel())
349       continue;
350
351     // If this is a begin label, break out with the state and end label.
352     // Otherwise this is probably a CFI EH_LABEL that we should continue past.
353     MCSymbol *Label = MI.getOperand(0).getMCSymbol();
354     auto StateAndEnd = EHInfo.InvokeToStateMap.find(Label);
355     if (StateAndEnd == EHInfo.InvokeToStateMap.end())
356       continue;
357     MBBI = MachineBasicBlock::const_iterator(&MI);
358     CurRange.BeginLabel = Label;
359     CurRange.EndLabel = StateAndEnd->second.second;
360     CurRange.State = StateAndEnd->second.first;
361     break;
362   }
363
364   // If we didn't find a begin label, we are done, return the end iterator.
365   if (!CurRange.BeginLabel) {
366     MBBI = MBBIEnd;
367     return *this;
368   }
369
370   // If this is a begin label, update MBBI to point past the end label.
371   for (; MBBI != MBBIEnd; ++MBBI)
372     if (MBBI->isEHLabel() &&
373         MBBI->getOperand(0).getMCSymbol() == CurRange.EndLabel)
374       break;
375   return *this;
376 }
377
378 /// Utility for making a range for all the invoke ranges.
379 static iterator_range<InvokeLabelIterator>
380 invoke_ranges(WinEHFuncInfo &EHInfo, const MachineBasicBlock &MBB) {
381   return make_range(InvokeLabelIterator(EHInfo, MBB.begin(), MBB.end()),
382                     InvokeLabelIterator(EHInfo, MBB.end(), MBB.end()));
383 }
384
385 /// Emit the language-specific data that __C_specific_handler expects.  This
386 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
387 /// up after faults with __try, __except, and __finally.  The typeinfo values
388 /// are not really RTTI data, but pointers to filter functions that return an
389 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
390 /// blocks and other cleanups, the landing pad label is zero, and the filter
391 /// function is actually a cleanup handler with the same prototype.  A catch-all
392 /// entry is modeled with a null filter function field and a non-zero landing
393 /// pad label.
394 ///
395 /// Possible filter function return values:
396 ///   EXCEPTION_EXECUTE_HANDLER (1):
397 ///     Jump to the landing pad label after cleanups.
398 ///   EXCEPTION_CONTINUE_SEARCH (0):
399 ///     Continue searching this table or continue unwinding.
400 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
401 ///     Resume execution at the trapping PC.
402 ///
403 /// Inferred table structure:
404 ///   struct Table {
405 ///     int NumEntries;
406 ///     struct Entry {
407 ///       imagerel32 LabelStart;
408 ///       imagerel32 LabelEnd;
409 ///       imagerel32 FilterOrFinally;  // One means catch-all.
410 ///       imagerel32 LabelLPad;        // Zero means __finally.
411 ///     } Entries[NumEntries];
412 ///   };
413 void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
414   auto &OS = *Asm->OutStreamer;
415   MCContext &Ctx = Asm->OutContext;
416
417   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
418   if (!FuncInfo.SEHUnwindMap.empty()) {
419     // Remember what state we were in the last time we found a begin try label.
420     // This allows us to coalesce many nearby invokes with the same state into
421     // one entry.
422     int LastEHState = -1;
423     MCSymbol *LastBeginLabel = nullptr;
424     MCSymbol *LastEndLabel = nullptr;
425
426     // Use the assembler to compute the number of table entries through label
427     // difference and division.
428     MCSymbol *TableBegin =
429         Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
430     MCSymbol *TableEnd =
431         Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
432     const MCExpr *LabelDiff =
433         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TableEnd, Ctx),
434                                 MCSymbolRefExpr::create(TableBegin, Ctx), Ctx);
435     const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
436     const MCExpr *EntryCount =
437         MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
438     OS.EmitValue(EntryCount, 4);
439
440     OS.EmitLabel(TableBegin);
441
442     // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
443     // models exceptions from invokes. LLVM also allows arbitrary reordering of
444     // the code, so our tables end up looking a bit different. Rather than
445     // trying to match MSVC's tables exactly, we emit a denormalized table.  For
446     // each range of invokes in the same state, we emit table entries for all
447     // the actions that would be taken in that state. This means our tables are
448     // slightly bigger, which is OK.
449     for (const auto &MBB : *MF) {
450       for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
451         // If this invoke is in the same state as the last invoke and there were
452         // no non-throwing calls between it, extend the range to include both
453         // and continue.
454         if (!I.SawPotentiallyThrowing && I.State == LastEHState) {
455           LastEndLabel = I.EndLabel;
456           continue;
457         }
458
459         // If this invoke ends a previous one, emit all the actions for this
460         // state.
461         if (LastEHState != -1) {
462           assert(LastBeginLabel && LastEndLabel);
463           for (int State = LastEHState; State != -1;) {
464             SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
465             const MCExpr *FilterOrFinally;
466             const MCExpr *ExceptOrNull;
467             auto *Handler = UME.Handler.get<MachineBasicBlock *>();
468             if (UME.IsFinally) {
469               FilterOrFinally = create32bitRef(Handler->getSymbol());
470               ExceptOrNull = MCConstantExpr::create(0, Ctx);
471             } else {
472               // For an except, the filter can be 1 (catch-all) or a function
473               // label.
474               FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
475                                            : MCConstantExpr::create(1, Ctx);
476               ExceptOrNull = create32bitRef(Handler->getSymbol());
477             }
478
479             OS.EmitValue(getLabelPlusOne(LastBeginLabel), 4);
480             OS.EmitValue(getLabelPlusOne(LastEndLabel), 4);
481             OS.EmitValue(FilterOrFinally, 4);
482             OS.EmitValue(ExceptOrNull, 4);
483
484             State = UME.ToState;
485           }
486         }
487
488         LastBeginLabel = I.BeginLabel;
489         LastEndLabel = I.EndLabel;
490         LastEHState = I.State;
491       }
492     }
493     OS.EmitLabel(TableEnd);
494     return;
495   }
496
497   // Simplifying assumptions for first implementation:
498   // - Cleanups are not implemented.
499   // - Filters are not implemented.
500
501   // The Itanium LSDA table sorts similar landing pads together to simplify the
502   // actions table, but we don't need that.
503   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
504   SmallVector<const LandingPadInfo *, 64> LandingPads;
505   LandingPads.reserve(PadInfos.size());
506   for (const auto &LP : PadInfos)
507     LandingPads.push_back(&LP);
508
509   // Compute label ranges for call sites as we would for the Itanium LSDA, but
510   // use an all zero action table because we aren't using these actions.
511   SmallVector<unsigned, 64> FirstActions;
512   FirstActions.resize(LandingPads.size());
513   SmallVector<CallSiteEntry, 64> CallSites;
514   computeCallSiteTable(CallSites, LandingPads, FirstActions);
515
516   MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
517   MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
518
519   // Emit the number of table entries.
520   unsigned NumEntries = 0;
521   for (const CallSiteEntry &CSE : CallSites) {
522     if (!CSE.LPad)
523       continue; // Ignore gaps.
524     NumEntries += CSE.LPad->SEHHandlers.size();
525   }
526   OS.EmitIntValue(NumEntries, 4);
527
528   // If there are no actions, we don't need to iterate again.
529   if (NumEntries == 0)
530     return;
531
532   // Emit the four-label records for each call site entry. The table has to be
533   // sorted in layout order, and the call sites should already be sorted.
534   for (const CallSiteEntry &CSE : CallSites) {
535     // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
536     // an EH table entry will propagate the exception rather than terminating
537     // the program.
538     if (!CSE.LPad)
539       continue;
540     const LandingPadInfo *LPad = CSE.LPad;
541
542     // Compute the label range. We may reuse the function begin and end labels
543     // rather than forming new ones.
544     const MCExpr *Begin =
545         create32bitRef(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
546     const MCExpr *End;
547     if (CSE.EndLabel) {
548       // The interval is half-open, so we have to add one to include the return
549       // address of the last invoke in the range.
550       End = getLabelPlusOne(CSE.EndLabel);
551     } else {
552       End = create32bitRef(EHFuncEndSym);
553     }
554
555     // Emit an entry for each action.
556     for (SEHHandler Handler : LPad->SEHHandlers) {
557       OS.EmitValue(Begin, 4);
558       OS.EmitValue(End, 4);
559
560       // Emit the filter or finally function pointer, if present. Otherwise,
561       // emit '1' to indicate a catch-all.
562       const Function *F = Handler.FilterOrFinally;
563       if (F)
564         OS.EmitValue(create32bitRef(Asm->getSymbol(F)), 4);
565       else
566         OS.EmitIntValue(1, 4);
567
568       // Emit the recovery address, if present. Otherwise, this must be a
569       // finally.
570       const BlockAddress *BA = Handler.RecoverBA;
571       if (BA)
572         OS.EmitValue(
573             create32bitRef(Asm->GetBlockAddressSymbol(BA)), 4);
574       else
575         OS.EmitIntValue(0, 4);
576     }
577   }
578 }
579
580 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
581   const Function *F = MF->getFunction();
582   auto &OS = *Asm->OutStreamer;
583   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
584
585   StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
586
587   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
588   MCSymbol *FuncInfoXData = nullptr;
589   if (shouldEmitPersonality) {
590     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
591     // IPs to state numbers.
592     FuncInfoXData =
593         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
594     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
595   } else {
596     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
597     emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
598   }
599
600   MCSymbol *UnwindMapXData = nullptr;
601   MCSymbol *TryBlockMapXData = nullptr;
602   MCSymbol *IPToStateXData = nullptr;
603   if (!FuncInfo.UnwindMap.empty())
604     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
605         Twine("$stateUnwindMap$", FuncLinkageName));
606   if (!FuncInfo.TryBlockMap.empty())
607     TryBlockMapXData =
608         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
609   if (!IPToStateTable.empty())
610     IPToStateXData =
611         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
612
613   // FuncInfo {
614   //   uint32_t           MagicNumber
615   //   int32_t            MaxState;
616   //   UnwindMapEntry    *UnwindMap;
617   //   uint32_t           NumTryBlocks;
618   //   TryBlockMapEntry  *TryBlockMap;
619   //   uint32_t           IPMapEntries; // always 0 for x86
620   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
621   //   uint32_t           UnwindHelp;   // non-x86 only
622   //   ESTypeList        *ESTypeList;
623   //   int32_t            EHFlags;
624   // }
625   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
626   // EHFlags & 2 -> ???
627   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
628   OS.EmitValueToAlignment(4);
629   OS.EmitLabel(FuncInfoXData);
630   OS.EmitIntValue(0x19930522, 4);                      // MagicNumber
631   OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4);       // MaxState
632   OS.EmitValue(create32bitRef(UnwindMapXData), 4);     // UnwindMap
633   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);     // NumTryBlocks
634   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);   // TryBlockMap
635   OS.EmitIntValue(IPToStateTable.size(), 4);           // IPMapEntries
636   OS.EmitValue(create32bitRef(IPToStateXData), 4);     // IPToStateMap
637   if (Asm->MAI->usesWindowsCFI())
638     OS.EmitIntValue(FuncInfo.UnwindHelpFrameOffset, 4); // UnwindHelp
639   OS.EmitIntValue(0, 4);                               // ESTypeList
640   OS.EmitIntValue(1, 4);                               // EHFlags
641
642   // UnwindMapEntry {
643   //   int32_t ToState;
644   //   void  (*Action)();
645   // };
646   if (UnwindMapXData) {
647     OS.EmitLabel(UnwindMapXData);
648     for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
649       MCSymbol *CleanupSym = getMCSymbolForMBBOrGV(Asm, UME.Cleanup);
650       OS.EmitIntValue(UME.ToState, 4);             // ToState
651       OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
652     }
653   }
654
655   // TryBlockMap {
656   //   int32_t      TryLow;
657   //   int32_t      TryHigh;
658   //   int32_t      CatchHigh;
659   //   int32_t      NumCatches;
660   //   HandlerType *HandlerArray;
661   // };
662   if (TryBlockMapXData) {
663     OS.EmitLabel(TryBlockMapXData);
664     SmallVector<MCSymbol *, 1> HandlerMaps;
665     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
666       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
667
668       MCSymbol *HandlerMapXData = nullptr;
669       if (!TBME.HandlerArray.empty())
670         HandlerMapXData =
671             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
672                                                   .concat(Twine(I))
673                                                   .concat("$")
674                                                   .concat(FuncLinkageName));
675       HandlerMaps.push_back(HandlerMapXData);
676
677       // TBMEs should form intervals.
678       assert(0 <= TBME.TryLow && "bad trymap interval");
679       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
680       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
681       assert(TBME.CatchHigh < int(FuncInfo.UnwindMap.size()) &&
682              "bad trymap interval");
683
684       OS.EmitIntValue(TBME.TryLow, 4);                    // TryLow
685       OS.EmitIntValue(TBME.TryHigh, 4);                   // TryHigh
686       OS.EmitIntValue(TBME.CatchHigh, 4);                 // CatchHigh
687       OS.EmitIntValue(TBME.HandlerArray.size(), 4);       // NumCatches
688       OS.EmitValue(create32bitRef(HandlerMapXData), 4);   // HandlerArray
689     }
690
691     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
692       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
693       MCSymbol *HandlerMapXData = HandlerMaps[I];
694       if (!HandlerMapXData)
695         continue;
696       // HandlerType {
697       //   int32_t         Adjectives;
698       //   TypeDescriptor *Type;
699       //   int32_t         CatchObjOffset;
700       //   void          (*Handler)();
701       //   int32_t         ParentFrameOffset; // x64 only
702       // };
703       OS.EmitLabel(HandlerMapXData);
704       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
705         // Get the frame escape label with the offset of the catch object. If
706         // the index is -1, then there is no catch object, and we should emit an
707         // offset of zero, indicating that no copy will occur.
708         const MCExpr *FrameAllocOffsetRef = nullptr;
709         if (HT.CatchObjRecoverIdx >= 0) {
710           MCSymbol *FrameAllocOffset =
711               Asm->OutContext.getOrCreateFrameAllocSymbol(
712                   FuncLinkageName, HT.CatchObjRecoverIdx);
713           FrameAllocOffsetRef = MCSymbolRefExpr::create(
714               FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
715         } else if (HT.CatchObj.FrameOffset != INT_MAX) {
716           int Offset = HT.CatchObj.FrameOffset;
717           // For 32-bit, the catch object offset is relative to the end of the
718           // EH registration node. For 64-bit, it's relative to SP at the end of
719           // the prologue.
720           if (!shouldEmitPersonality) {
721             assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
722             Offset += FuncInfo.EHRegNodeEndOffset;
723           }
724           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
725         } else {
726           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
727         }
728
729         MCSymbol *HandlerSym = getMCSymbolForMBBOrGV(Asm, HT.Handler);
730
731         OS.EmitIntValue(HT.Adjectives, 4);                  // Adjectives
732         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
733         OS.EmitValue(FrameAllocOffsetRef, 4);               // CatchObjOffset
734         OS.EmitValue(create32bitRef(HandlerSym), 4);        // Handler
735
736         if (shouldEmitPersonality) {
737           // With the new IR, this is always 16 + 8 + getMaxCallFrameSize().
738           // Keep this in sync with X86FrameLowering::emitPrologue.
739           int ParentFrameOffset =
740               16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
741           OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
742         }
743       }
744     }
745   }
746
747   // IPToStateMapEntry {
748   //   void   *IP;
749   //   int32_t State;
750   // };
751   if (IPToStateXData) {
752     OS.EmitLabel(IPToStateXData);
753     for (auto &IPStatePair : IPToStateTable) {
754       OS.EmitValue(IPStatePair.first, 4);     // IP
755       OS.EmitIntValue(IPStatePair.second, 4); // State
756     }
757   }
758 }
759
760 void WinException::computeIP2StateTable(
761     const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
762     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
763   // Remember what state we were in the last time we found a begin try label.
764   // This allows us to coalesce many nearby invokes with the same state into one
765   // entry.
766   int LastEHState = -1;
767   MCSymbol *LastEndLabel = Asm->getFunctionBegin();
768   assert(LastEndLabel && "need local function start label");
769
770   // Indicate that all calls from the prologue to the first invoke unwind to
771   // caller. We handle this as a special case since other ranges starting at end
772   // labels need to use LtmpN+1.
773   IPToStateTable.push_back(std::make_pair(create32bitRef(LastEndLabel), -1));
774
775   for (const auto &MBB : *MF) {
776     // FIXME: Do we need to emit entries for funclet base states?
777
778     for (InvokeRange &I : invoke_ranges(FuncInfo, MBB)) {
779       assert(I.BeginLabel && I.EndLabel);
780       // If there was a potentially throwing call between this begin label and
781       // the last end label, we need an extra base state entry to indicate that
782       // those calls unwind directly to the caller.
783       if (I.SawPotentiallyThrowing && LastEHState != -1) {
784         IPToStateTable.push_back(
785             std::make_pair(getLabelPlusOne(LastEndLabel), -1));
786         LastEHState = -1;
787       }
788
789       // Emit an entry indicating that PCs after 'Label' have this EH state.
790       if (I.State != LastEHState)
791         IPToStateTable.push_back(
792             std::make_pair(create32bitRef(I.BeginLabel), I.State));
793       LastEHState = I.State;
794       LastEndLabel = I.EndLabel;
795     }
796   }
797
798   if (LastEndLabel != Asm->getFunctionBegin()) {
799     // Indicate that all calls from the last invoke until the epilogue unwind to
800     // caller. This also ensures that we have at least one ip2state entry, if
801     // somehow all invokes were deleted during CodeGen.
802     IPToStateTable.push_back(std::make_pair(getLabelPlusOne(LastEndLabel), -1));
803   }
804 }
805
806 void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
807                                                  StringRef FLinkageName) {
808   // Outlined helpers called by the EH runtime need to know the offset of the EH
809   // registration in order to recover the parent frame pointer. Now that we know
810   // we've code generated the parent, we can emit the label assignment that
811   // those helpers use to get the offset of the registration node.
812   assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
813          "no EH reg node localescape index");
814   MCSymbol *ParentFrameOffset =
815       Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
816   MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
817       FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
818   const MCExpr *RegistrationOffsetSymRef =
819       MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
820   Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
821 }
822
823 /// Emit the language-specific data that _except_handler3 and 4 expect. This is
824 /// functionally equivalent to the __C_specific_handler table, except it is
825 /// indexed by state number instead of IP.
826 void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
827   MCStreamer &OS = *Asm->OutStreamer;
828   const Function *F = MF->getFunction();
829   StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
830
831   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
832   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
833
834   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
835   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
836   OS.EmitValueToAlignment(4);
837   OS.EmitLabel(LSDALabel);
838
839   const Function *Per =
840       dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
841   StringRef PerName = Per->getName();
842   int BaseState = -1;
843   if (PerName == "_except_handler4") {
844     // The LSDA for _except_handler4 starts with this struct, followed by the
845     // scope table:
846     //
847     // struct EH4ScopeTable {
848     //   int32_t GSCookieOffset;
849     //   int32_t GSCookieXOROffset;
850     //   int32_t EHCookieOffset;
851     //   int32_t EHCookieXOROffset;
852     //   ScopeTableEntry ScopeRecord[];
853     // };
854     //
855     // Only the EHCookieOffset field appears to vary, and it appears to be the
856     // offset from the final saved SP value to the retaddr.
857     OS.EmitIntValue(-2, 4);
858     OS.EmitIntValue(0, 4);
859     // FIXME: Calculate.
860     OS.EmitIntValue(9999, 4);
861     OS.EmitIntValue(0, 4);
862     BaseState = -2;
863   }
864
865   if (!FuncInfo.SEHUnwindMap.empty()) {
866     for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
867       MCSymbol *ExceptOrFinally =
868           UME.Handler.get<MachineBasicBlock *>()->getSymbol();
869       OS.EmitIntValue(UME.ToState, 4);                  // ToState
870       OS.EmitValue(create32bitRef(UME.Filter), 4);      // Filter
871       OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
872     }
873     return;
874   }
875   // FIXME: The following code is for the old landingpad-based SEH
876   // implementation. Remove it when possible.
877
878   // Build a list of pointers to LandingPadInfos and then sort by WinEHState.
879   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
880   SmallVector<const LandingPadInfo *, 4> LPads;
881   LPads.reserve((PadInfos.size()));
882   for (const LandingPadInfo &LPInfo : PadInfos)
883     LPads.push_back(&LPInfo);
884   std::sort(LPads.begin(), LPads.end(),
885             [](const LandingPadInfo *L, const LandingPadInfo *R) {
886               return L->WinEHState < R->WinEHState;
887             });
888
889   // For each action in each lpad, emit one of these:
890   // struct ScopeTableEntry {
891   //   int32_t EnclosingLevel;
892   //   int32_t (__cdecl *Filter)();
893   //   void *HandlerOrFinally;
894   // };
895   //
896   // The "outermost" action will use BaseState as its enclosing level. Each
897   // other action will refer to the previous state as its enclosing level.
898   int CurState = 0;
899   for (const LandingPadInfo *LPInfo : LPads) {
900     int EnclosingLevel = BaseState;
901     assert(CurState + int(LPInfo->SEHHandlers.size()) - 1 ==
902                LPInfo->WinEHState &&
903            "gaps in the SEH scope table");
904     for (auto I = LPInfo->SEHHandlers.rbegin(), E = LPInfo->SEHHandlers.rend();
905          I != E; ++I) {
906       const SEHHandler &Handler = *I;
907       const BlockAddress *BA = Handler.RecoverBA;
908       const Function *F = Handler.FilterOrFinally;
909       assert(F && "cannot catch all in 32-bit SEH without filter function");
910       const MCExpr *FilterOrNull =
911           create32bitRef(BA ? Asm->getSymbol(F) : nullptr);
912       const MCExpr *ExceptOrFinally = create32bitRef(
913           BA ? Asm->GetBlockAddressSymbol(BA) : Asm->getSymbol(F));
914
915       OS.EmitIntValue(EnclosingLevel, 4);
916       OS.EmitValue(FilterOrNull, 4);
917       OS.EmitValue(ExceptOrFinally, 4);
918
919       // The next state unwinds to this state.
920       EnclosingLevel = CurState;
921       CurState++;
922     }
923   }
924 }