blob: 095315809cb0a2d2c71c9d3688cf4704440b5516 [file] [log] [blame]
Reid Kleckner60b640b2015-05-28 22:47:01 +00001//===-- CodeGen/AsmPrinter/WinException.cpp - Dwarf Exception Impl ------===//
Charles Davis91ed7992011-05-27 23:47:32 +00002//
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
Reid Kleckner60b640b2015-05-28 22:47:01 +000014#include "WinException.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallString.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/ADT/Twine.h"
Charles Davis91ed7992011-05-27 23:47:32 +000018#include "llvm/CodeGen/AsmPrinter.h"
Charles Davis91ed7992011-05-27 23:47:32 +000019#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000022#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000024#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Module.h"
Charles Davis91ed7992011-05-27 23:47:32 +000026#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"
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000032#include "llvm/MC/MCWin64EH.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/Dwarf.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/FormattedStream.h"
Charles Davis91ed7992011-05-27 23:47:32 +000036#include "llvm/Target/TargetFrameLowering.h"
37#include "llvm/Target/TargetLoweringObjectFile.h"
Charles Davis91ed7992011-05-27 23:47:32 +000038#include "llvm/Target/TargetOptions.h"
39#include "llvm/Target/TargetRegisterInfo.h"
Charles Davis91ed7992011-05-27 23:47:32 +000040using namespace llvm;
41
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000042WinException::WinException(AsmPrinter *A) : EHStreamer(A) {
43 // MSVC's EH tables are always composed of 32-bit words. All known 64-bit
44 // platforms use an imagerel32 relocation to refer to symbols.
45 useImageRel32 = (A->getDataLayout().getPointerSizeInBits() == 64);
46}
Charles Davis91ed7992011-05-27 23:47:32 +000047
Reid Kleckner60b640b2015-05-28 22:47:01 +000048WinException::~WinException() {}
Charles Davis91ed7992011-05-27 23:47:32 +000049
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +000050/// endModule - Emit all exception information that should come after the
Charles Davis91ed7992011-05-27 23:47:32 +000051/// content.
Reid Kleckner60b640b2015-05-28 22:47:01 +000052void WinException::endModule() {
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000053 auto &OS = *Asm->OutStreamer;
54 const Module *M = MMI->getModule();
Reid Klecknerca6ef662015-06-10 01:13:44 +000055 for (const Function &F : *M)
56 if (F.hasFnAttribute("safeseh"))
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000057 OS.EmitCOFFSafeSEH(Asm->getSymbol(&F));
Charles Davis91ed7992011-05-27 23:47:32 +000058}
59
Reid Kleckner60b640b2015-05-28 22:47:01 +000060void WinException::beginFunction(const MachineFunction *MF) {
Charles Davis5638b9f2011-05-28 04:21:04 +000061 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
62
63 // If any landing pads survive, we need an EH table.
64 bool hasLandingPads = !MMI->getLandingPads().empty();
Reid Kleckner0e288232015-08-27 23:27:47 +000065 bool hasEHFunclets = MMI->hasEHFunclets();
Charles Davis5638b9f2011-05-28 04:21:04 +000066
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000067 const Function *F = MF->getFunction();
68 const Function *ParentF = MMI->getWinEHParent(F);
69
Charles Davis5638b9f2011-05-28 04:21:04 +000070 shouldEmitMoves = Asm->needsSEHMoves();
71
72 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
73 unsigned PerEncoding = TLOF.getPersonalityEncoding();
Reid Kleckner9a1a9192015-07-13 20:41:46 +000074 const Function *Per = nullptr;
75 if (F->hasPersonalityFn())
76 Per = dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Charles Davis5638b9f2011-05-28 04:21:04 +000077
Keno Fischeraff703a2015-07-14 19:22:51 +000078 bool forceEmitPersonality =
79 F->hasPersonalityFn() && !isNoOpWithoutInvoke(classifyEHPersonality(Per)) &&
80 F->needsUnwindTableEntry();
81
Reid Kleckner0e288232015-08-27 23:27:47 +000082 shouldEmitPersonality =
83 forceEmitPersonality || ((hasLandingPads || hasEHFunclets) &&
84 PerEncoding != dwarf::DW_EH_PE_omit && Per);
Charles Davis5638b9f2011-05-28 04:21:04 +000085
86 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
87 shouldEmitLSDA = shouldEmitPersonality &&
88 LSDAEncoding != dwarf::DW_EH_PE_omit;
89
Reid Kleckner0e288232015-08-27 23:27:47 +000090 // If we're not using CFI, we don't want the CFI or the personality, but we
91 // might want EH tables if we had EH pads.
92 // FIXME: If WinEHPrepare outlined something, we should emit the LSDA. Remove
93 // this once WinEHPrepare stops doing that.
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000094 if (!Asm->MAI->usesWindowsCFI()) {
Reid Kleckner0e288232015-08-27 23:27:47 +000095 shouldEmitLSDA =
96 hasEHFunclets || (F->hasFnAttribute("wineh-parent") && F == ParentF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +000097 shouldEmitPersonality = false;
98 return;
99 }
David Majnemera225a192015-03-31 22:35:44 +0000100
101 // If this was an outlined handler, we need to define the label corresponding
102 // to the offset of the parent frame relative to the stack pointer after the
103 // prologue.
David Majnemera225a192015-03-31 22:35:44 +0000104 if (F != ParentF) {
105 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
106 auto I = FuncInfo.CatchHandlerParentFrameObjOffset.find(F);
107 if (I != FuncInfo.CatchHandlerParentFrameObjOffset.end()) {
108 MCSymbol *HandlerTypeParentFrameOffset =
109 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(
110 GlobalValue::getRealLinkageName(F->getName()));
111
112 // Emit a symbol assignment.
Lang Hames9ff69c82015-04-24 19:11:51 +0000113 Asm->OutStreamer->EmitAssignment(
David Majnemera225a192015-03-31 22:35:44 +0000114 HandlerTypeParentFrameOffset,
Jim Grosbach13760bd2015-05-30 01:25:56 +0000115 MCConstantExpr::create(I->second, Asm->OutContext));
David Majnemera225a192015-03-31 22:35:44 +0000116 }
117 }
118
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000119 if (shouldEmitMoves || shouldEmitPersonality)
120 Asm->OutStreamer->EmitWinCFIStartProc(Asm->CurrentFnSym);
Charles Davis5638b9f2011-05-28 04:21:04 +0000121
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000122 if (shouldEmitPersonality) {
123 const MCSymbol *PersHandlerSym =
124 TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
125 Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
126 }
Charles Davis91ed7992011-05-27 23:47:32 +0000127}
128
Timur Iskhodzhanov119f3072013-11-26 13:34:55 +0000129/// endFunction - Gather and emit post-function exception information.
Charles Davis91ed7992011-05-27 23:47:32 +0000130///
Reid Kleckner60b640b2015-05-28 22:47:01 +0000131void WinException::endFunction(const MachineFunction *MF) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000132 if (!shouldEmitPersonality && !shouldEmitMoves && !shouldEmitLSDA)
Charles Davis5638b9f2011-05-28 04:21:04 +0000133 return;
134
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000135 const Function *F = MF->getFunction();
136 EHPersonality Per = EHPersonality::Unknown;
137 if (F->hasPersonalityFn())
138 Per = classifyEHPersonality(F->getPersonalityFn());
Reid Kleckner3e9fadf2015-04-15 18:48:15 +0000139
140 // Get rid of any dead landing pads if we're not using a Windows EH scheme. In
141 // Windows EH schemes, the landing pad is not actually reachable. It only
142 // exists so that we can emit the right table data.
143 if (!isMSVCEHPersonality(Per))
144 MMI->TidyLandingPads();
Charles Davisa5752262011-05-30 00:13:34 +0000145
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000146 if (shouldEmitPersonality || shouldEmitLSDA) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000147 Asm->OutStreamer->PushSection();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000148
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000149 if (shouldEmitMoves || shouldEmitPersonality) {
150 // Emit an UNWIND_INFO struct describing the prologue.
151 Asm->OutStreamer->EmitWinEHHandlerData();
152 } else {
153 // Just switch sections to the right xdata section. This use of
154 // CurrentFnSym assumes that we only emit the LSDA when ending the parent
155 // function.
156 MCSection *XData = WinEH::UnwindEmitter::getXDataSection(
157 Asm->CurrentFnSym, Asm->OutContext);
158 Asm->OutStreamer->SwitchSection(XData);
159 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000160
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000161 // Emit the tables appropriate to the personality function in use. If we
162 // don't recognize the personality, assume it uses an Itanium-style LSDA.
Reid Kleckner2d5fb682015-02-14 00:21:02 +0000163 if (Per == EHPersonality::MSVC_Win64SEH)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000164 emitCSpecificHandlerTable(MF);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000165 else if (Per == EHPersonality::MSVC_X86SEH)
Reid Klecknerf12c0302015-06-09 21:42:19 +0000166 emitExceptHandlerTable(MF);
David Majnemercde33032015-03-30 22:58:10 +0000167 else if (Per == EHPersonality::MSVC_CXX)
168 emitCXXFrameHandler3Table(MF);
Reid Kleckner9b5eaf02015-01-14 18:50:10 +0000169 else
Reid Kleckner0a57f652015-01-14 01:05:27 +0000170 emitExceptionTable();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000171
Lang Hames9ff69c82015-04-24 19:11:51 +0000172 Asm->OutStreamer->PopSection();
Charles Davisa5752262011-05-30 00:13:34 +0000173 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000174
175 if (shouldEmitMoves)
176 Asm->OutStreamer->EmitWinCFIEndProc();
Charles Davis91ed7992011-05-27 23:47:32 +0000177}
Reid Kleckner0a57f652015-01-14 01:05:27 +0000178
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000179const MCExpr *WinException::create32bitRef(const MCSymbol *Value) {
David Majnemercde33032015-03-30 22:58:10 +0000180 if (!Value)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000181 return MCConstantExpr::create(0, Asm->OutContext);
182 return MCSymbolRefExpr::create(Value, useImageRel32
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000183 ? MCSymbolRefExpr::VK_COFF_IMGREL32
184 : MCSymbolRefExpr::VK_None,
Reid Kleckner0a57f652015-01-14 01:05:27 +0000185 Asm->OutContext);
186}
187
David Majnemer0ad363e2015-08-18 19:07:12 +0000188const MCExpr *WinException::create32bitRef(const Value *V) {
189 if (!V)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000190 return MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner0e288232015-08-27 23:27:47 +0000191 // FIXME: Delete the GlobalValue case once the new IR is fully functional.
192 if (const auto *GV = dyn_cast<GlobalValue>(V))
193 return create32bitRef(Asm->getSymbol(GV));
194 return create32bitRef(MMI->getAddrLabelSymbol(cast<BasicBlock>(V)));
David Majnemercde33032015-03-30 22:58:10 +0000195}
196
Reid Kleckner0a57f652015-01-14 01:05:27 +0000197/// Emit the language-specific data that __C_specific_handler expects. This
198/// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
199/// up after faults with __try, __except, and __finally. The typeinfo values
200/// are not really RTTI data, but pointers to filter functions that return an
201/// integer (1, 0, or -1) indicating how to handle the exception. For __finally
202/// blocks and other cleanups, the landing pad label is zero, and the filter
203/// function is actually a cleanup handler with the same prototype. A catch-all
204/// entry is modeled with a null filter function field and a non-zero landing
205/// pad label.
206///
207/// Possible filter function return values:
208/// EXCEPTION_EXECUTE_HANDLER (1):
209/// Jump to the landing pad label after cleanups.
210/// EXCEPTION_CONTINUE_SEARCH (0):
211/// Continue searching this table or continue unwinding.
212/// EXCEPTION_CONTINUE_EXECUTION (-1):
213/// Resume execution at the trapping PC.
214///
215/// Inferred table structure:
216/// struct Table {
217/// int NumEntries;
218/// struct Entry {
219/// imagerel32 LabelStart;
220/// imagerel32 LabelEnd;
Reid Klecknerf690f502015-01-22 02:27:44 +0000221/// imagerel32 FilterOrFinally; // One means catch-all.
Reid Kleckner0a57f652015-01-14 01:05:27 +0000222/// imagerel32 LabelLPad; // Zero means __finally.
223/// } Entries[NumEntries];
224/// };
Reid Kleckner94b704c2015-09-09 21:10:03 +0000225void WinException::emitCSpecificHandlerTable(const MachineFunction *MF) {
Reid Kleckner0a57f652015-01-14 01:05:27 +0000226 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
227
Reid Kleckner94b704c2015-09-09 21:10:03 +0000228 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(MF->getFunction());
229 if (!FuncInfo.SEHUnwindMap.empty())
230 report_fatal_error("x64 SEH tables not yet implemented");
231
Reid Kleckner0a57f652015-01-14 01:05:27 +0000232 // Simplifying assumptions for first implementation:
233 // - Cleanups are not implemented.
234 // - Filters are not implemented.
235
236 // The Itanium LSDA table sorts similar landing pads together to simplify the
237 // actions table, but we don't need that.
238 SmallVector<const LandingPadInfo *, 64> LandingPads;
239 LandingPads.reserve(PadInfos.size());
240 for (const auto &LP : PadInfos)
241 LandingPads.push_back(&LP);
242
243 // Compute label ranges for call sites as we would for the Itanium LSDA, but
244 // use an all zero action table because we aren't using these actions.
245 SmallVector<unsigned, 64> FirstActions;
246 FirstActions.resize(LandingPads.size());
247 SmallVector<CallSiteEntry, 64> CallSites;
248 computeCallSiteTable(CallSites, LandingPads, FirstActions);
249
Rafael Espindola629cdba2015-02-27 18:18:39 +0000250 MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
251 MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000252
253 // Emit the number of table entries.
254 unsigned NumEntries = 0;
255 for (const CallSiteEntry &CSE : CallSites) {
256 if (!CSE.LPad)
257 continue; // Ignore gaps.
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000258 NumEntries += CSE.LPad->SEHHandlers.size();
Reid Kleckner0a57f652015-01-14 01:05:27 +0000259 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000260 Asm->OutStreamer->EmitIntValue(NumEntries, 4);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000261
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000262 // If there are no actions, we don't need to iterate again.
263 if (NumEntries == 0)
264 return;
265
Reid Kleckner0a57f652015-01-14 01:05:27 +0000266 // Emit the four-label records for each call site entry. The table has to be
267 // sorted in layout order, and the call sites should already be sorted.
268 for (const CallSiteEntry &CSE : CallSites) {
269 // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
270 // an EH table entry will propagate the exception rather than terminating
271 // the program.
272 if (!CSE.LPad)
273 continue;
274 const LandingPadInfo *LPad = CSE.LPad;
275
276 // Compute the label range. We may reuse the function begin and end labels
277 // rather than forming new ones.
278 const MCExpr *Begin =
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000279 create32bitRef(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000280 const MCExpr *End;
281 if (CSE.EndLabel) {
282 // The interval is half-open, so we have to add one to include the return
283 // address of the last invoke in the range.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000284 End = MCBinaryExpr::createAdd(create32bitRef(CSE.EndLabel),
285 MCConstantExpr::create(1, Asm->OutContext),
Reid Kleckner0a57f652015-01-14 01:05:27 +0000286 Asm->OutContext);
287 } else {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000288 End = create32bitRef(EHFuncEndSym);
Reid Kleckner0a57f652015-01-14 01:05:27 +0000289 }
290
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000291 // Emit an entry for each action.
292 for (SEHHandler Handler : LPad->SEHHandlers) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000293 Asm->OutStreamer->EmitValue(Begin, 4);
294 Asm->OutStreamer->EmitValue(End, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000295
296 // Emit the filter or finally function pointer, if present. Otherwise,
297 // emit '1' to indicate a catch-all.
298 const Function *F = Handler.FilterOrFinally;
299 if (F)
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000300 Asm->OutStreamer->EmitValue(create32bitRef(Asm->getSymbol(F)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000301 else
Lang Hames9ff69c82015-04-24 19:11:51 +0000302 Asm->OutStreamer->EmitIntValue(1, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000303
304 // Emit the recovery address, if present. Otherwise, this must be a
305 // finally.
306 const BlockAddress *BA = Handler.RecoverBA;
307 if (BA)
Lang Hames9ff69c82015-04-24 19:11:51 +0000308 Asm->OutStreamer->EmitValue(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000309 create32bitRef(Asm->GetBlockAddressSymbol(BA)), 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000310 else
Lang Hames9ff69c82015-04-24 19:11:51 +0000311 Asm->OutStreamer->EmitIntValue(0, 4);
Reid Klecknerd2a1a512015-04-21 18:23:57 +0000312 }
Reid Kleckner0a57f652015-01-14 01:05:27 +0000313 }
314}
David Majnemercde33032015-03-30 22:58:10 +0000315
Reid Kleckner94b704c2015-09-09 21:10:03 +0000316/// Retreive the MCSymbol for a GlobalValue or MachineBasicBlock. GlobalValues
317/// are used in the old WinEH scheme, and they will be removed eventually.
318static MCSymbol *getMCSymbolForMBBOrGV(AsmPrinter *Asm, ValueOrMBB Handler) {
Reid Kleckner78783912015-09-10 00:25:23 +0000319 if (!Handler)
320 return nullptr;
Reid Kleckner94b704c2015-09-09 21:10:03 +0000321 if (Handler.is<MachineBasicBlock *>())
322 return Handler.get<MachineBasicBlock *>()->getSymbol();
Reid Kleckner78783912015-09-10 00:25:23 +0000323 return Asm->getSymbol(cast<GlobalValue>(Handler.get<const Value *>()));
Reid Kleckner94b704c2015-09-09 21:10:03 +0000324}
325
Reid Kleckner60b640b2015-05-28 22:47:01 +0000326void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
David Majnemercde33032015-03-30 22:58:10 +0000327 const Function *F = MF->getFunction();
328 const Function *ParentF = MMI->getWinEHParent(F);
Lang Hames9ff69c82015-04-24 19:11:51 +0000329 auto &OS = *Asm->OutStreamer;
David Majnemera225a192015-03-31 22:35:44 +0000330 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
David Majnemercde33032015-03-30 22:58:10 +0000331
332 StringRef ParentLinkageName =
333 GlobalValue::getRealLinkageName(ParentF->getName());
334
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000335 MCSymbol *FuncInfoXData = nullptr;
336 if (shouldEmitPersonality) {
337 FuncInfoXData = Asm->OutContext.getOrCreateSymbol(
338 Twine("$cppxdata$", ParentLinkageName));
339 OS.EmitValue(create32bitRef(FuncInfoXData), 4);
340
341 extendIP2StateTable(MF, ParentF, FuncInfo);
342
Reid Kleckner0e288232015-08-27 23:27:47 +0000343 if (!MMI->hasEHFunclets()) {
344 // Defer emission until we've visited the parent function and all the
345 // catch handlers. Cleanups don't contribute to the ip2state table, so
346 // don't count them.
347 if (ParentF != F && !FuncInfo.CatchHandlerMaxState.count(F))
348 return;
349 ++FuncInfo.NumIPToStateFuncsVisited;
350 if (FuncInfo.NumIPToStateFuncsVisited !=
351 FuncInfo.CatchHandlerMaxState.size())
352 return;
353 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000354 } else {
355 FuncInfoXData = Asm->OutContext.getOrCreateLSDASymbol(ParentLinkageName);
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000356 emitEHRegistrationOffsetLabel(FuncInfo, ParentLinkageName);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000357 }
358
359 MCSymbol *UnwindMapXData = nullptr;
360 MCSymbol *TryBlockMapXData = nullptr;
361 MCSymbol *IPToStateXData = nullptr;
362 if (!FuncInfo.UnwindMap.empty())
363 UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
364 Twine("$stateUnwindMap$", ParentLinkageName));
365 if (!FuncInfo.TryBlockMap.empty())
366 TryBlockMapXData = Asm->OutContext.getOrCreateSymbol(
367 Twine("$tryMap$", ParentLinkageName));
368 if (!FuncInfo.IPToStateList.empty())
369 IPToStateXData = Asm->OutContext.getOrCreateSymbol(
370 Twine("$ip2state$", ParentLinkageName));
371
372 // FuncInfo {
373 // uint32_t MagicNumber
374 // int32_t MaxState;
375 // UnwindMapEntry *UnwindMap;
376 // uint32_t NumTryBlocks;
377 // TryBlockMapEntry *TryBlockMap;
378 // uint32_t IPMapEntries; // always 0 for x86
379 // IPToStateMapEntry *IPToStateMap; // always 0 for x86
380 // uint32_t UnwindHelp; // non-x86 only
381 // ESTypeList *ESTypeList;
382 // int32_t EHFlags;
383 // }
384 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
385 // EHFlags & 2 -> ???
386 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
Reid Kleckner85a24502015-07-10 00:08:49 +0000387 OS.EmitValueToAlignment(4);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000388 OS.EmitLabel(FuncInfoXData);
389 OS.EmitIntValue(0x19930522, 4); // MagicNumber
390 OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4); // MaxState
391 OS.EmitValue(create32bitRef(UnwindMapXData), 4); // UnwindMap
392 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
393 OS.EmitValue(create32bitRef(TryBlockMapXData), 4); // TryBlockMap
394 OS.EmitIntValue(FuncInfo.IPToStateList.size(), 4); // IPMapEntries
395 OS.EmitValue(create32bitRef(IPToStateXData), 4); // IPToStateMap
396 if (Asm->MAI->usesWindowsCFI())
397 OS.EmitIntValue(FuncInfo.UnwindHelpFrameOffset, 4); // UnwindHelp
398 OS.EmitIntValue(0, 4); // ESTypeList
399 OS.EmitIntValue(1, 4); // EHFlags
400
401 // UnwindMapEntry {
402 // int32_t ToState;
403 // void (*Action)();
404 // };
405 if (UnwindMapXData) {
406 OS.EmitLabel(UnwindMapXData);
407 for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
Reid Kleckner78783912015-09-10 00:25:23 +0000408 MCSymbol *CleanupSym = getMCSymbolForMBBOrGV(Asm, UME.Cleanup);
409 OS.EmitIntValue(UME.ToState, 4); // ToState
410 OS.EmitValue(create32bitRef(CleanupSym), 4); // Action
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000411 }
412 }
413
414 // TryBlockMap {
415 // int32_t TryLow;
416 // int32_t TryHigh;
417 // int32_t CatchHigh;
418 // int32_t NumCatches;
419 // HandlerType *HandlerArray;
420 // };
421 if (TryBlockMapXData) {
422 OS.EmitLabel(TryBlockMapXData);
423 SmallVector<MCSymbol *, 1> HandlerMaps;
424 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
425 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
426 MCSymbol *HandlerMapXData = nullptr;
427
428 if (!TBME.HandlerArray.empty())
429 HandlerMapXData =
430 Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
431 .concat(Twine(I))
432 .concat("$")
433 .concat(ParentLinkageName));
434
435 HandlerMaps.push_back(HandlerMapXData);
436
Reid Kleckner0e288232015-08-27 23:27:47 +0000437 int CatchHigh = TBME.CatchHigh;
438 if (CatchHigh == -1) {
439 for (WinEHHandlerType &HT : TBME.HandlerArray)
Reid Kleckner94b704c2015-09-09 21:10:03 +0000440 CatchHigh =
441 std::max(CatchHigh, FuncInfo.CatchHandlerMaxState[cast<Function>(
442 HT.Handler.get<const Value *>())]);
Reid Kleckner0e288232015-08-27 23:27:47 +0000443 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000444
445 assert(TBME.TryLow <= TBME.TryHigh);
446 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
447 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
448 OS.EmitIntValue(CatchHigh, 4); // CatchHigh
449 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
450 OS.EmitValue(create32bitRef(HandlerMapXData), 4); // HandlerArray
451 }
452
453 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
454 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
455 MCSymbol *HandlerMapXData = HandlerMaps[I];
456 if (!HandlerMapXData)
457 continue;
458 // HandlerType {
459 // int32_t Adjectives;
460 // TypeDescriptor *Type;
461 // int32_t CatchObjOffset;
462 // void (*Handler)();
463 // int32_t ParentFrameOffset; // x64 only
464 // };
465 OS.EmitLabel(HandlerMapXData);
466 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
467 // Get the frame escape label with the offset of the catch object. If
468 // the index is -1, then there is no catch object, and we should emit an
469 // offset of zero, indicating that no copy will occur.
470 const MCExpr *FrameAllocOffsetRef = nullptr;
471 if (HT.CatchObjRecoverIdx >= 0) {
472 MCSymbol *FrameAllocOffset =
473 Asm->OutContext.getOrCreateFrameAllocSymbol(
474 GlobalValue::getRealLinkageName(ParentF->getName()),
475 HT.CatchObjRecoverIdx);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000476 FrameAllocOffsetRef = MCSymbolRefExpr::create(
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000477 FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
478 } else {
Jim Grosbach13760bd2015-05-30 01:25:56 +0000479 FrameAllocOffsetRef = MCConstantExpr::create(0, Asm->OutContext);
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000480 }
481
Reid Kleckner94b704c2015-09-09 21:10:03 +0000482 MCSymbol *HandlerSym = getMCSymbolForMBBOrGV(Asm, HT.Handler);
483
484 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
485 OS.EmitValue(create32bitRef(HT.TypeDescriptor), 4); // Type
486 OS.EmitValue(FrameAllocOffsetRef, 4); // CatchObjOffset
487 OS.EmitValue(create32bitRef(HandlerSym), 4); // Handler
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000488
489 if (shouldEmitPersonality) {
Reid Klecknerdf129512015-09-08 22:44:41 +0000490 if (FuncInfo.CatchHandlerParentFrameObjOffset.empty()) {
491 // With the new IR, this is always 16 + 8 + getMaxCallFrameSize().
492 // Keep this in sync with X86FrameLowering::emitPrologue.
493 int ParentFrameOffset =
494 16 + 8 + MF->getFrameInfo()->getMaxCallFrameSize();
495 OS.EmitIntValue(ParentFrameOffset, 4); // ParentFrameOffset
496 } else {
497 MCSymbol *ParentFrameOffset =
498 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(
Reid Kleckner94b704c2015-09-09 21:10:03 +0000499 GlobalValue::getRealLinkageName(
500 HT.Handler.get<const Value *>()->getName()));
Reid Klecknerdf129512015-09-08 22:44:41 +0000501 const MCSymbolRefExpr *ParentFrameOffsetRef =
502 MCSymbolRefExpr::create(ParentFrameOffset, Asm->OutContext);
503 OS.EmitValue(ParentFrameOffsetRef, 4); // ParentFrameOffset
504 }
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000505 }
506 }
507 }
508 }
509
510 // IPToStateMapEntry {
511 // void *IP;
512 // int32_t State;
513 // };
514 if (IPToStateXData) {
515 OS.EmitLabel(IPToStateXData);
516 for (auto &IPStatePair : FuncInfo.IPToStateList) {
517 OS.EmitValue(create32bitRef(IPStatePair.first), 4); // IP
518 OS.EmitIntValue(IPStatePair.second, 4); // State
519 }
520 }
521}
522
523void WinException::extendIP2StateTable(const MachineFunction *MF,
524 const Function *ParentF,
525 WinEHFuncInfo &FuncInfo) {
526 const Function *F = MF->getFunction();
David Majnemercde33032015-03-30 22:58:10 +0000527
528 // The Itanium LSDA table sorts similar landing pads together to simplify the
529 // actions table, but we don't need that.
530 SmallVector<const LandingPadInfo *, 64> LandingPads;
531 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
532 LandingPads.reserve(PadInfos.size());
533 for (const auto &LP : PadInfos)
534 LandingPads.push_back(&LP);
535
536 RangeMapType PadMap;
537 computePadMap(LandingPads, PadMap);
538
539 // The end label of the previous invoke or nounwind try-range.
540 MCSymbol *LastLabel = Asm->getFunctionBegin();
541
542 // Whether there is a potentially throwing instruction (currently this means
543 // an ordinary call) between the end of the previous try-range and now.
544 bool SawPotentiallyThrowing = false;
545
David Majnemercde33032015-03-30 22:58:10 +0000546 int LastEHState = -2;
547
548 // The parent function and the catch handlers contribute to the 'ip2state'
549 // table.
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000550
551 // Include ip2state entries for the beginning of the main function and
552 // for catch handler functions.
553 if (F == ParentF) {
554 FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
555 LastEHState = -1;
556 } else if (FuncInfo.HandlerBaseState.count(F)) {
Reid Kleckner1d3d4ad2015-05-29 17:00:57 +0000557 FuncInfo.IPToStateList.push_back(
558 std::make_pair(LastLabel, FuncInfo.HandlerBaseState[F]));
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000559 LastEHState = FuncInfo.HandlerBaseState[F];
560 }
David Majnemercde33032015-03-30 22:58:10 +0000561 for (const auto &MBB : *MF) {
562 for (const auto &MI : MBB) {
563 if (!MI.isEHLabel()) {
564 if (MI.isCall())
565 SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
566 continue;
567 }
568
569 // End of the previous try-range?
570 MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
571 if (BeginLabel == LastLabel)
572 SawPotentiallyThrowing = false;
573
574 // Beginning of a new try-range?
575 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
576 if (L == PadMap.end())
577 // Nope, it was just some random label.
578 continue;
579
580 const PadRange &P = L->second;
581 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
582 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
583 "Inconsistent landing pad map!");
584
Andrew Kaylor762a6be2015-05-11 19:41:19 +0000585 // FIXME: Should this be using FuncInfo.HandlerBaseState?
586 if (SawPotentiallyThrowing && LastEHState != -1) {
David Majnemercde33032015-03-30 22:58:10 +0000587 FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
588 SawPotentiallyThrowing = false;
589 LastEHState = -1;
590 }
591
592 if (LandingPad->WinEHState != LastEHState)
593 FuncInfo.IPToStateList.push_back(
594 std::make_pair(BeginLabel, LandingPad->WinEHState));
595 LastEHState = LandingPad->WinEHState;
596 LastLabel = LandingPad->EndLabels[P.RangeIndex];
597 }
598 }
David Majnemercde33032015-03-30 22:58:10 +0000599}
Reid Klecknerf12c0302015-06-09 21:42:19 +0000600
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000601void WinException::emitEHRegistrationOffsetLabel(const WinEHFuncInfo &FuncInfo,
602 StringRef FLinkageName) {
603 // Outlined helpers called by the EH runtime need to know the offset of the EH
604 // registration in order to recover the parent frame pointer. Now that we know
605 // we've code generated the parent, we can emit the label assignment that
606 // those helpers use to get the offset of the registration node.
607 assert(FuncInfo.EHRegNodeEscapeIndex != INT_MAX &&
Reid Kleckner60381792015-07-07 22:25:32 +0000608 "no EH reg node localescape index");
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000609 MCSymbol *ParentFrameOffset =
610 Asm->OutContext.getOrCreateParentFrameOffsetSymbol(FLinkageName);
611 MCSymbol *RegistrationOffsetSym = Asm->OutContext.getOrCreateFrameAllocSymbol(
612 FLinkageName, FuncInfo.EHRegNodeEscapeIndex);
613 const MCExpr *RegistrationOffsetSymRef =
614 MCSymbolRefExpr::create(RegistrationOffsetSym, Asm->OutContext);
615 Asm->OutStreamer->EmitAssignment(ParentFrameOffset, RegistrationOffsetSymRef);
616}
617
Reid Klecknerf12c0302015-06-09 21:42:19 +0000618/// Emit the language-specific data that _except_handler3 and 4 expect. This is
619/// functionally equivalent to the __C_specific_handler table, except it is
620/// indexed by state number instead of IP.
621void WinException::emitExceptHandlerTable(const MachineFunction *MF) {
Reid Klecknera9d62532015-06-11 22:32:23 +0000622 MCStreamer &OS = *Asm->OutStreamer;
Reid Klecknera9d62532015-06-11 22:32:23 +0000623 const Function *F = MF->getFunction();
Reid Klecknera9d62532015-06-11 22:32:23 +0000624 StringRef FLinkageName = GlobalValue::getRealLinkageName(F->getName());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000625
626 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(F);
627 emitEHRegistrationOffsetLabel(FuncInfo, FLinkageName);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000628
629 // Emit the __ehtable label that we use for llvm.x86.seh.lsda.
Reid Klecknerf12c0302015-06-09 21:42:19 +0000630 MCSymbol *LSDALabel = Asm->OutContext.getOrCreateLSDASymbol(FLinkageName);
Reid Kleckner85a24502015-07-10 00:08:49 +0000631 OS.EmitValueToAlignment(4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000632 OS.EmitLabel(LSDALabel);
633
Reid Kleckner9a1a9192015-07-13 20:41:46 +0000634 const Function *Per =
635 dyn_cast<Function>(F->getPersonalityFn()->stripPointerCasts());
Reid Klecknerf12c0302015-06-09 21:42:19 +0000636 StringRef PerName = Per->getName();
637 int BaseState = -1;
638 if (PerName == "_except_handler4") {
639 // The LSDA for _except_handler4 starts with this struct, followed by the
640 // scope table:
641 //
642 // struct EH4ScopeTable {
643 // int32_t GSCookieOffset;
644 // int32_t GSCookieXOROffset;
645 // int32_t EHCookieOffset;
646 // int32_t EHCookieXOROffset;
647 // ScopeTableEntry ScopeRecord[];
648 // };
649 //
650 // Only the EHCookieOffset field appears to vary, and it appears to be the
651 // offset from the final saved SP value to the retaddr.
652 OS.EmitIntValue(-2, 4);
653 OS.EmitIntValue(0, 4);
654 // FIXME: Calculate.
655 OS.EmitIntValue(9999, 4);
656 OS.EmitIntValue(0, 4);
657 BaseState = -2;
658 }
659
Reid Kleckner94b704c2015-09-09 21:10:03 +0000660 if (!FuncInfo.SEHUnwindMap.empty()) {
661 for (SEHUnwindMapEntry &UME : FuncInfo.SEHUnwindMap) {
662 MCSymbol *ExceptOrFinally =
663 UME.Handler.get<MachineBasicBlock *>()->getSymbol();
664 OS.EmitIntValue(UME.ToState, 4); // ToState
665 OS.EmitValue(create32bitRef(UME.Filter), 4); // Filter
666 OS.EmitValue(create32bitRef(ExceptOrFinally), 4); // Except/Finally
667 }
668 return;
669 }
670 // FIXME: The following code is for the old landingpad-based SEH
671 // implementation. Remove it when possible.
672
Reid Klecknerf12c0302015-06-09 21:42:19 +0000673 // Build a list of pointers to LandingPadInfos and then sort by WinEHState.
674 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
675 SmallVector<const LandingPadInfo *, 4> LPads;
676 LPads.reserve((PadInfos.size()));
677 for (const LandingPadInfo &LPInfo : PadInfos)
678 LPads.push_back(&LPInfo);
679 std::sort(LPads.begin(), LPads.end(),
680 [](const LandingPadInfo *L, const LandingPadInfo *R) {
681 return L->WinEHState < R->WinEHState;
682 });
683
684 // For each action in each lpad, emit one of these:
685 // struct ScopeTableEntry {
686 // int32_t EnclosingLevel;
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000687 // int32_t (__cdecl *Filter)();
688 // void *HandlerOrFinally;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000689 // };
690 //
691 // The "outermost" action will use BaseState as its enclosing level. Each
692 // other action will refer to the previous state as its enclosing level.
693 int CurState = 0;
694 for (const LandingPadInfo *LPInfo : LPads) {
695 int EnclosingLevel = BaseState;
Reid Kleckner7912d9b2015-06-10 00:04:53 +0000696 assert(CurState + int(LPInfo->SEHHandlers.size()) - 1 ==
697 LPInfo->WinEHState &&
Reid Klecknerf12c0302015-06-09 21:42:19 +0000698 "gaps in the SEH scope table");
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000699 for (auto I = LPInfo->SEHHandlers.rbegin(), E = LPInfo->SEHHandlers.rend();
700 I != E; ++I) {
701 const SEHHandler &Handler = *I;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000702 const BlockAddress *BA = Handler.RecoverBA;
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000703 const Function *F = Handler.FilterOrFinally;
704 assert(F && "cannot catch all in 32-bit SEH without filter function");
705 const MCExpr *FilterOrNull =
706 create32bitRef(BA ? Asm->getSymbol(F) : nullptr);
707 const MCExpr *ExceptOrFinally = create32bitRef(
708 BA ? Asm->GetBlockAddressSymbol(BA) : Asm->getSymbol(F));
Reid Klecknerf12c0302015-06-09 21:42:19 +0000709
710 OS.EmitIntValue(EnclosingLevel, 4);
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000711 OS.EmitValue(FilterOrNull, 4);
712 OS.EmitValue(ExceptOrFinally, 4);
Reid Klecknerf12c0302015-06-09 21:42:19 +0000713
714 // The next state unwinds to this state.
715 EnclosingLevel = CurState;
716 CurState++;
717 }
718 }
719}