1 //===-- CodeGen/AsmPrinter/Win64Exception.cpp - Dwarf Exception Impl ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing Win64 exception info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "Win64Exception.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/Support/Dwarf.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Target/TargetFrameLowering.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
41 Win64Exception::Win64Exception(AsmPrinter *A)
42 : EHStreamer(A), shouldEmitPersonality(false), shouldEmitLSDA(false),
43 shouldEmitMoves(false) {}
45 Win64Exception::~Win64Exception() {}
47 /// endModule - Emit all exception information that should come after the
49 void Win64Exception::endModule() {
52 void Win64Exception::beginFunction(const MachineFunction *MF) {
53 shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
55 // If any landing pads survive, we need an EH table.
56 bool hasLandingPads = !MMI->getLandingPads().empty();
58 shouldEmitMoves = Asm->needsSEHMoves();
60 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
61 unsigned PerEncoding = TLOF.getPersonalityEncoding();
62 const Function *Per = MF->getMMI().getPersonality();
64 shouldEmitPersonality = hasLandingPads &&
65 PerEncoding != dwarf::DW_EH_PE_omit && Per;
67 unsigned LSDAEncoding = TLOF.getLSDAEncoding();
68 shouldEmitLSDA = shouldEmitPersonality &&
69 LSDAEncoding != dwarf::DW_EH_PE_omit;
71 if (!shouldEmitPersonality && !shouldEmitMoves)
74 Asm->OutStreamer.EmitWinCFIStartProc(Asm->CurrentFnSym);
76 if (!shouldEmitPersonality)
79 const MCSymbol *PersHandlerSym =
80 TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
81 Asm->OutStreamer.EmitWinEHHandler(PersHandlerSym, true, true);
84 /// endFunction - Gather and emit post-function exception information.
86 void Win64Exception::endFunction(const MachineFunction *MF) {
87 if (!shouldEmitPersonality && !shouldEmitMoves)
90 // Map all labels and get rid of any dead landing pads.
91 MMI->TidyLandingPads();
93 if (shouldEmitPersonality) {
94 Asm->OutStreamer.PushSection();
96 // Emit an UNWIND_INFO struct describing the prologue.
97 Asm->OutStreamer.EmitWinEHHandlerData();
99 // Emit the tables appropriate to the personality function in use. If we
100 // don't recognize the personality, assume it uses an Itanium-style LSDA.
101 EHPersonality Per = MMI->getPersonalityType();
102 if (Per == EHPersonality::MSVC_Win64SEH)
103 emitCSpecificHandlerTable();
104 else if (Per == EHPersonality::MSVC_CXX)
105 emitCXXFrameHandler3Table(MF);
107 emitExceptionTable();
109 Asm->OutStreamer.PopSection();
111 Asm->OutStreamer.EmitWinCFIEndProc();
114 const MCExpr *Win64Exception::createImageRel32(const MCSymbol *Value) {
116 return MCConstantExpr::Create(0, Asm->OutContext);
117 return MCSymbolRefExpr::Create(Value, MCSymbolRefExpr::VK_COFF_IMGREL32,
121 const MCExpr *Win64Exception::createImageRel32(const GlobalValue *GV) {
123 return MCConstantExpr::Create(0, Asm->OutContext);
124 return createImageRel32(Asm->getSymbol(GV));
127 /// Emit the language-specific data that __C_specific_handler expects. This
128 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
129 /// up after faults with __try, __except, and __finally. The typeinfo values
130 /// are not really RTTI data, but pointers to filter functions that return an
131 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
132 /// blocks and other cleanups, the landing pad label is zero, and the filter
133 /// function is actually a cleanup handler with the same prototype. A catch-all
134 /// entry is modeled with a null filter function field and a non-zero landing
137 /// Possible filter function return values:
138 /// EXCEPTION_EXECUTE_HANDLER (1):
139 /// Jump to the landing pad label after cleanups.
140 /// EXCEPTION_CONTINUE_SEARCH (0):
141 /// Continue searching this table or continue unwinding.
142 /// EXCEPTION_CONTINUE_EXECUTION (-1):
143 /// Resume execution at the trapping PC.
145 /// Inferred table structure:
149 /// imagerel32 LabelStart;
150 /// imagerel32 LabelEnd;
151 /// imagerel32 FilterOrFinally; // One means catch-all.
152 /// imagerel32 LabelLPad; // Zero means __finally.
153 /// } Entries[NumEntries];
155 void Win64Exception::emitCSpecificHandlerTable() {
156 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
158 // Simplifying assumptions for first implementation:
159 // - Cleanups are not implemented.
160 // - Filters are not implemented.
162 // The Itanium LSDA table sorts similar landing pads together to simplify the
163 // actions table, but we don't need that.
164 SmallVector<const LandingPadInfo *, 64> LandingPads;
165 LandingPads.reserve(PadInfos.size());
166 for (const auto &LP : PadInfos)
167 LandingPads.push_back(&LP);
169 // Compute label ranges for call sites as we would for the Itanium LSDA, but
170 // use an all zero action table because we aren't using these actions.
171 SmallVector<unsigned, 64> FirstActions;
172 FirstActions.resize(LandingPads.size());
173 SmallVector<CallSiteEntry, 64> CallSites;
174 computeCallSiteTable(CallSites, LandingPads, FirstActions);
176 MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
177 MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
179 // Emit the number of table entries.
180 unsigned NumEntries = 0;
181 for (const CallSiteEntry &CSE : CallSites) {
183 continue; // Ignore gaps.
184 for (int Selector : CSE.LPad->TypeIds) {
185 // Ignore C++ filter clauses in SEH.
186 // FIXME: Implement cleanup clauses.
187 if (isCatchEHSelector(Selector))
191 Asm->OutStreamer.EmitIntValue(NumEntries, 4);
193 // Emit the four-label records for each call site entry. The table has to be
194 // sorted in layout order, and the call sites should already be sorted.
195 for (const CallSiteEntry &CSE : CallSites) {
196 // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
197 // an EH table entry will propagate the exception rather than terminating
201 const LandingPadInfo *LPad = CSE.LPad;
203 // Compute the label range. We may reuse the function begin and end labels
204 // rather than forming new ones.
205 const MCExpr *Begin =
206 createImageRel32(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
209 // The interval is half-open, so we have to add one to include the return
210 // address of the last invoke in the range.
211 End = MCBinaryExpr::CreateAdd(createImageRel32(CSE.EndLabel),
212 MCConstantExpr::Create(1, Asm->OutContext),
215 End = createImageRel32(EHFuncEndSym);
218 // These aren't really type info globals, they are actually pointers to
219 // filter functions ordered by selector. The zero selector is used for
220 // cleanups, so slot zero corresponds to selector 1.
221 const std::vector<const GlobalValue *> &SelectorToFilter = MMI->getTypeInfos();
223 // Do a parallel iteration across typeids and clause labels, skipping filter
225 size_t NextClauseLabel = 0;
226 for (size_t I = 0, E = LPad->TypeIds.size(); I < E; ++I) {
227 // AddLandingPadInfo stores the clauses in reverse, but there is a FIXME
229 int Selector = LPad->TypeIds[E - I - 1];
231 // Ignore C++ filter clauses in SEH.
232 // FIXME: Implement cleanup clauses.
233 if (!isCatchEHSelector(Selector))
236 Asm->OutStreamer.EmitValue(Begin, 4);
237 Asm->OutStreamer.EmitValue(End, 4);
238 if (isCatchEHSelector(Selector)) {
239 assert(unsigned(Selector - 1) < SelectorToFilter.size());
240 const GlobalValue *TI = SelectorToFilter[Selector - 1];
241 if (TI) // Emit the filter function pointer.
242 Asm->OutStreamer.EmitValue(createImageRel32(Asm->getSymbol(TI)), 4);
243 else // Otherwise, this is a "catch i8* null", or catch all.
244 Asm->OutStreamer.EmitIntValue(1, 4);
246 MCSymbol *ClauseLabel = LPad->ClauseLabels[NextClauseLabel++];
247 Asm->OutStreamer.EmitValue(createImageRel32(ClauseLabel), 4);
252 void Win64Exception::emitCXXFrameHandler3Table(const MachineFunction *MF) {
253 const Function *F = MF->getFunction();
254 const Function *ParentF = MMI->getWinEHParent(F);
255 auto &OS = Asm->OutStreamer;
257 StringRef ParentLinkageName =
258 GlobalValue::getRealLinkageName(ParentF->getName());
260 MCSymbol *FuncInfoXData =
261 Asm->OutContext.GetOrCreateSymbol(Twine("$cppxdata$", ParentLinkageName));
262 OS.EmitValue(createImageRel32(FuncInfoXData), 4);
264 // The Itanium LSDA table sorts similar landing pads together to simplify the
265 // actions table, but we don't need that.
266 SmallVector<const LandingPadInfo *, 64> LandingPads;
267 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
268 LandingPads.reserve(PadInfos.size());
269 for (const auto &LP : PadInfos)
270 LandingPads.push_back(&LP);
273 computePadMap(LandingPads, PadMap);
275 // The end label of the previous invoke or nounwind try-range.
276 MCSymbol *LastLabel = Asm->getFunctionBegin();
278 // Whether there is a potentially throwing instruction (currently this means
279 // an ordinary call) between the end of the previous try-range and now.
280 bool SawPotentiallyThrowing = false;
282 WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
284 int LastEHState = -2;
286 // The parent function and the catch handlers contribute to the 'ip2state'
288 for (const auto &MBB : *MF) {
289 for (const auto &MI : MBB) {
290 if (!MI.isEHLabel()) {
292 SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
296 // End of the previous try-range?
297 MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
298 if (BeginLabel == LastLabel)
299 SawPotentiallyThrowing = false;
301 // Beginning of a new try-range?
302 RangeMapType::const_iterator L = PadMap.find(BeginLabel);
303 if (L == PadMap.end())
304 // Nope, it was just some random label.
307 const PadRange &P = L->second;
308 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
309 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
310 "Inconsistent landing pad map!");
312 if (SawPotentiallyThrowing) {
313 FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
314 SawPotentiallyThrowing = false;
318 if (LandingPad->WinEHState != LastEHState)
319 FuncInfo.IPToStateList.push_back(
320 std::make_pair(BeginLabel, LandingPad->WinEHState));
321 LastEHState = LandingPad->WinEHState;
322 LastLabel = LandingPad->EndLabels[P.RangeIndex];
329 MCSymbol *UnwindMapXData = nullptr;
330 MCSymbol *TryBlockMapXData = nullptr;
331 MCSymbol *IPToStateXData = nullptr;
332 if (!FuncInfo.UnwindMap.empty())
333 UnwindMapXData = Asm->OutContext.GetOrCreateSymbol(
334 Twine("$stateUnwindMap$", ParentLinkageName));
335 if (!FuncInfo.TryBlockMap.empty())
336 TryBlockMapXData = Asm->OutContext.GetOrCreateSymbol(
337 Twine("$tryMap$", ParentLinkageName));
338 if (!FuncInfo.IPToStateList.empty())
339 IPToStateXData = Asm->OutContext.GetOrCreateSymbol(
340 Twine("$ip2state$", ParentLinkageName));
343 // uint32_t MagicNumber
345 // UnwindMapEntry *UnwindMap;
346 // uint32_t NumTryBlocks;
347 // TryBlockMapEntry *TryBlockMap;
348 // uint32_t IPMapEntries;
349 // IPToStateMapEntry *IPToStateMap;
350 // uint32_t UnwindHelp; // (x64/ARM only)
351 // ESTypeList *ESTypeList;
354 // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
355 // EHFlags & 2 -> ???
356 // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
357 OS.EmitLabel(FuncInfoXData);
358 OS.EmitIntValue(0x19930522, 4); // MagicNumber
359 OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4); // MaxState
360 OS.EmitValue(createImageRel32(UnwindMapXData), 4); // UnwindMap
361 OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4); // NumTryBlocks
362 OS.EmitValue(createImageRel32(TryBlockMapXData), 4); // TryBlockMap
363 OS.EmitIntValue(FuncInfo.IPToStateList.size(), 4); // IPMapEntries
364 OS.EmitValue(createImageRel32(IPToStateXData), 4); // IPToStateMap
365 OS.EmitIntValue(FuncInfo.UnwindHelpFrameOffset, 4); // UnwindHelp
366 OS.EmitIntValue(0, 4); // ESTypeList
367 OS.EmitIntValue(1, 4); // EHFlags
373 if (UnwindMapXData) {
374 OS.EmitLabel(UnwindMapXData);
375 for (const WinEHUnwindMapEntry &UME : FuncInfo.UnwindMap) {
376 OS.EmitIntValue(UME.ToState, 4); // ToState
377 OS.EmitValue(createImageRel32(UME.Cleanup), 4); // Action
384 // int32_t CatchHigh;
385 // int32_t NumCatches;
386 // HandlerType *HandlerArray;
388 if (TryBlockMapXData) {
389 OS.EmitLabel(TryBlockMapXData);
390 SmallVector<MCSymbol *, 1> HandlerMaps;
391 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
392 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
393 MCSymbol *HandlerMapXData = nullptr;
395 if (!TBME.HandlerArray.empty())
397 Asm->OutContext.GetOrCreateSymbol(Twine("$handlerMap$")
400 .concat(ParentLinkageName));
402 HandlerMaps.push_back(HandlerMapXData);
404 assert(TBME.TryLow <= TBME.TryHigh);
405 assert(TBME.CatchHigh > TBME.TryHigh);
406 OS.EmitIntValue(TBME.TryLow, 4); // TryLow
407 OS.EmitIntValue(TBME.TryHigh, 4); // TryHigh
408 OS.EmitIntValue(TBME.CatchHigh, 4); // CatchHigh
409 OS.EmitIntValue(TBME.HandlerArray.size(), 4); // NumCatches
410 OS.EmitValue(createImageRel32(HandlerMapXData), 4); // HandlerArray
413 for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
414 WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
415 MCSymbol *HandlerMapXData = HandlerMaps[I];
416 if (!HandlerMapXData)
419 // int32_t Adjectives;
420 // TypeDescriptor *Type;
421 // int32_t CatchObjOffset;
422 // void (*Handler)();
423 // int32_t ParentFrameOffset; // x64 only
425 OS.EmitLabel(HandlerMapXData);
426 for (const WinEHHandlerType &HT : TBME.HandlerArray) {
427 OS.EmitIntValue(HT.Adjectives, 4); // Adjectives
428 OS.EmitValue(createImageRel32(HT.TypeDescriptor), 4); // Type
429 OS.EmitIntValue(0, 4); // CatchObjOffset
430 OS.EmitValue(createImageRel32(HT.Handler), 4); // Handler
431 OS.EmitIntValue(0, 4); // ParentFrameOffset
436 // IPToStateMapEntry {
440 if (IPToStateXData) {
441 OS.EmitLabel(IPToStateXData);
442 for (auto &IPStatePair : FuncInfo.IPToStateList) {
443 OS.EmitValue(createImageRel32(IPStatePair.first), 4); // IP
444 OS.EmitIntValue(IPStatePair.second, 4); // State