bd348f681c548521e811978400c9bd22a07fa433
[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 #include "llvm/Target/TargetSubtargetInfo.h"
42 using namespace llvm;
43
44 WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
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
50 WinException::~WinException() {}
51
52 /// endModule - Emit all exception information that should come after the
53 /// content.
54 void WinException::endModule() {
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
62 void WinException::beginFunction(const MachineFunction *MF) {
63   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
64
65   // If any landing pads survive, we need an EH table.
66   bool hasLandingPads = !MMI->getLandingPads().empty();
67   bool hasEHFunclets = MMI->hasEHFunclets();
68
69   const Function *F = MF->getFunction();
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   if (!Asm->MAI->usesWindowsCFI()) {
94     shouldEmitLSDA = hasEHFunclets;
95     shouldEmitPersonality = false;
96     return;
97   }
98
99   beginFunclet(MF->front(), Asm->CurrentFnSym);
100 }
101
102 /// endFunction - Gather and emit post-function exception information.
103 ///
104 void WinException::endFunction(const MachineFunction *MF) {
105   if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
106     return;
107
108   const Function *F = MF->getFunction();
109   EHPersonality Per = EHPersonality::Unknown;
110   if (F->hasPersonalityFn())
111     Per = classifyEHPersonality(F->getPersonalityFn());
112
113   // Get rid of any dead landing pads if we're not using funclets. In funclet
114   // schemes, the landing pad is not actually reachable. It only exists so
115   // that we can emit the right table data.
116   if (!isFuncletEHPersonality(Per))
117     MMI->TidyLandingPads();
118
119   endFunclet();
120
121   // endFunclet will emit the necessary .xdata tables for x64 SEH.
122   if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets())
123     return;
124
125   if (shouldEmitPersonality || shouldEmitLSDA) {
126     Asm->OutStreamer->PushSection();
127
128     // Just switch sections to the right xdata section. This use of CurrentFnSym
129     // assumes that we only emit the LSDA when ending the parent function.
130     MCSection *XData = WinEH::UnwindEmitter::getXDataSection(Asm->CurrentFnSym,
131                                                              Asm->OutContext);
132     Asm->OutStreamer->SwitchSection(XData);
133
134     // Emit the tables appropriate to the personality function in use. If we
135     // don't recognize the personality, assume it uses an Itanium-style LSDA.
136     if (Per == EHPersonality::MSVC_Win64SEH)
137       emitCSpecificHandlerTable(MF);
138     else if (Per == EHPersonality::MSVC_X86SEH)
139       emitExceptHandlerTable(MF);
140     else if (Per == EHPersonality::MSVC_CXX)
141       emitCXXFrameHandler3Table(MF);
142     else
143       emitExceptionTable();
144
145     Asm->OutStreamer->PopSection();
146   }
147 }
148
149 /// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock.
150 static MCSymbol *getMCSymbolForMBB(AsmPrinter *Asm,
151                                    const MachineBasicBlock *MBB) {
152   if (!MBB)
153     return nullptr;
154
155   assert(MBB->isEHFuncletEntry());
156
157   // Give catches and cleanups a name based off of their parent function and
158   // their funclet entry block's number.
159   const MachineFunction *MF = MBB->getParent();
160   const Function *F = MF->getFunction();
161   StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
162   MCContext &Ctx = MF->getContext();
163   StringRef HandlerPrefix = MBB->isCleanupFuncletEntry() ? "dtor" : "catch";
164   return Ctx.getOrCreateSymbol("?" + HandlerPrefix + "$" +
165                                Twine(MBB->getNumber()) + "@?0?" +
166                                FuncLinkageName + "@4HA");
167 }
168
169 void WinException::beginFunclet(const MachineBasicBlock &MBB,
170                                 MCSymbol *Sym) {
171   CurrentFuncletEntry = &MBB;
172
173   const Function *F = Asm->MF->getFunction();
174   // If a symbol was not provided for the funclet, invent one.
175   if (!Sym) {
176     Sym = getMCSymbolForMBB(Asm, &MBB);
177
178     // Describe our funclet symbol as a function with internal linkage.
179     Asm->OutStreamer->BeginCOFFSymbolDef(Sym);
180     Asm->OutStreamer->EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
181     Asm->OutStreamer->EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
182                                          << COFF::SCT_COMPLEX_TYPE_SHIFT);
183     Asm->OutStreamer->EndCOFFSymbolDef();
184
185     // We want our funclet's entry point to be aligned such that no nops will be
186     // present after the label.
187     Asm->EmitAlignment(std::max(Asm->MF->getAlignment(), MBB.getAlignment()),
188                        F);
189
190     // Now that we've emitted the alignment directive, point at our funclet.
191     Asm->OutStreamer->EmitLabel(Sym);
192   }
193
194   // Mark 'Sym' as starting our funclet.
195   if (shouldEmitMoves || shouldEmitPersonality)
196     Asm->OutStreamer->EmitWinCFIStartProc(Sym);
197
198   if (shouldEmitPersonality) {
199     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
200     const Function *PerFn = nullptr;
201
202     // Determine which personality routine we are using for this funclet.
203     if (F->hasPersonalityFn())
204       PerFn = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
205     const MCSymbol *PersHandlerSym =
206         TLOF.getCFIPersonalitySymbol(PerFn, *Asm->Mang, Asm->TM, MMI);
207
208     // Classify the personality routine so that we may reason about it.
209     EHPersonality Per = EHPersonality::Unknown;
210     if (F->hasPersonalityFn())
211       Per = classifyEHPersonality(F->getPersonalityFn());
212
213     // Do not emit a .seh_handler directive if it is a C++ cleanup funclet.
214     if (Per != EHPersonality::MSVC_CXX ||
215         !CurrentFuncletEntry->isCleanupFuncletEntry())
216       Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
217   }
218 }
219
220 void WinException::endFunclet() {
221   // No funclet to process?  Great, we have nothing to do.
222   if (!CurrentFuncletEntry)
223     return;
224
225   if (shouldEmitMoves || shouldEmitPersonality) {
226     const Function *F = Asm->MF->getFunction();
227     EHPersonality Per = EHPersonality::Unknown;
228     if (F->hasPersonalityFn())
229       Per = classifyEHPersonality(F->getPersonalityFn());
230
231     // The .seh_handlerdata directive implicitly switches section, push the
232     // current section so that we may return to it.
233     Asm->OutStreamer->PushSection();
234
235     // Emit an UNWIND_INFO struct describing the prologue.
236     Asm->OutStreamer->EmitWinEHHandlerData();
237
238     if (Per == EHPersonality::MSVC_CXX && shouldEmitPersonality &&
239         !CurrentFuncletEntry->isCleanupFuncletEntry()) {
240       // If this is a C++ catch funclet (or the parent function),
241       // emit a reference to the LSDA for the parent function.
242       StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
243       MCSymbol *FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
244           Twine("$cppxdata$", FuncLinkageName));
245       Asm->OutStreamer->EmitValue(create32bitRef(FuncInfoXData), 4);
246     } else if (Per == EHPersonality::MSVC_Win64SEH && MMI->hasEHFunclets() &&
247                !CurrentFuncletEntry->isEHFuncletEntry()) {
248       // If this is the parent function in Win64 SEH, emit the LSDA immediately
249       // following .seh_handlerdata.
250       emitCSpecificHandlerTable(Asm->MF);
251     }
252
253     // Switch back to the previous section now that we are done writing to
254     // .xdata.
255     Asm->OutStreamer->PopSection();
256
257     // Emit a .seh_endproc directive to mark the end of the function.
258     Asm->OutStreamer->EmitWinCFIEndProc();
259   }
260
261   // Let's make sure we don't try to end the same funclet twice.
262   CurrentFuncletEntry = nullptr;
263 }
264
265 const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
266   if (!Value)
267     return MCConstantExpr::create(0, Asm->OutContext);
268   return MCSymbolRefExpr::create(Value, useImageRel32
269                                             ? MCSymbolRefExpr::VK_COFF_IMGREL32
270                                             : MCSymbolRefExpr::VK_None,
271                                  Asm->OutContext);
272 }
273
274 const MCExpr *WinException::create32bitRef(const Value *V) {
275   if (!V)
276     return MCConstantExpr::create(0, Asm->OutContext);
277   if (const auto *GV = dyn_cast<GlobalValue>(V))
278     return create32bitRef(Asm->getSymbol(GV));
279   return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
280 }
281
282 const MCExpr *WinException::getLabelPlusOne(const MCSymbol *Label) {
283   return MCBinaryExpr::createAdd(create32bitRef(Label),
284                                  MCConstantExpr::create(1, Asm->OutContext),
285                                  Asm->OutContext);
286 }
287
288 int WinException::getFrameIndexOffset(int FrameIndex) {
289   const TargetFrameLowering &TFI = *Asm->MF->getSubtarget().getFrameLowering();
290   unsigned UnusedReg;
291   if (Asm->MAI->usesWindowsCFI())
292     return TFI.getFrameIndexReferenceFromSP(*Asm->MF, FrameIndex, UnusedReg);
293   return TFI.getFrameIndexReference(*Asm->MF, FrameIndex, UnusedReg);
294 }
295
296 namespace {
297
298 /// Top-level state used to represent unwind to caller
299 const int NullState = -1;
300
301 struct InvokeStateChange {
302   /// EH Label immediately after the last invoke in the previous state, or
303   /// nullptr if the previous state was the null state.
304   const MCSymbol *PreviousEndLabel;
305
306   /// EH label immediately before the first invoke in the new state, or nullptr
307   /// if the new state is the null state.
308   const MCSymbol *NewStartLabel;
309
310   /// State of the invoke following NewStartLabel, or NullState to indicate
311   /// the presence of calls which may unwind to caller.
312   int NewState;
313 };
314
315 /// Iterator that reports all the invoke state changes in a range of machine
316 /// basic blocks.  Changes to the null state are reported whenever a call that
317 /// may unwind to caller is encountered.  The MBB range is expected to be an
318 /// entire function or funclet, and the start and end of the range are treated
319 /// as being in the NullState even if there's not an unwind-to-caller call
320 /// before the first invoke or after the last one (i.e., the first state change
321 /// reported is the first change to something other than NullState, and a
322 /// change back to NullState is always reported at the end of iteration).
323 class InvokeStateChangeIterator {
324   InvokeStateChangeIterator(WinEHFuncInfo &EHInfo,
325                             MachineFunction::const_iterator MFI,
326                             MachineFunction::const_iterator MFE,
327                             MachineBasicBlock::const_iterator MBBI)
328       : EHInfo(EHInfo), MFI(MFI), MFE(MFE), MBBI(MBBI) {
329     LastStateChange.PreviousEndLabel = nullptr;
330     LastStateChange.NewStartLabel = nullptr;
331     LastStateChange.NewState = NullState;
332     scan();
333   }
334
335 public:
336   static iterator_range<InvokeStateChangeIterator>
337   range(WinEHFuncInfo &EHInfo, const MachineFunction &MF) {
338     // Reject empty MFs to simplify bookkeeping by ensuring that we can get the
339     // end of the last block.
340     assert(!MF.empty());
341     auto FuncBegin = MF.begin();
342     auto FuncEnd = MF.end();
343     auto BlockBegin = FuncBegin->begin();
344     auto BlockEnd = MF.back().end();
345     return make_range(
346         InvokeStateChangeIterator(EHInfo, FuncBegin, FuncEnd, BlockBegin),
347         InvokeStateChangeIterator(EHInfo, FuncEnd, FuncEnd, BlockEnd));
348   }
349   static iterator_range<InvokeStateChangeIterator>
350   range(WinEHFuncInfo &EHInfo, MachineFunction::const_iterator Begin,
351         MachineFunction::const_iterator End) {
352     // Reject empty ranges to simplify bookkeeping by ensuring that we can get
353     // the end of the last block.
354     assert(Begin != End);
355     auto BlockBegin = Begin->begin();
356     auto BlockEnd = std::prev(End)->end();
357     return make_range(InvokeStateChangeIterator(EHInfo, Begin, End, BlockBegin),
358                       InvokeStateChangeIterator(EHInfo, End, End, BlockEnd));
359   }
360
361   // Iterator methods.
362   bool operator==(const InvokeStateChangeIterator &O) const {
363     // Must be visiting same block.
364     if (MFI != O.MFI)
365       return false;
366     // Must be visiting same isntr.
367     if (MBBI != O.MBBI)
368       return false;
369     // At end of block/instr iteration, we can still have two distinct states:
370     // one to report the final EndLabel, and another indicating the end of the
371     // state change iteration.  Check for CurrentEndLabel equality to
372     // distinguish these.
373     return CurrentEndLabel == O.CurrentEndLabel;
374   }
375
376   bool operator!=(const InvokeStateChangeIterator &O) const {
377     return !operator==(O);
378   }
379   InvokeStateChange &operator*() { return LastStateChange; }
380   InvokeStateChange *operator->() { return &LastStateChange; }
381   InvokeStateChangeIterator &operator++() { return scan(); }
382
383 private:
384   InvokeStateChangeIterator &scan();
385
386   WinEHFuncInfo &EHInfo;
387   const MCSymbol *CurrentEndLabel = nullptr;
388   MachineFunction::const_iterator MFI;
389   MachineFunction::const_iterator MFE;
390   MachineBasicBlock::const_iterator MBBI;
391   InvokeStateChange LastStateChange;
392   bool VisitingInvoke = false;
393 };
394
395 } // end anonymous namespace
396
397 InvokeStateChangeIterator &InvokeStateChangeIterator::scan() {
398   bool IsNewBlock = false;
399   for (; MFI != MFE; ++MFI, IsNewBlock = true) {
400     if (IsNewBlock)
401       MBBI = MFI->begin();
402     for (auto MBBE = MFI->end(); MBBI != MBBE; ++MBBI) {
403       const MachineInstr &MI = *MBBI;
404       if (!VisitingInvoke && LastStateChange.NewState != NullState &&
405           MI.isCall() && !EHStreamer::callToNoUnwindFunction(&MI)) {
406         // Indicate a change of state to the null state.  We don't have
407         // start/end EH labels handy but the caller won't expect them for
408         // null state regions.
409         LastStateChange.PreviousEndLabel = CurrentEndLabel;
410         LastStateChange.NewStartLabel = nullptr;
411         LastStateChange.NewState = NullState;
412         CurrentEndLabel = nullptr;
413         // Don't re-visit this instr on the next scan
414         ++MBBI;
415         return *this;
416       }
417
418       // All other state changes are at EH labels before/after invokes.
419       if (!MI.isEHLabel())
420         continue;
421       MCSymbol *Label = MI.getOperand(0).getMCSymbol();
422       if (Label == CurrentEndLabel) {
423         VisitingInvoke = false;
424         continue;
425       }
426       auto InvokeMapIter = EHInfo.InvokeToStateMap.find(Label);
427       // Ignore EH labels that aren't the ones inserted before an invoke
428       if (InvokeMapIter == EHInfo.InvokeToStateMap.end())
429         continue;
430       auto &StateAndEnd = InvokeMapIter->second;
431       int NewState = StateAndEnd.first;
432       // Ignore EH labels explicitly annotated with the null state (which
433       // can happen for invokes that unwind to a chain of endpads the last
434       // of which unwinds to caller).  We'll see the subsequent invoke and
435       // report a transition to the null state same as we do for calls.
436       if (NewState == NullState)
437         continue;
438       // Keep track of the fact that we're between EH start/end labels so
439       // we know not to treat the inoke we'll see as unwinding to caller.
440       VisitingInvoke = true;
441       if (NewState == LastStateChange.NewState) {
442         // The state isn't actually changing here.  Record the new end and
443         // keep going.
444         CurrentEndLabel = StateAndEnd.second;
445         continue;
446       }
447       // Found a state change to report
448       LastStateChange.PreviousEndLabel = CurrentEndLabel;
449       LastStateChange.NewStartLabel = Label;
450       LastStateChange.NewState = NewState;
451       // Start keeping track of the new current end
452       CurrentEndLabel = StateAndEnd.second;
453       // Don't re-visit this instr on the next scan
454       ++MBBI;
455       return *this;
456     }
457   }
458   // Iteration hit the end of the block range.
459   if (LastStateChange.NewState != NullState) {
460     // Report the end of the last new state
461     LastStateChange.PreviousEndLabel = CurrentEndLabel;
462     LastStateChange.NewStartLabel = nullptr;
463     LastStateChange.NewState = NullState;
464     // Leave CurrentEndLabel non-null to distinguish this state from end.
465     assert(CurrentEndLabel != nullptr);
466     return *this;
467   }
468   // We've reported all state changes and hit the end state.
469   CurrentEndLabel = nullptr;
470   return *this;
471 }
472
473 /// Emit the language-specific data that __C_specific_handler expects.  This
474 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
475 /// up after faults with __try, __except, and __finally.  The typeinfo values
476 /// are not really RTTI data, but pointers to filter functions that return an
477 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
478 /// blocks and other cleanups, the landing pad label is zero, and the filter
479 /// function is actually a cleanup handler with the same prototype.  A catch-all
480 /// entry is modeled with a null filter function field and a non-zero landing
481 /// pad label.
482 ///
483 /// Possible filter function return values:
484 ///   EXCEPTION_EXECUTE_HANDLER (1):
485 ///     Jump to the landing pad label after cleanups.
486 ///   EXCEPTION_CONTINUE_SEARCH (0):
487 ///     Continue searching this table or continue unwinding.
488 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
489 ///     Resume execution at the trapping PC.
490 ///
491 /// Inferred table structure:
492 ///   struct Table {
493 ///     int NumEntries;
494 ///     struct Entry {
495 ///       imagerel32 LabelStart;
496 ///       imagerel32 LabelEnd;
497 ///       imagerel32 FilterOrFinally;  // One means catch-all.
498 ///       imagerel32 LabelLPad;        // Zero means __finally.
499 ///     } Entries[NumEntries];
500 ///   };
501 void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
502   auto &OS = *Asm->OutStreamer;
503   MCContext &Ctx = Asm->OutContext;
504
505   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
506   // Use the assembler to compute the number of table entries through label
507   // difference and division.
508   MCSymbol *TableBegin =
509       Ctx.createTempSymbol("lsda_begin", /*AlwaysAddSuffix=*/true);
510   MCSymbol *TableEnd =
511       Ctx.createTempSymbol("lsda_end", /*AlwaysAddSuffix=*/true);
512   const MCExpr *LabelDiff =
513       MCBinaryExpr::createSub(MCSymbolRefExpr::create(TableEnd, Ctx),
514                               MCSymbolRefExpr::create(TableBegin, Ctx), Ctx);
515   const MCExpr *EntrySize = MCConstantExpr::create(16, Ctx);
516   const MCExpr *EntryCount = MCBinaryExpr::createDiv(LabelDiff, EntrySize, Ctx);
517   OS.EmitValue(EntryCount, 4);
518
519   OS.EmitLabel(TableBegin);
520
521   // Iterate over all the invoke try ranges. Unlike MSVC, LLVM currently only
522   // models exceptions from invokes. LLVM also allows arbitrary reordering of
523   // the code, so our tables end up looking a bit different. Rather than
524   // trying to match MSVC's tables exactly, we emit a denormalized table.  For
525   // each range of invokes in the same state, we emit table entries for all
526   // the actions that would be taken in that state. This means our tables are
527   // slightly bigger, which is OK.
528   const MCSymbol *LastStartLabel = nullptr;
529   int LastEHState = -1;
530   // Break out before we enter into a finally funclet.
531   // FIXME: We need to emit separate EH tables for cleanups.
532   MachineFunction::const_iterator End = MF->end();
533   MachineFunction::const_iterator Stop = std::next(MF->begin());
534   while (Stop != End && !Stop->isEHFuncletEntry())
535     ++Stop;
536   for (const auto &StateChange :
537        InvokeStateChangeIterator::range(FuncInfo, MF->begin(), Stop)) {
538     // Emit all the actions for the state we just transitioned out of
539     // if it was not the null state
540     if (LastEHState != -1)
541       emitSEHActionsForRange(FuncInfo, LastStartLabel,
542                              StateChange.PreviousEndLabel, LastEHState);
543     LastStartLabel = StateChange.NewStartLabel;
544     LastEHState = StateChange.NewState;
545   }
546
547   OS.EmitLabel(TableEnd);
548 }
549
550 void WinException::emitSEHActionsForRange(WinEHFuncInfo &FuncInfo,
551                                           const MCSymbol *BeginLabel,
552                                           const MCSymbol *EndLabel, int State) {
553   auto &OS = *Asm->OutStreamer;
554   MCContext &Ctx = Asm->OutContext;
555
556   assert(BeginLabel && EndLabel);
557   while (State != -1) {
558     SEHUnwindMapEntry &UME = FuncInfo.SEHUnwindMap[State];
559     const MCExpr *FilterOrFinally;
560     const MCExpr *ExceptOrNull;
561     auto *Handler = UME.Handler.get<MachineBasicBlock *>();
562     if (UME.IsFinally) {
563       FilterOrFinally = create32bitRef(getMCSymbolForMBB(Asm, Handler));
564       ExceptOrNull = MCConstantExpr::create(0, Ctx);
565     } else {
566       // For an except, the filter can be 1 (catch-all) or a function
567       // label.
568       FilterOrFinally = UME.Filter ? create32bitRef(UME.Filter)
569                                    : MCConstantExpr::create(1, Ctx);
570       ExceptOrNull = create32bitRef(Handler->getSymbol());
571     }
572
573     OS.EmitValue(getLabelPlusOne(BeginLabel), 4);
574     OS.EmitValue(getLabelPlusOne(EndLabel), 4);
575     OS.EmitValue(FilterOrFinally, 4);
576     OS.EmitValue(ExceptOrNull, 4);
577
578     assert(UME.ToState < State && "states should decrease");
579     State = UME.ToState;
580   }
581 }
582
583 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
584   const Function *F = MF->getFunction();
585   auto &OS = *Asm->OutStreamer;
586   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
587
588   StringRef FuncLinkageName = GlobalValue::getRealLinkageName(F->getName());
589
590   SmallVector<std::pair<const MCExpr *, int>, 4> IPToStateTable;
591   MCSymbol *FuncInfoXData = nullptr;
592   if (shouldEmitPersonality) {
593     // If we're 64-bit, emit a pointer to the C++ EH data, and build a map from
594     // IPs to state numbers.
595     FuncInfoXData =
596         Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", FuncLinkageName));
597     computeIP2StateTable(MF, FuncInfo, IPToStateTable);
598   } else {
599     FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(FuncLinkageName);
600     emitEHRegistrationOffsetLabel(FuncInfo, FuncLinkageName);
601   }
602
603   int UnwindHelpOffset = 0;
604   if (Asm->MAI->usesWindowsCFI())
605     UnwindHelpOffset = getFrameIndexOffset(FuncInfo.UnwindHelpFrameIdx);
606
607   MCSymbol *UnwindMapXData = nullptr;
608   MCSymbol *TryBlockMapXData = nullptr;
609   MCSymbol *IPToStateXData = nullptr;
610   if (!FuncInfo.CxxUnwindMap.empty())
611     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
612         Twine("$stateUnwindMap$", FuncLinkageName));
613   if (!FuncInfo.TryBlockMap.empty())
614     TryBlockMapXData =
615         Asm->OutContext.getOrCreateSymbol(Twine("$tryMap$", FuncLinkageName));
616   if (!IPToStateTable.empty())
617     IPToStateXData =
618         Asm->OutContext.getOrCreateSymbol(Twine("$ip2state$", FuncLinkageName));
619
620   // FuncInfo {
621   //   uint32_t           MagicNumber
622   //   int32_t            MaxState;
623   //   UnwindMapEntry    *UnwindMap;
624   //   uint32_t           NumTryBlocks;
625   //   TryBlockMapEntry  *TryBlockMap;
626   //   uint32_t           IPMapEntries; // always 0 for x86
627   //   IPToStateMapEntry *IPToStateMap; // always 0 for x86
628   //   uint32_t           UnwindHelp;   // non-x86 only
629   //   ESTypeList        *ESTypeList;
630   //   int32_t            EHFlags;
631   // }
632   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
633   // EHFlags & 2 -> ???
634   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
635   OS.EmitValueToAlignment(4);
636   OS.EmitLabel(FuncInfoXData);
637   OS.EmitIntValue(0x19930522, 4);                      // MagicNumber
638   OS.EmitIntValue(FuncInfo.CxxUnwindMap.size(), 4);       // MaxState
639   OS.EmitValue(create32bitRef(UnwindMapXData), 4);     // UnwindMap
640   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);     // NumTryBlocks
641   OS.EmitValue(create32bitRef(TryBlockMapXData), 4);   // TryBlockMap
642   OS.EmitIntValue(IPToStateTable.size(), 4);           // IPMapEntries
643   OS.EmitValue(create32bitRef(IPToStateXData), 4);     // IPToStateMap
644   if (Asm->MAI->usesWindowsCFI())
645     OS.EmitIntValue(UnwindHelpOffset, 4);              // UnwindHelp
646   OS.EmitIntValue(0, 4);                               // ESTypeList
647   OS.EmitIntValue(1, 4);                               // EHFlags
648
649   // UnwindMapEntry {
650   //   int32_t ToState;
651   //   void  (*Action)();
652   // };
653   if (UnwindMapXData) {
654     OS.EmitLabel(UnwindMapXData);
655     for (const CxxUnwindMapEntry &UME : FuncInfo.CxxUnwindMap) {
656       MCSymbol *CleanupSym =
657           getMCSymbolForMBB(Asm, UME.Cleanup.dyn_cast<MachineBasicBlock *>());
658       OS.EmitIntValue(UME.ToState, 4);             // ToState
659       OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
660     }
661   }
662
663   // TryBlockMap {
664   //   int32_t      TryLow;
665   //   int32_t      TryHigh;
666   //   int32_t      CatchHigh;
667   //   int32_t      NumCatches;
668   //   HandlerType *HandlerArray;
669   // };
670   if (TryBlockMapXData) {
671     OS.EmitLabel(TryBlockMapXData);
672     SmallVector<MCSymbol *, 1> HandlerMaps;
673     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
674       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
675
676       MCSymbol *HandlerMapXData = nullptr;
677       if (!TBME.HandlerArray.empty())
678         HandlerMapXData =
679             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
680                                                   .concat(Twine(I))
681                                                   .concat("$")
682                                                   .concat(FuncLinkageName));
683       HandlerMaps.push_back(HandlerMapXData);
684
685       // TBMEs should form intervals.
686       assert(0 <= TBME.TryLow && "bad trymap interval");
687       assert(TBME.TryLow <= TBME.TryHigh && "bad trymap interval");
688       assert(TBME.TryHigh < TBME.CatchHigh && "bad trymap interval");
689       assert(TBME.CatchHigh < int(FuncInfo.CxxUnwindMap.size()) &&
690              "bad trymap interval");
691
692       OS.EmitIntValue(TBME.TryLow, 4);                    // TryLow
693       OS.EmitIntValue(TBME.TryHigh, 4);                   // TryHigh
694       OS.EmitIntValue(TBME.CatchHigh, 4);                 // CatchHigh
695       OS.EmitIntValue(TBME.HandlerArray.size(), 4);       // NumCatches
696       OS.EmitValue(create32bitRef(HandlerMapXData), 4);   // HandlerArray
697     }
698
699     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
700       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
701       MCSymbol *HandlerMapXData = HandlerMaps[I];
702       if (!HandlerMapXData)
703         continue;
704       // HandlerType {
705       //   int32_t         Adjectives;
706       //   TypeDescriptor *Type;
707       //   int32_t         CatchObjOffset;
708       //   void          (*Handler)();
709       //   int32_t         ParentFrameOffset; // x64 only
710       // };
711       OS.EmitLabel(HandlerMapXData);
712       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
713         // Get the frame escape label with the offset of the catch object. If
714         // the index is INT_MAX, then there is no catch object, and we should
715         // emit an offset of zero, indicating that no copy will occur.
716         const MCExpr *FrameAllocOffsetRef = nullptr;
717         if (HT.CatchObj.FrameIndex != INT_MAX) {
718           int Offset = getFrameIndexOffset(HT.CatchObj.FrameIndex);
719           // For 32-bit, the catch object offset is relative to the end of the
720           // EH registration node. For 64-bit, it's relative to SP at the end of
721           // the prologue.
722           if (!shouldEmitPersonality) {
723             assert(FuncInfo.EHRegNodeEndOffset != INT_MAX);
724             Offset += FuncInfo.EHRegNodeEndOffset;
725           }
726           FrameAllocOffsetRef = MCConstantExpr::create(Offset, Asm->OutContext);
727         } else {
728           FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
729         }
730
731         MCSymbol *HandlerSym =
732             getMCSymbolForMBB(Asm, HT.Handler.dyn_cast<MachineBasicBlock *>());
733
734         OS.EmitIntValue(HT.Adjectives, 4);                  // Adjectives
735         OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
736         OS.EmitValue(FrameAllocOffsetRef, 4);               // CatchObjOffset
737         OS.EmitValue(create32bitRef(HandlerSym), 4);        // Handler
738
739         if (shouldEmitPersonality) {
740           // Keep this in sync with X86FrameLowering::emitPrologue.
741           int ParentFrameOffset =
742               16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
743           OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
744         }
745       }
746     }
747   }
748
749   // IPToStateMapEntry {
750   //   void   *IP;
751   //   int32_t State;
752   // };
753   if (IPToStateXData) {
754     OS.EmitLabel(IPToStateXData);
755     for (auto &IPStatePair : IPToStateTable) {
756       OS.EmitValue(IPStatePair.first, 4);     // IP
757       OS.EmitIntValue(IPStatePair.second, 4); // State
758     }
759   }
760 }
761
762 void WinException::computeIP2StateTable(
763     const MachineFunction *MF, WinEHFuncInfo &FuncInfo,
764     SmallVectorImpl<std::pair<const MCExpr *, int>> &IPToStateTable) {
765   // Indicate that all calls from the prologue to the first invoke unwind to
766   // caller. We handle this as a special case since other ranges starting at end
767   // labels need to use LtmpN+1.
768   MCSymbol *StartLabel = Asm->getFunctionBegin();
769   assert(StartLabel && "need local function start label");
770   IPToStateTable.push_back(std::make_pair(create32bitRef(StartLabel), -1));
771
772   // FIXME: Do we need to emit entries for funclet base states?
773   for (const auto &StateChange :
774        InvokeStateChangeIterator::range(FuncInfo, *MF)) {
775     // Compute the label to report as the start of this entry; use the EH start
776     // label for the invoke if we have one, otherwise (this is a call which may
777     // unwind to our caller and does not have an EH start label, so) use the
778     // previous end label.
779     const MCSymbol *ChangeLabel = StateChange.NewStartLabel;
780     if (!ChangeLabel)
781       ChangeLabel = StateChange.PreviousEndLabel;
782     // Emit an entry indicating that PCs after 'Label' have this EH state.
783     IPToStateTable.push_back(
784         std::make_pair(getLabelPlusOne(ChangeLabel), StateChange.NewState));
785   }
786 }
787
788 void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
789                                                  StringRef FLinkageName) {
790   // Outlined helpers called by the EH runtime need to know the offset of the EH
791   // registration in order to recover the parent frame pointer. Now that we know
792   // we've code generated the parent, we can emit the label assignment that
793   // those helpers use to get the offset of the registration node.
794   assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
795          "no EH reg node localescape index");
796   MCSymbol *ParentFrameOffset =
797       Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
798   MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
799       FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
800   const MCExpr *RegistrationOffsetSymRef =
801       MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
802   Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
803 }
804
805 /// Emit the language-specific data that _except_handler3 and 4 expect. This is
806 /// functionally equivalent to the __C_specific_handler table, except it is
807 /// indexed by state number instead of IP.
808 void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
809   MCStreamer &OS = *Asm->OutStreamer;
810   const Function *F = MF->getFunction();
811   StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
812
813   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
814   emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
815
816   // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
817   MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
818   OS.EmitValueToAlignment(4);
819   OS.EmitLabel(LSDALabel);
820
821   const Function *Per =
822       dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
823   StringRef PerName = Per->getName();
824   int BaseState = -1;
825   if (PerName == "_except_handler4") {
826     // The LSDA for _except_handler4 starts with this struct, followed by the
827     // scope table:
828     //
829     // struct EH4ScopeTable {
830     //   int32_t GSCookieOffset;
831     //   int32_t GSCookieXOROffset;
832     //   int32_t EHCookieOffset;
833     //   int32_t EHCookieXOROffset;
834     //   ScopeTableEntry ScopeRecord[];
835     // };
836     //
837     // Only the EHCookieOffset field appears to vary, and it appears to be the
838     // offset from the final saved SP value to the retaddr.
839     OS.EmitIntValue(-2, 4);
840     OS.EmitIntValue(0, 4);
841     // FIXME: Calculate.
842     OS.EmitIntValue(9999, 4);
843     OS.EmitIntValue(0, 4);
844     BaseState = -2;
845   }
846
847   assert(!FuncInfo.SEHUnwindMap.empty());
848   for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
849     MCSymbol *ExceptOrFinally =
850         UME.Handler.get<MachineBasicBlock *>()->getSymbol();
851     // -1 is usually the base state for "unwind to caller", but for
852     // _except_handler4 it's -2. Do that replacement here if necessary.
853     int ToState = UME.ToState == -1 ? BaseState : UME.ToState;
854     OS.EmitIntValue(ToState, 4);                      // ToState
855     OS.EmitValue(create32bitRef(UME.Filter), 4);      // Filter
856     OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
857   }
858 }