MCWin64EH.cpp revision eececbc7d3d420a27f9e1f9e11cce1b9bbff953f
1//===- lib/MC/MCWin64EH.cpp - MCWin64EH implementation --------------------===//
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#include "llvm/MC/MCWin64EH.h"
11#include "llvm/ADT/Twine.h"
12#include "llvm/MC/MCContext.h"
13#include "llvm/MC/MCExpr.h"
14#include "llvm/MC/MCObjectFileInfo.h"
15#include "llvm/MC/MCSectionCOFF.h"
16#include "llvm/MC/MCStreamer.h"
17#include "llvm/MC/MCSymbol.h"
18
19namespace llvm {
20
21// NOTE: All relocations generated here are 4-byte image-relative.
22
23static uint8_t CountOfUnwindCodes(std::vector<MCWin64EHInstruction> &instArray){
24  uint8_t count = 0;
25  for (std::vector<MCWin64EHInstruction>::const_iterator I = instArray.begin(),
26       E = instArray.end(); I != E; ++I) {
27    switch (I->getOperation()) {
28    case Win64EH::UOP_PushNonVol:
29    case Win64EH::UOP_AllocSmall:
30    case Win64EH::UOP_SetFPReg:
31    case Win64EH::UOP_PushMachFrame:
32      count += 1;
33      break;
34    case Win64EH::UOP_SaveNonVol:
35    case Win64EH::UOP_SaveXMM128:
36      count += 2;
37      break;
38    case Win64EH::UOP_SaveNonVolBig:
39    case Win64EH::UOP_SaveXMM128Big:
40      count += 3;
41      break;
42    case Win64EH::UOP_AllocLarge:
43      if (I->getSize() > 512*1024-8)
44        count += 3;
45      else
46        count += 2;
47      break;
48    }
49  }
50  return count;
51}
52
53static void EmitAbsDifference(MCStreamer &streamer, MCSymbol *lhs,
54                              MCSymbol *rhs) {
55  MCContext &context = streamer.getContext();
56  const MCExpr *diff = MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(
57                                                                  lhs, context),
58                                               MCSymbolRefExpr::Create(
59                                                                  rhs, context),
60                                               context);
61  streamer.EmitAbsValue(diff, 1);
62
63}
64
65static void EmitUnwindCode(MCStreamer &streamer, MCSymbol *begin,
66                           MCWin64EHInstruction &inst) {
67  uint8_t b2;
68  uint16_t w;
69  b2 = (inst.getOperation() & 0x0F);
70  switch (inst.getOperation()) {
71  case Win64EH::UOP_PushNonVol:
72    EmitAbsDifference(streamer, inst.getLabel(), begin);
73    b2 |= (inst.getRegister() & 0x0F) << 4;
74    streamer.EmitIntValue(b2, 1);
75    break;
76  case Win64EH::UOP_AllocLarge:
77    EmitAbsDifference(streamer, inst.getLabel(), begin);
78    if (inst.getSize() > 512*1024-8) {
79      b2 |= 0x10;
80      streamer.EmitIntValue(b2, 1);
81      w = inst.getSize() & 0xFFF8;
82      streamer.EmitIntValue(w, 2);
83      w = inst.getSize() >> 16;
84    } else {
85      streamer.EmitIntValue(b2, 1);
86      w = inst.getSize() >> 3;
87    }
88    streamer.EmitIntValue(w, 2);
89    break;
90  case Win64EH::UOP_AllocSmall:
91    b2 |= (((inst.getSize()-8) >> 3) & 0x0F) << 4;
92    EmitAbsDifference(streamer, inst.getLabel(), begin);
93    streamer.EmitIntValue(b2, 1);
94    break;
95  case Win64EH::UOP_SetFPReg:
96    EmitAbsDifference(streamer, inst.getLabel(), begin);
97    streamer.EmitIntValue(b2, 1);
98    break;
99  case Win64EH::UOP_SaveNonVol:
100  case Win64EH::UOP_SaveXMM128:
101    b2 |= (inst.getRegister() & 0x0F) << 4;
102    EmitAbsDifference(streamer, inst.getLabel(), begin);
103    streamer.EmitIntValue(b2, 1);
104    w = inst.getOffset() >> 3;
105    if (inst.getOperation() == Win64EH::UOP_SaveXMM128)
106      w >>= 1;
107    streamer.EmitIntValue(w, 2);
108    break;
109  case Win64EH::UOP_SaveNonVolBig:
110  case Win64EH::UOP_SaveXMM128Big:
111    b2 |= (inst.getRegister() & 0x0F) << 4;
112    EmitAbsDifference(streamer, inst.getLabel(), begin);
113    streamer.EmitIntValue(b2, 1);
114    if (inst.getOperation() == Win64EH::UOP_SaveXMM128Big)
115      w = inst.getOffset() & 0xFFF0;
116    else
117      w = inst.getOffset() & 0xFFF8;
118    streamer.EmitIntValue(w, 2);
119    w = inst.getOffset() >> 16;
120    streamer.EmitIntValue(w, 2);
121    break;
122  case Win64EH::UOP_PushMachFrame:
123    if (inst.isPushCodeFrame())
124      b2 |= 0x10;
125    EmitAbsDifference(streamer, inst.getLabel(), begin);
126    streamer.EmitIntValue(b2, 1);
127    break;
128  }
129}
130
131static void EmitSymbolRefWithOfs(MCStreamer &streamer,
132                                 const MCSymbol *Base,
133                                 const MCSymbol *Other) {
134  MCContext &Context = streamer.getContext();
135  const MCSymbolRefExpr *BaseRef = MCSymbolRefExpr::Create(Base, Context);
136  const MCSymbolRefExpr *OtherRef = MCSymbolRefExpr::Create(Other, Context);
137  const MCExpr *Ofs = MCBinaryExpr::CreateSub(OtherRef, BaseRef, Context);
138  const MCSymbolRefExpr *BaseRefRel = MCSymbolRefExpr::Create(Base,
139                                              MCSymbolRefExpr::VK_COFF_IMGREL32,
140                                              Context);
141  streamer.EmitValue(MCBinaryExpr::CreateAdd(BaseRefRel, Ofs, Context), 4);
142}
143
144static void EmitRuntimeFunction(MCStreamer &streamer,
145                                const MCWin64EHUnwindInfo *info) {
146  MCContext &context = streamer.getContext();
147
148  streamer.EmitValueToAlignment(4);
149  EmitSymbolRefWithOfs(streamer, info->Function, info->Begin);
150  EmitSymbolRefWithOfs(streamer, info->Function, info->End);
151  streamer.EmitValue(MCSymbolRefExpr::Create(info->Symbol,
152                                             MCSymbolRefExpr::VK_COFF_IMGREL32,
153                                             context), 4);
154}
155
156static void EmitUnwindInfo(MCStreamer &streamer, MCWin64EHUnwindInfo *info) {
157  // If this UNWIND_INFO already has a symbol, it's already been emitted.
158  if (info->Symbol) return;
159
160  MCContext &context = streamer.getContext();
161  streamer.EmitValueToAlignment(4);
162  // Upper 3 bits are the version number (currently 1).
163  uint8_t flags = 0x01;
164  info->Symbol = context.CreateTempSymbol();
165  streamer.EmitLabel(info->Symbol);
166
167  if (info->ChainedParent)
168    flags |= Win64EH::UNW_ChainInfo << 3;
169  else {
170    if (info->HandlesUnwind)
171      flags |= Win64EH::UNW_TerminateHandler << 3;
172    if (info->HandlesExceptions)
173      flags |= Win64EH::UNW_ExceptionHandler << 3;
174  }
175  streamer.EmitIntValue(flags, 1);
176
177  if (info->PrologEnd)
178    EmitAbsDifference(streamer, info->PrologEnd, info->Begin);
179  else
180    streamer.EmitIntValue(0, 1);
181
182  uint8_t numCodes = CountOfUnwindCodes(info->Instructions);
183  streamer.EmitIntValue(numCodes, 1);
184
185  uint8_t frame = 0;
186  if (info->LastFrameInst >= 0) {
187    MCWin64EHInstruction &frameInst = info->Instructions[info->LastFrameInst];
188    assert(frameInst.getOperation() == Win64EH::UOP_SetFPReg);
189    frame = (frameInst.getRegister() & 0x0F) |
190            (frameInst.getOffset() & 0xF0);
191  }
192  streamer.EmitIntValue(frame, 1);
193
194  // Emit unwind instructions (in reverse order).
195  uint8_t numInst = info->Instructions.size();
196  for (uint8_t c = 0; c < numInst; ++c) {
197    MCWin64EHInstruction inst = info->Instructions.back();
198    info->Instructions.pop_back();
199    EmitUnwindCode(streamer, info->Begin, inst);
200  }
201
202  if (flags & (Win64EH::UNW_ChainInfo << 3))
203    EmitRuntimeFunction(streamer, info->ChainedParent);
204  else if (flags &
205           ((Win64EH::UNW_TerminateHandler|Win64EH::UNW_ExceptionHandler) << 3))
206    streamer.EmitValue(MCSymbolRefExpr::Create(info->ExceptionHandler,
207                                              MCSymbolRefExpr::VK_COFF_IMGREL32,
208                                              context), 4);
209  else if (numCodes < 2) {
210    // The minimum size of an UNWIND_INFO struct is 8 bytes. If we're not
211    // a chained unwind info, if there is no handler, and if there are fewer
212    // than 2 slots used in the unwind code array, we have to pad to 8 bytes.
213    if (numCodes == 1)
214      streamer.EmitIntValue(0, 2);
215    else
216      streamer.EmitIntValue(0, 4);
217  }
218}
219
220StringRef MCWin64EHUnwindEmitter::GetSectionSuffix(const MCSymbol *func) {
221  if (!func || !func->isInSection()) return "";
222  const MCSection *section = &func->getSection();
223  const MCSectionCOFF *COFFSection;
224  if ((COFFSection = dyn_cast<MCSectionCOFF>(section))) {
225    StringRef name = COFFSection->getSectionName();
226    size_t dollar = name.find('$');
227    size_t dot = name.find('.', 1);
228    if (dollar == StringRef::npos && dot == StringRef::npos)
229      return "";
230    if (dot == StringRef::npos)
231      return name.substr(dollar);
232    if (dollar == StringRef::npos || dot < dollar)
233      return name.substr(dot);
234    return name.substr(dollar);
235  }
236  return "";
237}
238
239static const MCSection *getWin64EHTableSection(StringRef suffix,
240                                               MCContext &context) {
241  if (suffix == "")
242    return context.getObjectFileInfo()->getXDataSection();
243
244  return context.getCOFFSection((".xdata"+suffix).str(),
245                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
246                                COFF::IMAGE_SCN_MEM_READ,
247                                SectionKind::getDataRel());
248}
249
250static const MCSection *getWin64EHFuncTableSection(StringRef suffix,
251                                                   MCContext &context) {
252  if (suffix == "")
253    return context.getObjectFileInfo()->getPDataSection();
254  return context.getCOFFSection((".pdata"+suffix).str(),
255                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
256                                COFF::IMAGE_SCN_MEM_READ,
257                                SectionKind::getDataRel());
258}
259
260void MCWin64EHUnwindEmitter::EmitUnwindInfo(MCStreamer &streamer,
261                                            MCWin64EHUnwindInfo *info) {
262  // Switch sections (the static function above is meant to be called from
263  // here and from Emit().
264  MCContext &context = streamer.getContext();
265  const MCSection *xdataSect =
266    getWin64EHTableSection(GetSectionSuffix(info->Function), context);
267  streamer.SwitchSection(xdataSect);
268
269  llvm::EmitUnwindInfo(streamer, info);
270}
271
272void MCWin64EHUnwindEmitter::Emit(MCStreamer &streamer) {
273  MCContext &context = streamer.getContext();
274  // Emit the unwind info structs first.
275  for (unsigned i = 0; i < streamer.getNumW64UnwindInfos(); ++i) {
276    MCWin64EHUnwindInfo &info = streamer.getW64UnwindInfo(i);
277    const MCSection *xdataSect =
278      getWin64EHTableSection(GetSectionSuffix(info.Function), context);
279    streamer.SwitchSection(xdataSect);
280    llvm::EmitUnwindInfo(streamer, &info);
281  }
282  // Now emit RUNTIME_FUNCTION entries.
283  for (unsigned i = 0; i < streamer.getNumW64UnwindInfos(); ++i) {
284    MCWin64EHUnwindInfo &info = streamer.getW64UnwindInfo(i);
285    const MCSection *pdataSect =
286      getWin64EHFuncTableSection(GetSectionSuffix(info.Function), context);
287    streamer.SwitchSection(pdataSect);
288    EmitRuntimeFunction(streamer, &info);
289  }
290}
291
292} // End of namespace llvm
293
294