1 //===- lib/MC/MCWin64EH.cpp - MCWin64EH implementation --------------------===//
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 #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/MCObjectStreamer.h"
16 #include "llvm/MC/MCSectionCOFF.h"
17 #include "llvm/MC/MCStreamer.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/Support/Win64EH.h"
23 // NOTE: All relocations generated here are 4-byte image-relative.
25 static uint8_t CountOfUnwindCodes(std::vector<WinEH::Instruction> &Insns) {
27 for (const auto &I : Insns) {
28 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
30 llvm_unreachable("Unsupported unwind code");
31 case Win64EH::UOP_PushNonVol:
32 case Win64EH::UOP_AllocSmall:
33 case Win64EH::UOP_SetFPReg:
34 case Win64EH::UOP_PushMachFrame:
37 case Win64EH::UOP_SaveNonVol:
38 case Win64EH::UOP_SaveXMM128:
41 case Win64EH::UOP_SaveNonVolBig:
42 case Win64EH::UOP_SaveXMM128Big:
45 case Win64EH::UOP_AllocLarge:
46 Count += (I.Offset > 512 * 1024 - 8) ? 3 : 2;
53 static void EmitAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS,
54 const MCSymbol *RHS) {
55 MCContext &Context = Streamer.getContext();
57 MCBinaryExpr::createSub(MCSymbolRefExpr::create(LHS, Context),
58 MCSymbolRefExpr::create(RHS, Context), Context);
59 Streamer.EmitValue(Diff, 1);
62 static void EmitUnwindCode(MCStreamer &streamer, const MCSymbol *begin,
63 WinEH::Instruction &inst) {
66 b2 = (inst.Operation & 0x0F);
67 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
69 llvm_unreachable("Unsupported unwind code");
70 case Win64EH::UOP_PushNonVol:
71 EmitAbsDifference(streamer, inst.Label, begin);
72 b2 |= (inst.Register & 0x0F) << 4;
73 streamer.EmitIntValue(b2, 1);
75 case Win64EH::UOP_AllocLarge:
76 EmitAbsDifference(streamer, inst.Label, begin);
77 if (inst.Offset > 512 * 1024 - 8) {
79 streamer.EmitIntValue(b2, 1);
80 w = inst.Offset & 0xFFF8;
81 streamer.EmitIntValue(w, 2);
82 w = inst.Offset >> 16;
84 streamer.EmitIntValue(b2, 1);
87 streamer.EmitIntValue(w, 2);
89 case Win64EH::UOP_AllocSmall:
90 b2 |= (((inst.Offset - 8) >> 3) & 0x0F) << 4;
91 EmitAbsDifference(streamer, inst.Label, begin);
92 streamer.EmitIntValue(b2, 1);
94 case Win64EH::UOP_SetFPReg:
95 EmitAbsDifference(streamer, inst.Label, begin);
96 streamer.EmitIntValue(b2, 1);
98 case Win64EH::UOP_SaveNonVol:
99 case Win64EH::UOP_SaveXMM128:
100 b2 |= (inst.Register & 0x0F) << 4;
101 EmitAbsDifference(streamer, inst.Label, begin);
102 streamer.EmitIntValue(b2, 1);
103 w = inst.Offset >> 3;
104 if (inst.Operation == Win64EH::UOP_SaveXMM128)
106 streamer.EmitIntValue(w, 2);
108 case Win64EH::UOP_SaveNonVolBig:
109 case Win64EH::UOP_SaveXMM128Big:
110 b2 |= (inst.Register & 0x0F) << 4;
111 EmitAbsDifference(streamer, inst.Label, begin);
112 streamer.EmitIntValue(b2, 1);
113 if (inst.Operation == Win64EH::UOP_SaveXMM128Big)
114 w = inst.Offset & 0xFFF0;
116 w = inst.Offset & 0xFFF8;
117 streamer.EmitIntValue(w, 2);
118 w = inst.Offset >> 16;
119 streamer.EmitIntValue(w, 2);
121 case Win64EH::UOP_PushMachFrame:
122 if (inst.Offset == 1)
124 EmitAbsDifference(streamer, inst.Label, begin);
125 streamer.EmitIntValue(b2, 1);
130 static void EmitSymbolRefWithOfs(MCStreamer &streamer,
131 const MCSymbol *Base,
132 const MCSymbol *Other) {
133 MCContext &Context = streamer.getContext();
134 const MCSymbolRefExpr *BaseRef = MCSymbolRefExpr::create(Base, Context);
135 const MCSymbolRefExpr *OtherRef = MCSymbolRefExpr::create(Other, Context);
136 const MCExpr *Ofs = MCBinaryExpr::createSub(OtherRef, BaseRef, Context);
137 const MCSymbolRefExpr *BaseRefRel = MCSymbolRefExpr::create(Base,
138 MCSymbolRefExpr::VK_COFF_IMGREL32,
140 streamer.EmitValue(MCBinaryExpr::createAdd(BaseRefRel, Ofs, Context), 4);
143 static void EmitRuntimeFunction(MCStreamer &streamer,
144 const WinEH::FrameInfo *info) {
145 MCContext &context = streamer.getContext();
147 streamer.EmitValueToAlignment(4);
148 EmitSymbolRefWithOfs(streamer, info->Function, info->Begin);
149 EmitSymbolRefWithOfs(streamer, info->Function, info->End);
150 streamer.EmitValue(MCSymbolRefExpr::create(info->Symbol,
151 MCSymbolRefExpr::VK_COFF_IMGREL32,
155 static void EmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info) {
156 // If this UNWIND_INFO already has a symbol, it's already been emitted.
160 MCContext &context = streamer.getContext();
161 MCSymbol *Label = context.createTempSymbol();
163 streamer.EmitValueToAlignment(4);
164 streamer.EmitLabel(Label);
165 info->Symbol = Label;
167 // Upper 3 bits are the version number (currently 1).
168 uint8_t flags = 0x01;
169 if (info->ChainedParent)
170 flags |= Win64EH::UNW_ChainInfo << 3;
172 if (info->HandlesUnwind)
173 flags |= Win64EH::UNW_TerminateHandler << 3;
174 if (info->HandlesExceptions)
175 flags |= Win64EH::UNW_ExceptionHandler << 3;
177 streamer.EmitIntValue(flags, 1);
180 EmitAbsDifference(streamer, info->PrologEnd, info->Begin);
182 streamer.EmitIntValue(0, 1);
184 uint8_t numCodes = CountOfUnwindCodes(info->Instructions);
185 streamer.EmitIntValue(numCodes, 1);
188 if (info->LastFrameInst >= 0) {
189 WinEH::Instruction &frameInst = info->Instructions[info->LastFrameInst];
190 assert(frameInst.Operation == Win64EH::UOP_SetFPReg);
191 frame = (frameInst.Register & 0x0F) | (frameInst.Offset & 0xF0);
193 streamer.EmitIntValue(frame, 1);
195 // Emit unwind instructions (in reverse order).
196 uint8_t numInst = info->Instructions.size();
197 for (uint8_t c = 0; c < numInst; ++c) {
198 WinEH::Instruction inst = info->Instructions.back();
199 info->Instructions.pop_back();
200 EmitUnwindCode(streamer, info->Begin, inst);
203 // For alignment purposes, the instruction array will always have an even
204 // number of entries, with the final entry potentially unused (in which case
205 // the array will be one longer than indicated by the count of unwind codes
208 streamer.EmitIntValue(0, 2);
211 if (flags & (Win64EH::UNW_ChainInfo << 3))
212 EmitRuntimeFunction(streamer, info->ChainedParent);
214 ((Win64EH::UNW_TerminateHandler|Win64EH::UNW_ExceptionHandler) << 3))
215 streamer.EmitValue(MCSymbolRefExpr::create(info->ExceptionHandler,
216 MCSymbolRefExpr::VK_COFF_IMGREL32,
218 else if (numCodes == 0) {
219 // The minimum size of an UNWIND_INFO struct is 8 bytes. If we're not
220 // a chained unwind info, if there is no handler, and if there are fewer
221 // than 2 slots used in the unwind code array, we have to pad to 8 bytes.
222 streamer.EmitIntValue(0, 4);
226 void llvm::Win64EH::UnwindEmitter::Emit(MCStreamer &Streamer) const {
227 // Emit the unwind info structs first.
228 for (const auto &CFI : Streamer.getWinFrameInfos()) {
229 MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection);
230 Streamer.SwitchSection(XData);
231 ::EmitUnwindInfo(Streamer, CFI.get());
234 // Now emit RUNTIME_FUNCTION entries.
235 for (const auto &CFI : Streamer.getWinFrameInfos()) {
236 MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection);
237 Streamer.SwitchSection(PData);
238 EmitRuntimeFunction(Streamer, CFI.get());
242 void llvm::Win64EH::UnwindEmitter::EmitUnwindInfo(
243 MCStreamer &Streamer, WinEH::FrameInfo *info) const {
244 // Switch sections (the static function above is meant to be called from
245 // here and from Emit().
246 MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection);
247 Streamer.SwitchSection(XData);
249 ::EmitUnwindInfo(Streamer, info);
252 static int64_t GetAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS,
253 const MCSymbol *RHS) {
254 MCContext &Context = Streamer.getContext();
256 MCBinaryExpr::createSub(MCSymbolRefExpr::create(LHS, Context),
257 MCSymbolRefExpr::create(RHS, Context), Context);
258 MCObjectStreamer *OS = (MCObjectStreamer *)(&Streamer);
260 Diff->evaluateAsAbsolute(value, OS->getAssembler());
265 ARM64CountOfUnwindCodes(const std::vector<WinEH::Instruction> &Insns) {
267 for (const auto &I : Insns) {
268 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
270 llvm_unreachable("Unsupported ARM64 unwind code");
271 case Win64EH::UOP_AllocSmall:
274 case Win64EH::UOP_AllocMedium:
277 case Win64EH::UOP_AllocLarge:
280 case Win64EH::UOP_SaveFPLRX:
283 case Win64EH::UOP_SaveFPLR:
286 case Win64EH::UOP_SaveReg:
289 case Win64EH::UOP_SaveRegP:
292 case Win64EH::UOP_SaveRegPX:
295 case Win64EH::UOP_SaveRegX:
298 case Win64EH::UOP_SaveFReg:
301 case Win64EH::UOP_SaveFRegP:
304 case Win64EH::UOP_SaveFRegX:
307 case Win64EH::UOP_SaveFRegPX:
310 case Win64EH::UOP_SetFP:
313 case Win64EH::UOP_AddFP:
316 case Win64EH::UOP_Nop:
319 case Win64EH::UOP_End:
327 // Unwind opcode encodings and restrictions are documented at
328 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
329 static void ARM64EmitUnwindCode(MCStreamer &streamer, const MCSymbol *begin,
330 WinEH::Instruction &inst) {
332 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
334 llvm_unreachable("Unsupported ARM64 unwind code");
335 case Win64EH::UOP_AllocSmall:
336 b = (inst.Offset >> 4) & 0x1F;
337 streamer.EmitIntValue(b, 1);
339 case Win64EH::UOP_AllocMedium: {
340 uint16_t hw = (inst.Offset >> 4) & 0x7FF;
343 streamer.EmitIntValue(b, 1);
345 streamer.EmitIntValue(b, 1);
348 case Win64EH::UOP_AllocLarge: {
351 streamer.EmitIntValue(b, 1);
352 w = inst.Offset >> 4;
353 b = (w & 0x00FF0000) >> 16;
354 streamer.EmitIntValue(b, 1);
355 b = (w & 0x0000FF00) >> 8;
356 streamer.EmitIntValue(b, 1);
358 streamer.EmitIntValue(b, 1);
361 case Win64EH::UOP_SetFP:
363 streamer.EmitIntValue(b, 1);
365 case Win64EH::UOP_AddFP:
367 streamer.EmitIntValue(b, 1);
368 b = (inst.Offset >> 3);
369 streamer.EmitIntValue(b, 1);
371 case Win64EH::UOP_Nop:
373 streamer.EmitIntValue(b, 1);
375 case Win64EH::UOP_SaveFPLRX:
377 b |= ((inst.Offset - 1) >> 3) & 0x3F;
378 streamer.EmitIntValue(b, 1);
380 case Win64EH::UOP_SaveFPLR:
382 b |= (inst.Offset >> 3) & 0x3F;
383 streamer.EmitIntValue(b, 1);
385 case Win64EH::UOP_SaveReg:
386 assert(inst.Register >= 19 && "Saved reg must be >= 19");
387 reg = inst.Register - 19;
388 b = 0xD0 | ((reg & 0xC) >> 2);
389 streamer.EmitIntValue(b, 1);
390 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
391 streamer.EmitIntValue(b, 1);
393 case Win64EH::UOP_SaveRegX:
394 assert(inst.Register >= 19 && "Saved reg must be >= 19");
395 reg = inst.Register - 19;
396 b = 0xD4 | ((reg & 0x8) >> 3);
397 streamer.EmitIntValue(b, 1);
398 b = ((reg & 0x7) << 5) | ((inst.Offset >> 3) - 1);
399 streamer.EmitIntValue(b, 1);
401 case Win64EH::UOP_SaveRegP:
402 assert(inst.Register >= 19 && "Saved registers must be >= 19");
403 reg = inst.Register - 19;
404 b = 0xC8 | ((reg & 0xC) >> 2);
405 streamer.EmitIntValue(b, 1);
406 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
407 streamer.EmitIntValue(b, 1);
409 case Win64EH::UOP_SaveRegPX:
410 assert(inst.Register >= 19 && "Saved registers must be >= 19");
411 reg = inst.Register - 19;
412 b = 0xCC | ((reg & 0xC) >> 2);
413 streamer.EmitIntValue(b, 1);
414 b = ((reg & 0x3) << 6) | ((inst.Offset >> 3) - 1);
415 streamer.EmitIntValue(b, 1);
417 case Win64EH::UOP_SaveFReg:
418 assert(inst.Register >= 8 && "Saved dreg must be >= 8");
419 reg = inst.Register - 8;
420 b = 0xDC | ((reg & 0x4) >> 2);
421 streamer.EmitIntValue(b, 1);
422 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
423 streamer.EmitIntValue(b, 1);
425 case Win64EH::UOP_SaveFRegX:
426 assert(inst.Register >= 8 && "Saved dreg must be >= 8");
427 reg = inst.Register - 8;
429 streamer.EmitIntValue(b, 1);
430 b = ((reg & 0x7) << 5) | ((inst.Offset >> 3) - 1);
431 streamer.EmitIntValue(b, 1);
433 case Win64EH::UOP_SaveFRegP:
434 assert(inst.Register >= 8 && "Saved dregs must be >= 8");
435 reg = inst.Register - 8;
436 b = 0xD8 | ((reg & 0x4) >> 2);
437 streamer.EmitIntValue(b, 1);
438 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
439 streamer.EmitIntValue(b, 1);
441 case Win64EH::UOP_SaveFRegPX:
442 assert(inst.Register >= 8 && "Saved dregs must be >= 8");
443 reg = inst.Register - 8;
444 b = 0xDA | ((reg & 0x4) >> 2);
445 streamer.EmitIntValue(b, 1);
446 b = ((reg & 0x3) << 6) | ((inst.Offset >> 3) - 1);
447 streamer.EmitIntValue(b, 1);
449 case Win64EH::UOP_End:
451 streamer.EmitIntValue(b, 1);
456 // Returns the epilog symbol of an epilog with the exact same unwind code
457 // sequence, if it exists. Otherwise, returns nulltpr.
458 // EpilogInstrs - Unwind codes for the current epilog.
459 // Epilogs - Epilogs that potentialy match the current epilog.
461 FindMatchingEpilog(const std::vector<WinEH::Instruction>& EpilogInstrs,
462 const std::vector<MCSymbol *>& Epilogs,
463 const WinEH::FrameInfo *info) {
464 for (auto *EpilogStart : Epilogs) {
465 auto InstrsIter = info->EpilogMap.find(EpilogStart);
466 assert(InstrsIter != info->EpilogMap.end() &&
467 "Epilog not found in EpilogMap");
468 const auto &Instrs = InstrsIter->second;
470 if (Instrs.size() != EpilogInstrs.size())
474 for (unsigned i = 0; i < Instrs.size(); ++i)
475 if (Instrs[i].Operation != EpilogInstrs[i].Operation ||
476 Instrs[i].Offset != EpilogInstrs[i].Offset ||
477 Instrs[i].Register != EpilogInstrs[i].Register) {
488 // Populate the .xdata section. The format of .xdata on ARM64 is documented at
489 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
490 static void ARM64EmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info) {
491 // If this UNWIND_INFO already has a symbol, it's already been emitted.
495 MCContext &context = streamer.getContext();
496 MCSymbol *Label = context.createTempSymbol();
498 streamer.EmitValueToAlignment(4);
499 streamer.EmitLabel(Label);
500 info->Symbol = Label;
502 uint32_t FuncLength = 0x0;
503 if (info->FuncletOrFuncEnd)
504 FuncLength = (uint32_t)GetAbsDifference(streamer, info->FuncletOrFuncEnd,
507 uint32_t PrologCodeBytes = ARM64CountOfUnwindCodes(info->Instructions);
508 uint32_t TotalCodeBytes = PrologCodeBytes;
511 MapVector<MCSymbol *, uint32_t> EpilogInfo;
512 // Epilogs processed so far.
513 std::vector<MCSymbol *> AddedEpilogs;
515 for (auto &I : info->EpilogMap) {
516 MCSymbol *EpilogStart = I.first;
517 auto &EpilogInstrs = I.second;
518 uint32_t CodeBytes = ARM64CountOfUnwindCodes(EpilogInstrs);
520 MCSymbol* MatchingEpilog =
521 FindMatchingEpilog(EpilogInstrs, AddedEpilogs, info);
522 if (MatchingEpilog) {
523 assert(EpilogInfo.find(MatchingEpilog) != EpilogInfo.end() &&
524 "Duplicate epilog not found");
525 EpilogInfo[EpilogStart] = EpilogInfo[MatchingEpilog];
526 // Clear the unwind codes in the EpilogMap, so that they don't get output
527 // in the logic below.
528 EpilogInstrs.clear();
530 EpilogInfo[EpilogStart] = TotalCodeBytes;
531 TotalCodeBytes += CodeBytes;
532 AddedEpilogs.push_back(EpilogStart);
536 // Code Words, Epilog count, E, X, Vers, Function Length
538 uint32_t CodeWords = TotalCodeBytes / 4;
539 uint32_t CodeWordsMod = TotalCodeBytes % 4;
542 uint32_t EpilogCount = info->EpilogMap.size();
543 bool ExtensionWord = EpilogCount > 31 || TotalCodeBytes > 124;
544 if (!ExtensionWord) {
545 row1 |= (EpilogCount & 0x1F) << 22;
546 row1 |= (CodeWords & 0x1F) << 27;
548 // E is always 0 right now, TODO: packed epilog setup
549 if (info->HandlesExceptions) // X
551 row1 |= FuncLength & 0x3FFFF;
552 streamer.EmitIntValue(row1, 4);
554 // Extended Code Words, Extended Epilog Count
556 // FIXME: We should be able to split unwind info into multiple sections.
557 // FIXME: We should share epilog codes across epilogs, where possible,
558 // which would make this issue show up less frequently.
559 if (CodeWords > 0xFF || EpilogCount > 0xFFFF)
560 report_fatal_error("SEH unwind data splitting not yet implemented");
562 row2 |= (CodeWords & 0xFF) << 16;
563 row2 |= (EpilogCount & 0xFFFF);
564 streamer.EmitIntValue(row2, 4);
567 // Epilog Start Index, Epilog Start Offset
568 for (auto &I : EpilogInfo) {
569 MCSymbol *EpilogStart = I.first;
570 uint32_t EpilogIndex = I.second;
571 uint32_t EpilogOffset =
572 (uint32_t)GetAbsDifference(streamer, EpilogStart, info->Begin);
575 uint32_t row3 = EpilogOffset;
576 row3 |= (EpilogIndex & 0x3FF) << 22;
577 streamer.EmitIntValue(row3, 4);
580 // Emit prolog unwind instructions (in reverse order).
581 uint8_t numInst = info->Instructions.size();
582 for (uint8_t c = 0; c < numInst; ++c) {
583 WinEH::Instruction inst = info->Instructions.back();
584 info->Instructions.pop_back();
585 ARM64EmitUnwindCode(streamer, info->Begin, inst);
588 // Emit epilog unwind instructions
589 for (auto &I : info->EpilogMap) {
590 auto &EpilogInstrs = I.second;
591 for (uint32_t i = 0; i < EpilogInstrs.size(); i++) {
592 WinEH::Instruction inst = EpilogInstrs[i];
593 ARM64EmitUnwindCode(streamer, info->Begin, inst);
597 int32_t BytesMod = CodeWords * 4 - TotalCodeBytes;
598 assert(BytesMod >= 0);
599 for (int i = 0; i < BytesMod; i++)
600 streamer.EmitIntValue(0xE3, 1);
602 if (info->HandlesExceptions)
604 MCSymbolRefExpr::create(info->ExceptionHandler,
605 MCSymbolRefExpr::VK_COFF_IMGREL32, context),
609 static void ARM64EmitRuntimeFunction(MCStreamer &streamer,
610 const WinEH::FrameInfo *info) {
611 MCContext &context = streamer.getContext();
613 streamer.EmitValueToAlignment(4);
614 EmitSymbolRefWithOfs(streamer, info->Function, info->Begin);
615 streamer.EmitValue(MCSymbolRefExpr::create(info->Symbol,
616 MCSymbolRefExpr::VK_COFF_IMGREL32,
621 void llvm::Win64EH::ARM64UnwindEmitter::Emit(MCStreamer &Streamer) const {
622 // Emit the unwind info structs first.
623 for (const auto &CFI : Streamer.getWinFrameInfos()) {
624 MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection);
625 Streamer.SwitchSection(XData);
626 ARM64EmitUnwindInfo(Streamer, CFI.get());
629 // Now emit RUNTIME_FUNCTION entries.
630 for (const auto &CFI : Streamer.getWinFrameInfos()) {
631 MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection);
632 Streamer.SwitchSection(PData);
633 ARM64EmitRuntimeFunction(Streamer, CFI.get());
637 void llvm::Win64EH::ARM64UnwindEmitter::EmitUnwindInfo(
638 MCStreamer &Streamer, WinEH::FrameInfo *info) const {
639 // Switch sections (the static function above is meant to be called from
640 // here and from Emit().
641 MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection);
642 Streamer.SwitchSection(XData);
643 ARM64EmitUnwindInfo(Streamer, info);