9c6069b41ddb8e025c9d2d795a14cfe0ffa172ca
[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/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"
39 using namespace llvm;
40
41 WinException::WinException(AsmPrinter *A)
42   : EHStreamer(A), shouldEmitPersonality(false), shouldEmitLSDA(false),
43     shouldEmitMoves(false) {}
44
45 WinException::~WinException() {}
46
47 /// endModule - Emit all exception information that should come after the
48 /// content.
49 void WinException::endModule() {
50 }
51
52 void WinException::beginFunction(const MachineFunction *MF) {
53   shouldEmitMoves = shouldEmitPersonality = shouldEmitLSDA = false;
54
55   // If any landing pads survive, we need an EH table.
56   bool hasLandingPads = !MMI->getLandingPads().empty();
57
58   shouldEmitMoves = Asm->needsSEHMoves();
59
60   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
61   unsigned PerEncoding = TLOF.getPersonalityEncoding();
62   const Function *Per = MF->getMMI().getPersonality();
63
64   shouldEmitPersonality = hasLandingPads &&
65     PerEncoding != dwarf::DW_EH_PE_omit && Per;
66
67   unsigned LSDAEncoding = TLOF.getLSDAEncoding();
68   shouldEmitLSDA = shouldEmitPersonality &&
69     LSDAEncoding != dwarf::DW_EH_PE_omit;
70
71
72   // If this was an outlined handler, we need to define the label corresponding
73   // to the offset of the parent frame relative to the stack pointer after the
74   // prologue.
75   const Function *F = MF->getFunction();
76   const Function *ParentF = MMI->getWinEHParent(F);
77   if (F != ParentF) {
78     WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
79     auto I = FuncInfo.CatchHandlerParentFrameObjOffset.find(F);
80     if (I != FuncInfo.CatchHandlerParentFrameObjOffset.end()) {
81       MCSymbol *HandlerTypeParentFrameOffset =
82           Asm->OutContext.getOrCreateParentFrameOffsetSymbol(
83               GlobalValue::getRealLinkageName(F->getName()));
84
85       // Emit a symbol assignment.
86       Asm->OutStreamer->EmitAssignment(
87           HandlerTypeParentFrameOffset,
88           MCConstantExpr::Create(I->second, Asm->OutContext));
89     }
90   }
91
92   if (!shouldEmitPersonality && !shouldEmitMoves)
93     return;
94
95   Asm->OutStreamer->EmitWinCFIStartProc(Asm->CurrentFnSym);
96
97   if (!shouldEmitPersonality)
98     return;
99
100   const MCSymbol *PersHandlerSym =
101       TLOF.getCFIPersonalitySymbol(Per, *Asm->Mang, Asm->TM, MMI);
102   Asm->OutStreamer->EmitWinEHHandler(PersHandlerSym, true, true);
103 }
104
105 /// endFunction - Gather and emit post-function exception information.
106 ///
107 void WinException::endFunction(const MachineFunction *MF) {
108   if (!shouldEmitPersonality && !shouldEmitMoves)
109     return;
110
111   EHPersonality Per = MMI->getPersonalityType();
112
113   // Get rid of any dead landing pads if we're not using a Windows EH scheme. In
114   // Windows EH schemes, the landing pad is not actually reachable. It only
115   // exists so that we can emit the right table data.
116   if (!isMSVCEHPersonality(Per))
117     MMI->TidyLandingPads();
118
119   if (shouldEmitPersonality) {
120     Asm->OutStreamer->PushSection();
121
122     // Emit an UNWIND_INFO struct describing the prologue.
123     Asm->OutStreamer->EmitWinEHHandlerData();
124
125     // Emit the tables appropriate to the personality function in use. If we
126     // don't recognize the personality, assume it uses an Itanium-style LSDA.
127     if (Per == EHPersonality::MSVC_Win64SEH)
128       emitCSpecificHandlerTable();
129     else if (Per == EHPersonality::MSVC_CXX)
130       emitCXXFrameHandler3Table(MF);
131     else
132       emitExceptionTable();
133
134     Asm->OutStreamer->PopSection();
135   }
136   Asm->OutStreamer->EmitWinCFIEndProc();
137 }
138
139 const MCExpr *WinException::createImageRel32(const MCSymbol *Value) {
140   if (!Value)
141     return MCConstantExpr::Create(0, Asm->OutContext);
142   return MCSymbolRefExpr::Create(Value, MCSymbolRefExpr::VK_COFF_IMGREL32,
143                                  Asm->OutContext);
144 }
145
146 const MCExpr *WinException::createImageRel32(const GlobalValue *GV) {
147   if (!GV)
148     return MCConstantExpr::Create(0, Asm->OutContext);
149   return createImageRel32(Asm->getSymbol(GV));
150 }
151
152 /// Emit the language-specific data that __C_specific_handler expects.  This
153 /// handler lives in the x64 Microsoft C runtime and allows catching or cleaning
154 /// up after faults with __try, __except, and __finally.  The typeinfo values
155 /// are not really RTTI data, but pointers to filter functions that return an
156 /// integer (1, 0, or -1) indicating how to handle the exception. For __finally
157 /// blocks and other cleanups, the landing pad label is zero, and the filter
158 /// function is actually a cleanup handler with the same prototype.  A catch-all
159 /// entry is modeled with a null filter function field and a non-zero landing
160 /// pad label.
161 ///
162 /// Possible filter function return values:
163 ///   EXCEPTION_EXECUTE_HANDLER (1):
164 ///     Jump to the landing pad label after cleanups.
165 ///   EXCEPTION_CONTINUE_SEARCH (0):
166 ///     Continue searching this table or continue unwinding.
167 ///   EXCEPTION_CONTINUE_EXECUTION (-1):
168 ///     Resume execution at the trapping PC.
169 ///
170 /// Inferred table structure:
171 ///   struct Table {
172 ///     int NumEntries;
173 ///     struct Entry {
174 ///       imagerel32 LabelStart;
175 ///       imagerel32 LabelEnd;
176 ///       imagerel32 FilterOrFinally;  // One means catch-all.
177 ///       imagerel32 LabelLPad;        // Zero means __finally.
178 ///     } Entries[NumEntries];
179 ///   };
180 void WinException::emitCSpecificHandlerTable() {
181   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
182
183   // Simplifying assumptions for first implementation:
184   // - Cleanups are not implemented.
185   // - Filters are not implemented.
186
187   // The Itanium LSDA table sorts similar landing pads together to simplify the
188   // actions table, but we don't need that.
189   SmallVector<const LandingPadInfo *, 64> LandingPads;
190   LandingPads.reserve(PadInfos.size());
191   for (const auto &LP : PadInfos)
192     LandingPads.push_back(&LP);
193
194   // Compute label ranges for call sites as we would for the Itanium LSDA, but
195   // use an all zero action table because we aren't using these actions.
196   SmallVector<unsigned, 64> FirstActions;
197   FirstActions.resize(LandingPads.size());
198   SmallVector<CallSiteEntry, 64> CallSites;
199   computeCallSiteTable(CallSites, LandingPads, FirstActions);
200
201   MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin();
202   MCSymbol *EHFuncEndSym = Asm->getFunctionEnd();
203
204   // Emit the number of table entries.
205   unsigned NumEntries = 0;
206   for (const CallSiteEntry &CSE : CallSites) {
207     if (!CSE.LPad)
208       continue; // Ignore gaps.
209     NumEntries += CSE.LPad->SEHHandlers.size();
210   }
211   Asm->OutStreamer->EmitIntValue(NumEntries, 4);
212
213   // If there are no actions, we don't need to iterate again.
214   if (NumEntries == 0)
215     return;
216
217   // Emit the four-label records for each call site entry. The table has to be
218   // sorted in layout order, and the call sites should already be sorted.
219   for (const CallSiteEntry &CSE : CallSites) {
220     // Ignore gaps. Unlike the Itanium model, unwinding through a frame without
221     // an EH table entry will propagate the exception rather than terminating
222     // the program.
223     if (!CSE.LPad)
224       continue;
225     const LandingPadInfo *LPad = CSE.LPad;
226
227     // Compute the label range. We may reuse the function begin and end labels
228     // rather than forming new ones.
229     const MCExpr *Begin =
230         createImageRel32(CSE.BeginLabel ? CSE.BeginLabel : EHFuncBeginSym);
231     const MCExpr *End;
232     if (CSE.EndLabel) {
233       // The interval is half-open, so we have to add one to include the return
234       // address of the last invoke in the range.
235       End = MCBinaryExpr::CreateAdd(createImageRel32(CSE.EndLabel),
236                                     MCConstantExpr::Create(1, Asm->OutContext),
237                                     Asm->OutContext);
238     } else {
239       End = createImageRel32(EHFuncEndSym);
240     }
241
242     // Emit an entry for each action.
243     for (SEHHandler Handler : LPad->SEHHandlers) {
244       Asm->OutStreamer->EmitValue(Begin, 4);
245       Asm->OutStreamer->EmitValue(End, 4);
246
247       // Emit the filter or finally function pointer, if present. Otherwise,
248       // emit '1' to indicate a catch-all.
249       const Function *F = Handler.FilterOrFinally;
250       if (F)
251         Asm->OutStreamer->EmitValue(createImageRel32(Asm->getSymbol(F)), 4);
252       else
253         Asm->OutStreamer->EmitIntValue(1, 4);
254
255       // Emit the recovery address, if present. Otherwise, this must be a
256       // finally.
257       const BlockAddress *BA = Handler.RecoverBA;
258       if (BA)
259         Asm->OutStreamer->EmitValue(
260             createImageRel32(Asm->GetBlockAddressSymbol(BA)), 4);
261       else
262         Asm->OutStreamer->EmitIntValue(0, 4);
263     }
264   }
265 }
266
267 void WinException::emitCXXFrameHandler3Table(const MachineFunction *MF) {
268   const Function *F = MF->getFunction();
269   const Function *ParentF = MMI->getWinEHParent(F);
270   auto &OS = *Asm->OutStreamer;
271   WinEHFuncInfo &FuncInfo = MMI->getWinEHFuncInfo(ParentF);
272
273   StringRef ParentLinkageName =
274       GlobalValue::getRealLinkageName(ParentF->getName());
275
276   MCSymbol *FuncInfoXData =
277       Asm->OutContext.getOrCreateSymbol(Twine("$cppxdata$", ParentLinkageName));
278   OS.EmitValue(createImageRel32(FuncInfoXData), 4);
279
280   // The Itanium LSDA table sorts similar landing pads together to simplify the
281   // actions table, but we don't need that.
282   SmallVector<const LandingPadInfo *, 64> LandingPads;
283   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
284   LandingPads.reserve(PadInfos.size());
285   for (const auto &LP : PadInfos)
286     LandingPads.push_back(&LP);
287
288   RangeMapType PadMap;
289   computePadMap(LandingPads, PadMap);
290
291   // The end label of the previous invoke or nounwind try-range.
292   MCSymbol *LastLabel = Asm->getFunctionBegin();
293
294   // Whether there is a potentially throwing instruction (currently this means
295   // an ordinary call) between the end of the previous try-range and now.
296   bool SawPotentiallyThrowing = false;
297
298   int LastEHState = -2;
299
300   // The parent function and the catch handlers contribute to the 'ip2state'
301   // table.
302
303   // Include ip2state entries for the beginning of the main function and
304   // for catch handler functions.
305   if (F == ParentF) {
306     FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
307     LastEHState = -1;
308   } else if (FuncInfo.HandlerBaseState.count(F)) {
309     FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, 
310                                      FuncInfo.HandlerBaseState[F]));
311     LastEHState = FuncInfo.HandlerBaseState[F];
312   }
313   for (const auto &MBB : *MF) {
314     for (const auto &MI : MBB) {
315       if (!MI.isEHLabel()) {
316         if (MI.isCall())
317           SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI);
318         continue;
319       }
320
321       // End of the previous try-range?
322       MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol();
323       if (BeginLabel == LastLabel)
324         SawPotentiallyThrowing = false;
325
326       // Beginning of a new try-range?
327       RangeMapType::const_iterator L = PadMap.find(BeginLabel);
328       if (L == PadMap.end())
329         // Nope, it was just some random label.
330         continue;
331
332       const PadRange &P = L->second;
333       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
334       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
335              "Inconsistent landing pad map!");
336
337       // FIXME: Should this be using FuncInfo.HandlerBaseState?
338       if (SawPotentiallyThrowing && LastEHState != -1) {
339         FuncInfo.IPToStateList.push_back(std::make_pair(LastLabel, -1));
340         SawPotentiallyThrowing = false;
341         LastEHState = -1;
342       }
343
344       if (LandingPad->WinEHState != LastEHState)
345         FuncInfo.IPToStateList.push_back(
346             std::make_pair(BeginLabel, LandingPad->WinEHState));
347       LastEHState = LandingPad->WinEHState;
348       LastLabel = LandingPad->EndLabels[P.RangeIndex];
349     }
350   }
351
352   // Defer emission until we've visited the parent function and all the catch
353   // handlers.  Cleanups don't contribute to the ip2state table yet, so don't
354   // count them.
355   if (ParentF != F && !FuncInfo.CatchHandlerMaxState.count(F))
356     return;
357   ++FuncInfo.NumIPToStateFuncsVisited;
358   if (FuncInfo.NumIPToStateFuncsVisited != FuncInfo.CatchHandlerMaxState.size())
359     return;
360
361   MCSymbol *UnwindMapXData = nullptr;
362   MCSymbol *TryBlockMapXData = nullptr;
363   MCSymbol *IPToStateXData = nullptr;
364   if (!FuncInfo.UnwindMap.empty())
365     UnwindMapXData = Asm->OutContext.getOrCreateSymbol(
366         Twine("$stateUnwindMap$", ParentLinkageName));
367   if (!FuncInfo.TryBlockMap.empty())
368     TryBlockMapXData = Asm->OutContext.getOrCreateSymbol(
369         Twine("$tryMap$", ParentLinkageName));
370   if (!FuncInfo.IPToStateList.empty())
371     IPToStateXData = Asm->OutContext.getOrCreateSymbol(
372         Twine("$ip2state$", ParentLinkageName));
373
374   // FuncInfo {
375   //   uint32_t           MagicNumber
376   //   int32_t            MaxState;
377   //   UnwindMapEntry    *UnwindMap;
378   //   uint32_t           NumTryBlocks;
379   //   TryBlockMapEntry  *TryBlockMap;
380   //   uint32_t           IPMapEntries;
381   //   IPToStateMapEntry *IPToStateMap;
382   //   uint32_t           UnwindHelp; // (x64/ARM only)
383   //   ESTypeList        *ESTypeList;
384   //   int32_t            EHFlags;
385   // }
386   // EHFlags & 1 -> Synchronous exceptions only, no async exceptions.
387   // EHFlags & 2 -> ???
388   // EHFlags & 4 -> The function is noexcept(true), unwinding can't continue.
389   OS.EmitLabel(FuncInfoXData);
390   OS.EmitIntValue(0x19930522, 4);                      // MagicNumber
391   OS.EmitIntValue(FuncInfo.UnwindMap.size(), 4);       // MaxState
392   OS.EmitValue(createImageRel32(UnwindMapXData), 4);   // UnwindMap
393   OS.EmitIntValue(FuncInfo.TryBlockMap.size(), 4);     // NumTryBlocks
394   OS.EmitValue(createImageRel32(TryBlockMapXData), 4); // TryBlockMap
395   OS.EmitIntValue(FuncInfo.IPToStateList.size(), 4);   // IPMapEntries
396   OS.EmitValue(createImageRel32(IPToStateXData), 4);   // IPToStateMap
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) {
408       OS.EmitIntValue(UME.ToState, 4);                // ToState
409       OS.EmitValue(createImageRel32(UME.Cleanup), 4); // Action
410     }
411   }
412
413   // TryBlockMap {
414   //   int32_t      TryLow;
415   //   int32_t      TryHigh;
416   //   int32_t      CatchHigh;
417   //   int32_t      NumCatches;
418   //   HandlerType *HandlerArray;
419   // };
420   if (TryBlockMapXData) {
421     OS.EmitLabel(TryBlockMapXData);
422     SmallVector<MCSymbol *, 1> HandlerMaps;
423     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
424       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
425       MCSymbol *HandlerMapXData = nullptr;
426
427       if (!TBME.HandlerArray.empty())
428         HandlerMapXData =
429             Asm->OutContext.getOrCreateSymbol(Twine("$handlerMap$")
430                                                   .concat(Twine(I))
431                                                   .concat("$")
432                                                   .concat(ParentLinkageName));
433
434       HandlerMaps.push_back(HandlerMapXData);
435
436       int CatchHigh = -1;
437       for (WinEHHandlerType &HT : TBME.HandlerArray)
438         CatchHigh =
439             std::max(CatchHigh, FuncInfo.CatchHandlerMaxState[HT.Handler]);
440
441       assert(TBME.TryLow <= TBME.TryHigh);
442       OS.EmitIntValue(TBME.TryLow, 4);                    // TryLow
443       OS.EmitIntValue(TBME.TryHigh, 4);                   // TryHigh
444       OS.EmitIntValue(CatchHigh, 4);                      // CatchHigh
445       OS.EmitIntValue(TBME.HandlerArray.size(), 4);       // NumCatches
446       OS.EmitValue(createImageRel32(HandlerMapXData), 4); // HandlerArray
447     }
448
449     for (size_t I = 0, E = FuncInfo.TryBlockMap.size(); I != E; ++I) {
450       WinEHTryBlockMapEntry &TBME = FuncInfo.TryBlockMap[I];
451       MCSymbol *HandlerMapXData = HandlerMaps[I];
452       if (!HandlerMapXData)
453         continue;
454       // HandlerType {
455       //   int32_t         Adjectives;
456       //   TypeDescriptor *Type;
457       //   int32_t         CatchObjOffset;
458       //   void          (*Handler)();
459       //   int32_t         ParentFrameOffset; // x64 only
460       // };
461       OS.EmitLabel(HandlerMapXData);
462       for (const WinEHHandlerType &HT : TBME.HandlerArray) {
463         MCSymbol *ParentFrameOffset =
464             Asm->OutContext.getOrCreateParentFrameOffsetSymbol(
465                 GlobalValue::getRealLinkageName(HT.Handler->getName()));
466         const MCSymbolRefExpr *ParentFrameOffsetRef = MCSymbolRefExpr::Create(
467             ParentFrameOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
468
469         // Get the frame escape label with the offset of the catch object. If
470         // the index is -1, then there is no catch object, and we should emit an
471         // offset of zero, indicating that no copy will occur.
472         const MCExpr *FrameAllocOffsetRef = nullptr;
473         if (HT.CatchObjRecoverIdx >= 0) {
474           MCSymbol *FrameAllocOffset =
475               Asm->OutContext.getOrCreateFrameAllocSymbol(
476                   GlobalValue::getRealLinkageName(ParentF->getName()),
477                   HT.CatchObjRecoverIdx);
478           FrameAllocOffsetRef = MCSymbolRefExpr::Create(
479               FrameAllocOffset, MCSymbolRefExpr::VK_None, Asm->OutContext);
480         } else {
481           FrameAllocOffsetRef = MCConstantExpr::Create(0, Asm->OutContext);
482         }
483
484         OS.EmitIntValue(HT.Adjectives, 4);                    // Adjectives
485         OS.EmitValue(createImageRel32(HT.TypeDescriptor), 4); // Type
486         OS.EmitValue(FrameAllocOffsetRef, 4);                 // CatchObjOffset
487         OS.EmitValue(createImageRel32(HT.Handler), 4);        // Handler
488         OS.EmitValue(ParentFrameOffsetRef, 4);                // ParentFrameOffset
489       }
490     }
491   }
492
493   // IPToStateMapEntry {
494   //   void   *IP;
495   //   int32_t State;
496   // };
497   if (IPToStateXData) {
498     OS.EmitLabel(IPToStateXData);
499     for (auto &IPStatePair : FuncInfo.IPToStateList) {
500       OS.EmitValue(createImageRel32(IPStatePair.first), 4); // IP
501       OS.EmitIntValue(IPStatePair.second, 4);               // State
502     }
503   }
504 }