LLVM 24.0.0git
MCWin64EH.cpp
Go to the documentation of this file.
1//===- lib/MC/MCWin64EH.cpp - MCWin64EH implementation --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/MC/MCWin64EH.h"
10#include "llvm/ADT/Twine.h"
11#include "llvm/MC/MCAssembler.h"
12#include "llvm/MC/MCContext.h"
13#include "llvm/MC/MCExpr.h"
15#include "llvm/MC/MCStreamer.h"
16#include "llvm/MC/MCSymbol.h"
17#include "llvm/MC/MCValue.h"
20
21namespace llvm {
22class MCSection;
23}
24
25using namespace llvm;
26
27namespace {
28/// MCExpr that represents the epilog unwind code in an unwind table.
29class MCUnwindV2EpilogTargetExpr final : public MCTargetExpr {
30 const WinEH::FrameInfo &FrameInfo;
31 const MCSymbol *UnwindV2Start;
32 const MCSymbol *EpilogEnd;
33 uint8_t EpilogSize;
34 SMLoc Loc;
35
36 MCUnwindV2EpilogTargetExpr(const WinEH::FrameInfo &FrameInfo,
37 const WinEH::FrameInfo::Epilog &Epilog,
38 uint8_t EpilogSize_)
39 : FrameInfo(FrameInfo), UnwindV2Start(Epilog.UnwindV2Start),
40 EpilogEnd(Epilog.End), EpilogSize(EpilogSize_), Loc(Epilog.Loc) {
41 assert(UnwindV2Start && "Epilog must have a start");
42 assert(EpilogEnd && "Epilog must have an end");
43 }
44
45public:
46 static MCUnwindV2EpilogTargetExpr *
47 create(const WinEH::FrameInfo &FrameInfo,
48 const WinEH::FrameInfo::Epilog &Epilog, uint8_t EpilogSize_,
49 MCContext &Ctx) {
50 return new (Ctx) MCUnwindV2EpilogTargetExpr(FrameInfo, Epilog, EpilogSize_);
51 }
52
53 void printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const override {
54 OS << ":epilog:";
55 UnwindV2Start->print(OS, MAI);
56 }
57
58 bool evaluateAsRelocatableImpl(MCValue &Res,
59 const MCAssembler *Asm) const override;
60
61 void visitUsedExpr(MCStreamer &Streamer) const override {
62 // Contains no sub-expressions.
63 }
64
65 MCFragment *findAssociatedFragment() const override {
66 return UnwindV2Start->getFragment();
67 }
68};
69
70/// MCExpr representing a V3 epilog's tail-relative EpilogOffset field. The
71/// first epilog descriptor is encoded relative to the fragment end, and each
72/// subsequent descriptor relative to the previous epilog's start. Measuring
73/// from the tail keeps the magnitude small (epilogs sit near the end of the
74/// function), avoiding overflow of the signed 16-bit field for large
75/// functions. The fragment end may not have a symbol yet when the unwind info
76/// is emitted (e.g. via .seh_handlerdata), so the value is resolved lazily
77/// through the FrameInfo reference.
78class MCUnwindV3EpilogOffsetTargetExpr final : public MCTargetExpr {
79 const WinEH::FrameInfo &FrameInfo;
80 const MCSymbol *EpilogStart;
81 const MCSymbol *PrevEpilogStart;
82 SMLoc Loc;
83
84 MCUnwindV3EpilogOffsetTargetExpr(const WinEH::FrameInfo &FrameInfo,
85 const MCSymbol *EpilogStart,
86 const MCSymbol *PrevEpilogStart, SMLoc Loc)
87 : FrameInfo(FrameInfo), EpilogStart(EpilogStart),
88 PrevEpilogStart(PrevEpilogStart), Loc(Loc) {}
89
90public:
91 static MCUnwindV3EpilogOffsetTargetExpr *
92 create(const WinEH::FrameInfo &FrameInfo, const MCSymbol *EpilogStart,
93 const MCSymbol *PrevEpilogStart, SMLoc Loc, MCContext &Ctx) {
94 return new (Ctx) MCUnwindV3EpilogOffsetTargetExpr(FrameInfo, EpilogStart,
95 PrevEpilogStart, Loc);
96 }
97
98 void printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const override {
99 OS << ":epilogoffset:";
100 EpilogStart->print(OS, MAI);
101 }
102
103 bool evaluateAsRelocatableImpl(MCValue &Res,
104 const MCAssembler *Asm) const override;
105
106 void visitUsedExpr(MCStreamer &Streamer) const override {
107 // Contains no sub-expressions.
108 }
109
110 MCFragment *findAssociatedFragment() const override {
111 return EpilogStart->getFragment();
112 }
113};
114} // namespace
115
116// NOTE: All relocations generated here are 4-byte image-relative.
117
118static uint8_t CountOfUnwindCodes(std::vector<WinEH::Instruction> &Insns) {
119 uint8_t Count = 0;
120 for (const auto &I : Insns) {
121 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
122 default:
123 llvm_unreachable("Unsupported unwind code");
128 Count += 1;
129 break;
132 Count += 2;
133 break;
136 Count += 3;
137 break;
139 Count += (I.Offset > 512 * 1024 - 8) ? 3 : 2;
140 break;
141 }
142 }
143 return Count;
144}
145
147 const MCSymbol *RHS) {
148 MCContext &Context = Streamer.getContext();
149 const MCExpr *Diff =
151 MCSymbolRefExpr::create(RHS, Context), Context);
152 Streamer.emitValue(Diff, 1);
153}
154
155/// Emit a 16-bit (2-byte LE) label difference. If the difference is
156/// evaluatable at this point, validate that it fits in [0, UINT16_MAX]
157/// and emit it as a constant; otherwise emit a 16-bit fixup.
159 const MCSymbol *RHS) {
160 MCContext &Context = Streamer.getContext();
161 const MCExpr *Diff =
163 MCSymbolRefExpr::create(RHS, Context), Context);
164 int64_t Value;
165 if (Diff->evaluateAsAbsolute(
166 Value, static_cast<MCObjectStreamer &>(Streamer).getAssembler())) {
167 if (Value < 0 || Value > UINT16_MAX)
168 Context.reportError(
169 SMLoc(),
170 "Label difference out of 16-bit unsigned range for V3 unwind info");
171 }
172 // Always emit a 2-byte value so subsequent emission stays in sync; if a
173 // diagnostic was reported, the object file will be discarded by the caller.
174 Streamer.emitValue(Diff, 2);
175}
176
177static void EmitUnwindCode(MCStreamer &streamer, const MCSymbol *begin,
178 WinEH::Instruction &inst) {
179 uint8_t b2;
180 uint16_t w;
181 b2 = (inst.Operation & 0x0F);
182 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
183 default:
184 llvm_unreachable("Unsupported unwind code");
186 // Reachable from hand-written .s if a UOP_Push2 ends up in a V1/V2
187 // frame (e.g. via a per-function `.seh_unwindversion` downgrade after
188 // `.seh_push2regs`). Emit a recoverable diagnostic and skip the op so
189 // the assembler doesn't keep writing malformed bytes.
190 streamer.getContext().reportError(
191 SMLoc(), "UOP_Push2 (PUSH2 with two registers) requires V3 unwind "
192 "info. Use `.seh_unwindversion 3`.");
193 return;
195 EmitAbsDifference(streamer, inst.Label, begin);
196 b2 |= (inst.Register & 0x0F) << 4;
197 streamer.emitInt8(b2);
198 break;
200 EmitAbsDifference(streamer, inst.Label, begin);
201 if (inst.Offset > 512 * 1024 - 8) {
202 b2 |= 0x10;
203 streamer.emitInt8(b2);
204 w = inst.Offset & 0xFFF8;
205 streamer.emitInt16(w);
206 w = inst.Offset >> 16;
207 } else {
208 streamer.emitInt8(b2);
209 w = inst.Offset >> 3;
210 }
211 streamer.emitInt16(w);
212 break;
214 b2 |= (((inst.Offset - 8) >> 3) & 0x0F) << 4;
215 EmitAbsDifference(streamer, inst.Label, begin);
216 streamer.emitInt8(b2);
217 break;
219 EmitAbsDifference(streamer, inst.Label, begin);
220 streamer.emitInt8(b2);
221 break;
224 b2 |= (inst.Register & 0x0F) << 4;
225 EmitAbsDifference(streamer, inst.Label, begin);
226 streamer.emitInt8(b2);
227 w = inst.Offset >> 3;
229 w >>= 1;
230 streamer.emitInt16(w);
231 break;
234 b2 |= (inst.Register & 0x0F) << 4;
235 EmitAbsDifference(streamer, inst.Label, begin);
236 streamer.emitInt8(b2);
238 w = inst.Offset & 0xFFF0;
239 else
240 w = inst.Offset & 0xFFF8;
241 streamer.emitInt16(w);
242 w = inst.Offset >> 16;
243 streamer.emitInt16(w);
244 break;
246 if (inst.Offset == 1)
247 b2 |= 0x10;
248 EmitAbsDifference(streamer, inst.Label, begin);
249 streamer.emitInt8(b2);
250 break;
251 }
252}
253
254static void EmitSymbolRefWithOfs(MCStreamer &streamer,
255 const MCSymbol *Base,
256 int64_t Offset) {
257 MCContext &Context = streamer.getContext();
258 const MCConstantExpr *OffExpr = MCConstantExpr::create(Offset, Context);
259 const MCSymbolRefExpr *BaseRefRel = MCSymbolRefExpr::create(Base,
261 Context);
262 streamer.emitValue(MCBinaryExpr::createAdd(BaseRefRel, OffExpr, Context), 4);
263}
264
265static void EmitSymbolRefWithOfs(MCStreamer &streamer,
266 const MCSymbol *Base,
267 const MCSymbol *Other) {
268 MCContext &Context = streamer.getContext();
269 const MCSymbolRefExpr *BaseRef = MCSymbolRefExpr::create(Base, Context);
270 const MCSymbolRefExpr *OtherRef = MCSymbolRefExpr::create(Other, Context);
271 const MCExpr *Ofs = MCBinaryExpr::createSub(OtherRef, BaseRef, Context);
272 const MCSymbolRefExpr *BaseRefRel = MCSymbolRefExpr::create(Base,
274 Context);
275 streamer.emitValue(MCBinaryExpr::createAdd(BaseRefRel, Ofs, Context), 4);
276}
277
278static void EmitRuntimeFunction(MCStreamer &streamer,
279 const WinEH::FrameInfo *info) {
280 MCContext &context = streamer.getContext();
281
282 streamer.emitValueToAlignment(Align(4));
283 EmitSymbolRefWithOfs(streamer, info->Begin, info->Begin);
284 EmitSymbolRefWithOfs(streamer, info->Begin, info->End);
285 streamer.emitValue(MCSymbolRefExpr::create(info->Symbol,
287 context), 4);
288}
289
290static std::optional<int64_t>
292 const MCSymbol *RHS) {
293 MCContext &Context = Assembler.getContext();
294 const MCExpr *Diff =
296 MCSymbolRefExpr::create(RHS, Context), Context);
297 // It should normally be possible to calculate the length of a function
298 // at this point, but it might not be possible in the presence of certain
299 // unusual constructs, like an inline asm with an alignment directive.
300 int64_t value;
301 if (!Diff->evaluateAsAbsolute(value, Assembler))
302 return std::nullopt;
303 return value;
304}
305
306//===----------------------------------------------------------------------===//
307// V3 UNWIND_INFO Emission
308// See https://learn.microsoft.com/en-us/cpp/build/x64-unwind-information-v3
309//===----------------------------------------------------------------------===//
310
311/// Encode a single WinEH::Instruction as V3 WOD bytes.
312/// Appends encoded bytes to Out.
315 switch (static_cast<Win64EH::UnwindOpcodes>(Inst.Operation)) {
317 // WOD_PUSH: 1 byte, bits [2:0] = 4, bits [7:3] = register (5-bit)
318 uint8_t Reg = Inst.Register & 0x1F;
319 Out.push_back((Reg << 3) | Win64EH::WOD_PUSH);
320 break;
321 }
323 // WOD_ALLOC_SMALL: 1 byte, bits [3:0] = 8, bits [7:4] = (size/8 - 1)
324 // V1/V2 stores (size-8)/8 in OpInfo; actual size = Offset.
325 // Inst.Offset is the raw allocation size.
326 if (Inst.Offset < 8 || Inst.Offset > 128 || Inst.Offset % 8 != 0)
328 "UOP_AllocSmall outside expected range or alignment");
329 uint8_t Encoded = ((Inst.Offset / 8 - 1) & 0x0F);
330 Out.push_back((Encoded << 4) | Win64EH::WOD_ALLOC_SMALL);
331 break;
332 }
334 if (Inst.Offset > 512 * 1024 - 8) {
335 // WOD_ALLOC_HUGE: 5 bytes, byte[0] = 1, bytes[1:4] = LE32(size)
336 Out.push_back(Win64EH::WOD_ALLOC_HUGE);
337 uint32_t Size = Inst.Offset;
338 Out.push_back(Size & 0xFF);
339 Out.push_back((Size >> 8) & 0xFF);
340 Out.push_back((Size >> 16) & 0xFF);
341 Out.push_back((Size >> 24) & 0xFF);
342 } else {
343 // WOD_ALLOC_LARGE: 3 bytes, byte[0] = 2, bytes[1:2] = LE16(size/8)
344 Out.push_back(Win64EH::WOD_ALLOC_LARGE);
345 uint16_t Scaled = Inst.Offset / 8;
346 Out.push_back(Scaled & 0xFF);
347 Out.push_back((Scaled >> 8) & 0xFF);
348 }
349 break;
350 }
352 // WOD_SET_FPREG: 2 bytes, byte[0] = 0, byte[1] = reg(4) | (offset/16)(4)
353 // The frame register field is only 4 bits, so EGPR (R16-R31) cannot be
354 // used as the frame pointer in V3 unwind info.
355 if (Inst.Register > 0x0F)
357 "SET_FPREG frame register does not fit in 4 bits");
358 Out.push_back(Win64EH::WOD_SET_FPREG);
359 uint8_t Reg = Inst.Register & 0x0F;
360 uint8_t Off = (Inst.Offset / 16) & 0x0F;
361 Out.push_back(Reg | (Off << 4));
362 break;
363 }
365 // WOD_SAVE_NONVOL: 3 bytes, bits [2:0] = 6, bits [7:3] = reg,
366 // bytes[1:2] = LE16(displacement/8)
367 uint8_t Reg = Inst.Register & 0x1F;
368 Out.push_back((Reg << 3) | Win64EH::WOD_SAVE_NONVOL);
369 uint16_t Disp = Inst.Offset / 8;
370 Out.push_back(Disp & 0xFF);
371 Out.push_back((Disp >> 8) & 0xFF);
372 break;
373 }
375 // WOD_SAVE_NONVOL_FAR: 5 bytes, bits [2:0] = 5, bits [7:3] = reg,
376 // bytes[1:4] = LE32(displacement)
377 uint8_t Reg = Inst.Register & 0x1F;
378 Out.push_back((Reg << 3) | Win64EH::WOD_SAVE_NONVOL_FAR);
379 uint32_t Disp = Inst.Offset;
380 Out.push_back(Disp & 0xFF);
381 Out.push_back((Disp >> 8) & 0xFF);
382 Out.push_back((Disp >> 16) & 0xFF);
383 Out.push_back((Disp >> 24) & 0xFF);
384 break;
385 }
387 // WOD_SAVE_XMM128: 3 bytes, bits [3:0] = 10, bits [7:4] = reg,
388 // bytes[1:2] = LE16(displacement/16)
389 // The XMM register field is only 4 bits, so XMM16-XMM31 (AVX-512 EVEX)
390 // cannot be encoded. Such registers are caller-saved on Win64 and should
391 // never reach here from codegen.
392 if (Inst.Register > 0x0F)
394 "SAVE_XMM128 register does not fit in 4 bits (XMM16-31 unsupported)");
395 uint8_t Reg = Inst.Register & 0x0F;
396 Out.push_back((Reg << 4) | Win64EH::WOD_SAVE_XMM128);
397 uint16_t Disp = Inst.Offset / 16;
398 Out.push_back(Disp & 0xFF);
399 Out.push_back((Disp >> 8) & 0xFF);
400 break;
401 }
403 // WOD_SAVE_XMM128_FAR: 5 bytes, bits [3:0] = 9, bits [7:4] = reg,
404 // bytes[1:4] = LE32(displacement)
405 if (Inst.Register > 0x0F)
406 reportFatalInternalError("SAVE_XMM128_FAR register does not fit in 4 "
407 "bits (XMM16-31 unsupported)");
408 uint8_t Reg = Inst.Register & 0x0F;
409 Out.push_back((Reg << 4) | Win64EH::WOD_SAVE_XMM128_FAR);
410 uint32_t Disp = Inst.Offset;
411 Out.push_back(Disp & 0xFF);
412 Out.push_back((Disp >> 8) & 0xFF);
413 Out.push_back((Disp >> 16) & 0xFF);
414 Out.push_back((Disp >> 24) & 0xFF);
415 break;
416 }
418 // WOD_PUSH_CANONICAL_FRAME: 2 bytes, byte[0] = 3, byte[1] = type
420 Out.push_back(Inst.Offset == 1 ? 1 : 0);
421 break;
422 }
423 case Win64EH::UOP_Push2: {
424 uint8_t Reg1 = Inst.Register & 0x1F;
425 uint8_t Reg2 = Inst.Register2 & 0x1F;
426 // Optimization: if registers are consecutive, use WOD_PUSH_CONSECUTIVE_2
427 // (opcode 7, 1 byte) instead of WOD_PUSH2 (opcode 32, 2 bytes).
428 if (Reg2 == Reg1 + 1) {
429 // WOD_PUSH_CONSECUTIVE_2: bits [2:0] = 111b, bits [7:3] = Register
430 Out.push_back((Reg1 << 3) | Win64EH::WOD_PUSH_CONSECUTIVE_2);
431 } else {
432 // WOD_PUSH2: 2 bytes
433 // Byte 0: [5:0] = 100000b (opcode 32), [7:6] = Register1[1:0]
434 // Byte 1: [2:0] = Register1[4:2], [7:3] = Register2
435 Out.push_back(((Reg1 & 0x03) << 6) | Win64EH::WOD_PUSH2);
436 Out.push_back(((Reg2 & 0x1F) << 3) | ((Reg1 >> 2) & 0x07));
437 }
438 break;
439 }
440 default:
441 llvm_unreachable("Unsupported unwind operation for V3 encoding");
442 }
443}
444
445/// Try to find Needle as a contiguous subsequence within Haystack.
446/// Returns the byte offset if found, or std::nullopt.
447static std::optional<uint16_t> FindInPool(ArrayRef<uint8_t> Haystack,
448 ArrayRef<uint8_t> Needle) {
449 assert(!Needle.empty() && "FindInPool called with empty Needle");
450 auto It = std::search(Haystack.begin(), Haystack.end(), Needle.begin(),
451 Needle.end());
452 if (It == Haystack.end())
453 return std::nullopt;
454 return static_cast<uint16_t>(std::distance(Haystack.begin(), It));
455}
456
457/// Compare the relative IP offset arrays of two epilogs.
460 const MCAssembler &Asm) {
461 if (A.Instructions.size() != B.Instructions.size())
462 return false;
463 for (unsigned I = 0; I < A.Instructions.size(); ++I) {
464 auto OffA = GetOptionalAbsDifference(Asm, A.Instructions[I].Label, A.Start);
465 auto OffB = GetOptionalAbsDifference(Asm, B.Instructions[I].Label, B.Start);
466 if (!OffA || !OffB || *OffA != *OffB)
467 return false;
468 }
469 return true;
470}
471
472/// Emit V3 UNWIND_INFO for a single frame.
474 // Should have been checked by our caller.
475 assert(!Info->Symbol && "UNWIND_INFO already has a symbol");
476
477 MCContext &Context = Streamer.getContext();
478 MCObjectStreamer *OS = static_cast<MCObjectStreamer *>(&Streamer);
479 const MCAssembler &Asm = OS->getAssembler();
480
481 MCSymbol *Label = Context.createTempSymbol();
482 Streamer.emitValueToAlignment(Align(4));
483 Streamer.emitLabel(Label);
484 Info->Symbol = Label;
485
486 // ===================================================================
487 // Phase 1: Data preparation — compute all metadata before emitting.
488 // ===================================================================
489
490 // --- Build prolog WOD pool (body-to-entry order) ---
492 for (auto It = Info->Instructions.rbegin(); It != Info->Instructions.rend();
493 ++It)
494 Win64EH::EncodeWOD(*It, WODPool);
495
496 // --- Build prolog IP offset label pairs (body-to-entry order) ---
498 unsigned PrologOpCount = Info->Instructions.size();
499 if (PrologOpCount > 31) {
501 "Too many prolog unwind codes for V3 encoding. Maximum "
502 "is 31. This function has " +
503 Twine(PrologOpCount));
504 }
505 for (auto It = Info->Instructions.rbegin(); It != Info->Instructions.rend();
506 ++It)
507 PrologIpLabels.push_back({It->Label, Info->Begin});
508
509 // --- Determine if UNW_FLAG_LARGE is needed for the prolog ---
510 // Conservative: if we KNOW a value exceeds 255 or can't measure, use LARGE.
511 // Reject evaluatable values that are negative or exceed the 16-bit unsigned
512 // range supported by LARGE, since those would be silently truncated.
513 bool NeedsLargeProlog = false;
514 if (Info->PrologEnd) {
515 auto MaybePrologSize =
516 GetOptionalAbsDifference(Asm, Info->PrologEnd, Info->Begin);
517 if (MaybePrologSize) {
518 if (*MaybePrologSize < 0)
519 reportFatalUsageError("Negative SizeOfProlog in V3 unwind info");
520 if (*MaybePrologSize > UINT16_MAX)
522 "SizeOfProlog exceeds 16-bit range for V3 unwind info");
523 NeedsLargeProlog = (*MaybePrologSize > 255);
524 } else {
525 NeedsLargeProlog = true; // Can't measure -> be conservative
526 }
527 }
528 for (auto &[InstLabel, BeginLabel] : PrologIpLabels) {
529 if (NeedsLargeProlog)
530 break;
531 auto MaybeOffset = GetOptionalAbsDifference(Asm, InstLabel, BeginLabel);
532 if (MaybeOffset) {
533 if (*MaybeOffset < 0)
534 reportFatalUsageError("Negative prolog IP offset in V3 unwind info");
535 if (*MaybeOffset > UINT16_MAX)
537 "Prolog IP offset exceeds 16-bit range for V3 unwind info");
538 NeedsLargeProlog = (*MaybeOffset > 255);
539 } else {
540 NeedsLargeProlog = true; // Can't measure -> be conservative
541 }
542 }
543
544 // --- Per-epilog data preparation ---
545 struct EpilogEmitInfo {
548 uint16_t FirstOp;
549 uint8_t NumberOfOps;
550 bool Inherited;
551 bool NeedsLarge; // EPILOG_INFO_LARGE needed for this epilog
552 };
553
555 for (const auto &[EpilogSym, Epilog] : Info->EpilogMap) {
556 if (Epilog.Instructions.empty())
557 continue;
558
559 EpilogEmitInfo EI;
560 EI.Epilog = &Epilog;
561 EI.NumberOfOps = Epilog.Instructions.size();
562 if (EI.NumberOfOps > 31)
564 "Too many epilog unwind codes for V3 encoding. Maximum "
565 "is 31. This epilog has " +
566 Twine(EI.NumberOfOps));
567 EI.Inherited = false;
568 EI.NeedsLarge = false;
569
570 // Determine if EPILOG_INFO_LARGE is needed.
571 // Check IpOffsetOfLastInstruction (EpilogEnd - EpilogStart).
572 // Reject negative or out-of-range evaluatable values.
573 auto MaybeLastInstOfs =
574 GetOptionalAbsDifference(Asm, Epilog.End, Epilog.Start);
575 if (MaybeLastInstOfs) {
576 if (*MaybeLastInstOfs < 0)
578 "Negative IpOffsetOfLastInstruction in V3 unwind info");
579 if (*MaybeLastInstOfs > UINT16_MAX)
581 "IpOffsetOfLastInstruction exceeds 16-bit range for "
582 "V3 unwind info");
583 EI.NeedsLarge = (*MaybeLastInstOfs > 255);
584 } else {
585 EI.NeedsLarge = true; // Can't measure -> be conservative
586 }
587
588 // Check each epilog IP offset.
589 for (const auto &EpiInst : Epilog.Instructions) {
590 if (EI.NeedsLarge)
591 break;
592 auto MaybeOffset =
593 GetOptionalAbsDifference(Asm, EpiInst.Label, Epilog.Start);
594 if (MaybeOffset) {
595 if (*MaybeOffset < 0)
596 reportFatalUsageError("Negative epilog IP offset in V3 unwind info");
597 if (*MaybeOffset > UINT16_MAX)
599 "Epilog IP offset exceeds 16-bit range for V3 unwind info");
600 EI.NeedsLarge = (*MaybeOffset > 255);
601 } else {
602 EI.NeedsLarge = true; // Can't measure -> be conservative
603 }
604 }
605
606 // Encode this epilog's WODs (forward order: body-to-terminator).
607 for (const auto &Inst : Epilog.Instructions)
608 Win64EH::EncodeWOD(Inst, EI.WODBytes);
609
610 // Pool sharing: try to re-use existing bytes in the pool rather than
611 // appending.
612 if (auto Offset = FindInPool(WODPool, EI.WODBytes)) {
613 EI.FirstOp = *Offset;
614 } else {
615 EI.FirstOp = WODPool.size();
616 WODPool.append(EI.WODBytes.begin(), EI.WODBytes.end());
617 }
618
619 EpilogInfos.push_back(std::move(EI));
620 }
621 if (EpilogInfos.size() > 7)
622 reportFatalUsageError("Too many epilogs for V3 encoding. Maximum is 7."
623 " This function has " +
624 Twine(EpilogInfos.size()));
625
626 // V3 epilog offsets are always encoded tail-relative: the first descriptor
627 // holds a negative byte offset from the fragment end, and each subsequent
628 // descriptor a (negative) delta from the previous epilog's start. The spec
629 // requires every descriptor in a fragment to use the same sign, so the
630 // descriptors must be listed in descending address order ("descending from
631 // tail"). EpilogMap is in ascending address order, so reverse it here before
632 // computing inheritance and emitting descriptors.
633 std::reverse(EpilogInfos.begin(), EpilogInfos.end());
634
635 // --- Inheritance decisions ---
636 // Per the V3 spec, an epilog descriptor with NumberOfOps == 0 inherits its
637 // effective NumberOfOps, FirstOp, IpOffsetOfLastInstruction, and IP offset
638 // array from the first preceding descriptor with NumberOfOps != 0 (the
639 // "base"), not necessarily the immediately preceding descriptor. An epilog
640 // can therefore use the inherited (3-byte) descriptor when FirstOp,
641 // NumberOfOps, and relative IP offsets all match that base. NeedsLarge is a
642 // deterministic function of those fields (it is set when an IP offset exceeds
643 // the 1-byte range), so a matching FirstOp/NumberOfOps and IP offsets imply a
644 // matching NeedsLarge; we assert that invariant rather than test it.
645 for (unsigned I = 1, Base = 0; I < EpilogInfos.size(); ++I) {
646 auto &BaseEI = EpilogInfos[Base];
647 auto &Curr = EpilogInfos[I];
648 if (Curr.FirstOp == BaseEI.FirstOp &&
649 Curr.NumberOfOps == BaseEI.NumberOfOps &&
650 EpilogIpOffsetsMatch(*Curr.Epilog, *BaseEI.Epilog,
651 OS->getAssembler())) {
652 assert(Curr.NeedsLarge == BaseEI.NeedsLarge &&
653 "NeedsLarge must follow from matching FirstOp, NumberOfOps, and "
654 "IP offsets");
655 Curr.Inherited = true;
656 } else
657 Base = I; // Curr is a full descriptor; it becomes the new base.
658 }
659
660 // --- Compute payload sizes ---
661 unsigned PrologIpEntrySize = NeedsLargeProlog ? 2 : 1;
662 unsigned EpilogDescBytes = 0;
663 for (const auto &EI : EpilogInfos) {
664 if (EI.Inherited) {
665 EpilogDescBytes += 3;
666 } else if (EI.NeedsLarge) {
667 // EPILOG_INFO_V3 (3) + EPILOG_INFO_LARGE_EX_V3 (4) + IP offsets (N*2)
668 EpilogDescBytes += 7 + EI.NumberOfOps * 2;
669 } else {
670 // EPILOG_INFO_V3 (3) + EPILOG_INFO_EX_V3 (3) + IP offsets (N*1)
671 EpilogDescBytes += 6 + EI.NumberOfOps;
672 }
673 }
674
675 unsigned PrologIpBytes = PrologOpCount * PrologIpEntrySize;
676 unsigned WODPoolBytes = WODPool.size();
677 // When UNW_FLAG_LARGE is set, the SizeOfPrologHighByte sits at the start
678 // of the payload (immediately after the 4-byte fixed header) and is
679 // counted in PayloadWords. See decodeUnwindInfoV3 / the V3 spec:
680 // handler_offset = ALIGN_UP(sizeof(UNWIND_INFO_V3) + PayloadWords * 2, 4)
681 unsigned LargeHeaderBytes = NeedsLargeProlog ? 1 : 0;
682 unsigned TotalPayloadBytes =
683 LargeHeaderBytes + PrologIpBytes + EpilogDescBytes + WODPoolBytes;
684 if (TotalPayloadBytes > 255 * 2) {
685 reportFatalUsageError("Too much unwind info for V3 encoding. Maximum is "
686 "510 bytes. This function has " +
687 Twine(TotalPayloadBytes));
688 }
689 uint8_t PayloadWords = (TotalPayloadBytes + 1) / 2;
690
691 // ===================================================================
692 // Phase 2: Emission — emit header, payload, and trailer.
693 // ===================================================================
694
695 // --- Emit header (4 bytes, or 5 when UNW_FLAG_LARGE) ---
696 uint8_t Flags = 0;
697 if (Info->ChainedParent)
698 Flags |= Win64EH::UNW_ChainInfo;
699 else {
700 if (Info->HandlesUnwind)
702 if (Info->HandlesExceptions)
704 }
705 if (NeedsLargeProlog)
706 Flags |= Win64EH::UNW_FlagLarge;
707
708 // Byte 0: (Flags << 3) | Version(3)
709 Streamer.emitInt8((Flags << 3) | 3);
710
711 // Byte 1: SizeOfProlog (low byte, or full 8-bit value when not LARGE)
712 if (Info->PrologEnd) {
713 if (NeedsLargeProlog) {
714 // Emit low byte as a fixup; we'll emit the high byte after Byte 3.
715 // Use a 2-byte value at a temp symbol and extract bytes, OR just emit
716 // the known value if evaluable.
717 auto MaybePrologSize =
718 GetOptionalAbsDifference(Asm, Info->PrologEnd, Info->Begin);
719 if (MaybePrologSize) {
720 Streamer.emitInt8(*MaybePrologSize & 0xFF);
721 } else {
722 // Emit as 1-byte fixup for the low byte.
723 EmitAbsDifference(Streamer, Info->PrologEnd, Info->Begin);
724 }
725 } else {
726 EmitAbsDifference(Streamer, Info->PrologEnd, Info->Begin);
727 }
728 } else {
729 Streamer.emitInt8(0);
730 }
731
732 // Byte 2: PayloadWords
733 Streamer.emitInt8(PayloadWords);
734
735 // Byte 3: (NumberOfEpilogs << 5) | NumberOfPrologOps
736 uint8_t NumberOfEpilogs = EpilogInfos.size();
737 Streamer.emitInt8((NumberOfEpilogs << 5) | (PrologOpCount & 0x1F));
738
739 // Byte 4 (LARGE only): SizeOfPrologHighByte
740 if (NeedsLargeProlog) {
741 if (Info->PrologEnd) {
742 auto MaybePrologSize =
743 GetOptionalAbsDifference(Asm, Info->PrologEnd, Info->Begin);
744 if (MaybePrologSize) {
745 Streamer.emitInt8((*MaybePrologSize >> 8) & 0xFF);
746 } else {
747 // Can't evaluate at this point — emit a fixup that shifts the
748 // difference right by 8 to extract the high byte.
749 const MCExpr *Diff = MCBinaryExpr::createSub(
750 MCSymbolRefExpr::create(Info->PrologEnd, Context),
751 MCSymbolRefExpr::create(Info->Begin, Context), Context);
752 const MCExpr *HighByte = MCBinaryExpr::createLShr(
753 Diff, MCConstantExpr::create(8, Context), Context);
754 Streamer.emitValue(HighByte, 1);
755 }
756 } else {
757 Streamer.emitInt8(0);
758 }
759 }
760
761 // --- Emit prolog IP offsets (8-bit or 16-bit) ---
762 for (auto &[InstLabel, BeginLabel] : PrologIpLabels) {
763 if (NeedsLargeProlog)
764 EmitAbsDifference16(Streamer, InstLabel, BeginLabel);
765 else
766 EmitAbsDifference(Streamer, InstLabel, BeginLabel);
767 }
768
769 // --- Emit epilog descriptors ---
770 const MCSymbol *PrevEpilogStart = nullptr;
771 [[maybe_unused]] uint8_t BaseEpiFlags = 0;
772 for (const auto &EI : EpilogInfos) {
773 const auto &Epilog = *EI.Epilog;
774
775 // FlagsAndNumOps: bits [2:0] = flags, bits [7:3] = NumberOfOps.
776 // For inherited descriptors, NumberOfOps = 0.
777 //
778 // Per the V3 spec, Flags bits 0 and 1 are NOT inherited by a descriptor
779 // with NumberOfOps == 0; the producer must replicate them so they have the
780 // same value as the base descriptor's. Since inheritance requires a
781 // matching NeedsLarge value, EI.NeedsLarge already equals the base's, so we
782 // emit EPILOG_INFO_LARGE for inherited descriptors too.
783 uint8_t EpiFlags = 0;
784 if (EI.NeedsLarge)
785 EpiFlags |= Win64EH::EPILOG_INFO_LARGE;
786 // An inherited descriptor must replicate the base descriptor's flags bits
787 // 0 and 1; verify we are about to emit a byte consistent with the base.
788 assert((!EI.Inherited || (EpiFlags & 0x03) == (BaseEpiFlags & 0x03)) &&
789 "inherited epilog must replicate base descriptor's flags bits 0-1");
790 if (!EI.Inherited)
791 BaseEpiFlags = EpiFlags;
792 uint8_t EpiNumOps = EI.Inherited ? 0 : EI.NumberOfOps;
793 Streamer.emitInt8((EpiNumOps << 3) | EpiFlags);
794
795 // EpilogOffset: signed 16-bit, always tail-relative (see
796 // MCUnwindV3EpilogOffsetTargetExpr). The first descriptor holds the
797 // negative byte offset from the fragment end; each subsequent descriptor
798 // holds the delta from the previous epilog's start. Emitted in descending
799 // address order, every offset is non-positive, satisfying the V3
800 // "all epilogs use the same sign" rule.
801 {
802 const MCExpr *EpilogOffsetExpr = MCUnwindV3EpilogOffsetTargetExpr::create(
803 *Info, Epilog.Start, PrevEpilogStart, Epilog.Loc, Context);
804 OS->ensureHeadroom(2);
805 OS->addFixup(EpilogOffsetExpr, FK_Data_2);
806 OS->appendContents(2, 0);
807 }
808 PrevEpilogStart = Epilog.Start;
809
810 // Full descriptor fields (only for non-inherited epilogs).
811 if (!EI.Inherited) {
812 // FirstOp: byte offset into WOD pool (2 bytes LE).
813 Streamer.emitInt8(EI.FirstOp & 0xFF);
814 Streamer.emitInt8((EI.FirstOp >> 8) & 0xFF);
815
816 // IpOffsetOfLastInstruction: 8-bit or 16-bit depending on
817 // EPILOG_INFO_LARGE.
818 {
819 const MCExpr *LastInstOffsetExpr = MCBinaryExpr::createSub(
820 MCSymbolRefExpr::create(Epilog.End, Context),
821 MCSymbolRefExpr::create(Epilog.Start, Context), Context);
822 unsigned FixupSize = EI.NeedsLarge ? 2 : 1;
823 OS->ensureHeadroom(FixupSize);
824 OS->addFixup(LastInstOffsetExpr, EI.NeedsLarge ? FK_Data_2 : FK_Data_1);
825 OS->appendContents(FixupSize, 0);
826 }
827
828 // Epilog IP offsets (forward order: body-to-terminator).
829 for (const auto &EpiInst : Epilog.Instructions) {
830 if (EI.NeedsLarge)
831 EmitAbsDifference16(Streamer, EpiInst.Label, Epilog.Start);
832 else
833 EmitAbsDifference(Streamer, EpiInst.Label, Epilog.Start);
834 }
835 }
836 }
837
838 // --- Emit WOD pool ---
839 for (uint8_t B : WODPool)
840 Streamer.emitInt8(B);
841
842 // --- Pad to PayloadWords * 2 bytes ---
843 // PayloadWords = (TotalPayloadBytes + 1) / 2, so at most 1 byte of padding.
844 if (TotalPayloadBytes % 2 != 0)
845 Streamer.emitInt8(0);
846
847 // --- Pad to 4-byte boundary before handler/chain info ---
848 // Per the V3 spec, the handler RVA / chained RUNTIME_FUNCTION begins at
849 // handler_offset = ALIGN_UP(sizeof(UNWIND_INFO_V3) + PayloadWords * 2, 4)
850 // The unwind info structure itself is 4-byte aligned, so when PayloadWords
851 // is odd, the natural end of the payload sits at +2 mod 4 and requires 2
852 // additional zero bytes of padding before the handler/chain.
853 if (PayloadWords % 2 != 0)
854 Streamer.emitInt16(0);
855
856 // --- Emit handler/chained info (same position as V1/V2) ---
857 if (Flags & Win64EH::UNW_ChainInfo)
858 EmitRuntimeFunction(Streamer, Info->ChainedParent);
859 else if (Flags &
861 Streamer.emitValue(
862 MCSymbolRefExpr::create(Info->ExceptionHandler,
864 4);
865 else if (PayloadWords == 0) {
866 // Minimum size: pad to 8 bytes total.
867 Streamer.emitInt32(0);
868 }
869}
870
872 // If this UNWIND_INFO already has a symbol, it's already been emitted.
873 if (info->Symbol)
874 return;
875
876 // V3 has a completely different binary layout; dispatch to separate emitter.
877 if (info->Version == 3) {
878 EmitUnwindInfoV3(streamer, info);
879 return;
880 }
881
882 // UOP_Push2 is V3-only and cannot be encoded in V1/V2. Detect this early
883 // (before counting codes) so the error is reported cleanly. This is
884 // reachable from hand-written .s if `.seh_push2regs` is followed by a
885 // per-function `.seh_unwindversion 1` or `2` downgrade.
886 for (const auto &Inst : info->Instructions) {
887 if (Inst.Operation == Win64EH::UOP_Push2) {
888 streamer.getContext().reportError(
889 SMLoc(), "UOP_Push2 (PUSH2 with two registers) requires V3 unwind "
890 "info. Use `.seh_unwindversion 3`.");
891 // Mark the frame as emitted (with no UNWIND_INFO) and bail so we don't
892 // emit malformed bytes or hit a downstream assertion.
893 info->Symbol = streamer.getContext().createTempSymbol();
894 return;
895 }
896 }
897
898 MCContext &context = streamer.getContext();
899 MCObjectStreamer *OS = (MCObjectStreamer *)(&streamer);
900 MCSymbol *Label = context.createTempSymbol();
901
902 streamer.emitValueToAlignment(Align(4));
903 streamer.emitLabel(Label);
904 info->Symbol = Label;
905
906 uint8_t numCodes = CountOfUnwindCodes(info->Instructions);
907 bool LastEpilogIsAtEnd = false;
908 bool AddPaddingEpilogCode = false;
909 uint8_t EpilogSize = 0;
910 bool EnableUnwindV2 = (info->Version >= 2) && !info->EpilogMap.empty();
911 if (EnableUnwindV2) {
912 auto &LastEpilog = info->EpilogMap.back().second;
913
914 // Calculate the size of the epilogs. Note that we +1 to the size so that
915 // the terminator instruction is also included in the epilog (the Windows
916 // unwinder does a simple range check versus the current instruction pointer
917 // so, although there are terminators that are large than 1 byte, the
918 // starting address of the terminator instruction will always be considered
919 // inside the epilog).
920 assert(
921 LastEpilog.UnwindV2Start &&
922 "If unwind v2 is enabled, epilog must have a unwind v2 start marker");
923 assert(LastEpilog.End && "Epilog must have an end");
924 auto MaybeSize = GetOptionalAbsDifference(
925 OS->getAssembler(), LastEpilog.End, LastEpilog.UnwindV2Start);
926 if (!MaybeSize) {
927 context.reportError(LastEpilog.Loc,
928 "Failed to evaluate epilog size for Unwind v2 in " +
929 info->Function->getName());
930 return;
931 }
932 assert(*MaybeSize >= 0);
933 if (*MaybeSize >= (int64_t)UINT8_MAX) {
934 context.reportError(LastEpilog.Loc,
935 "Epilog size is too large for Unwind v2 in " +
936 info->Function->getName());
937 return;
938 }
939 EpilogSize = *MaybeSize + 1;
940
941 // If the last epilog is at the end of the function, we can use a special
942 // encoding for it. Because of our +1 trick for the size, this will only
943 // work where that final terminator instruction is 1 byte long.
944 // NOTE: At the point where the unwind info is emitted, the function may not
945 // have ended yet (e.g., if there is EH Handler Data), so assume that we
946 // aren't at the end (since we can't calculate it).
947 if (info->End) {
948 auto LastEpilogToFuncEnd = GetOptionalAbsDifference(
949 OS->getAssembler(), info->End, LastEpilog.UnwindV2Start);
950 LastEpilogIsAtEnd = (LastEpilogToFuncEnd == EpilogSize);
951 }
952
953 // If we have an odd number of epilog codes, we need to add a padding code.
954 size_t numEpilogCodes =
955 info->EpilogMap.size() + (LastEpilogIsAtEnd ? 0 : 1);
956 if ((numEpilogCodes % 2) != 0) {
957 AddPaddingEpilogCode = true;
958 numEpilogCodes++;
959 }
960
961 // Too many epilogs to handle.
962 if ((size_t)numCodes + numEpilogCodes > UINT8_MAX) {
963 context.reportError(info->FunctionLoc,
964 "Too many unwind codes with Unwind v2 enabled in " +
965 info->Function->getName());
966 return;
967 }
968
969 numCodes += numEpilogCodes;
970 }
971
972 // Upper 3 bits are the version number.
973 uint8_t flags = info->Version;
974 if (info->ChainedParent)
975 flags |= Win64EH::UNW_ChainInfo << 3;
976 else {
977 if (info->HandlesUnwind)
978 flags |= Win64EH::UNW_TerminateHandler << 3;
979 if (info->HandlesExceptions)
980 flags |= Win64EH::UNW_ExceptionHandler << 3;
981 }
982 streamer.emitInt8(flags);
983
984 if (info->PrologEnd)
985 EmitAbsDifference(streamer, info->PrologEnd, info->Begin);
986 else
987 streamer.emitInt8(0);
988
989 streamer.emitInt8(numCodes);
990
991 uint8_t frame = 0;
992 if (info->LastFrameInst >= 0) {
993 WinEH::Instruction &frameInst = info->Instructions[info->LastFrameInst];
995 frame = (frameInst.Register & 0x0F) | (frameInst.Offset & 0xF0);
996 }
997 streamer.emitInt8(frame);
998
999 // Emit the epilog instructions.
1000 if (EnableUnwindV2) {
1001 // Ensure the fixups and appended content apply to the same fragment.
1002 // size byte + flags byte + 2 per epilog (for the distance).
1003 OS->ensureHeadroom(2 + info->EpilogMap.size() * 2);
1004
1005 bool IsLast = true;
1006 for (const auto &Epilog : llvm::reverse(info->EpilogMap)) {
1007 if (IsLast) {
1008 IsLast = false;
1009 uint8_t Flags = LastEpilogIsAtEnd ? 0x01 : 0;
1010 OS->emitInt8(EpilogSize);
1011 OS->emitInt8((Flags << 4) | Win64EH::UOP_Epilog);
1012
1013 if (LastEpilogIsAtEnd)
1014 continue;
1015 }
1016
1017 // Each epilog is emitted as a fixup, since we can't measure the distance
1018 // between the start of the epilog and the end of the function until
1019 // layout has been completed.
1020 auto *MCE = MCUnwindV2EpilogTargetExpr::create(*info, Epilog.second,
1021 EpilogSize, context);
1022 OS->addFixup(MCE, FK_Data_2);
1023 OS->appendContents(2, 0);
1024 }
1025 }
1026 if (AddPaddingEpilogCode)
1027 streamer.emitInt16(Win64EH::UOP_Epilog << 8);
1028
1029 // Emit unwind instructions (in reverse order).
1030 uint8_t numInst = info->Instructions.size();
1031 for (uint8_t c = 0; c < numInst; ++c) {
1032 WinEH::Instruction inst = info->Instructions.back();
1033 info->Instructions.pop_back();
1034 EmitUnwindCode(streamer, info->Begin, inst);
1035 }
1036
1037 // For alignment purposes, the instruction array will always have an even
1038 // number of entries, with the final entry potentially unused (in which case
1039 // the array will be one longer than indicated by the count of unwind codes
1040 // field).
1041 if (numCodes & 1) {
1042 streamer.emitInt16(0);
1043 }
1044
1045 if (flags & (Win64EH::UNW_ChainInfo << 3))
1046 EmitRuntimeFunction(streamer, info->ChainedParent);
1047 else if (flags &
1049 streamer.emitValue(MCSymbolRefExpr::create(info->ExceptionHandler,
1051 context), 4);
1052 else if (numCodes == 0) {
1053 // The minimum size of an UNWIND_INFO struct is 8 bytes. If we're not
1054 // a chained unwind info, if there is no handler, and if there are fewer
1055 // than 2 slots used in the unwind code array, we have to pad to 8 bytes.
1056 streamer.emitInt32(0);
1057 }
1058}
1059
1060bool MCUnwindV2EpilogTargetExpr::evaluateAsRelocatableImpl(
1061 MCValue &Res, const MCAssembler *Asm) const {
1062 // Calculate the offset to this epilog, and validate it's within the allowed
1063 // range.
1064 auto Offset = GetOptionalAbsDifference(*Asm, FrameInfo.End, UnwindV2Start);
1065 if (!Offset) {
1066 Asm->getContext().reportError(
1067 Loc, "Failed to evaluate epilog offset for Unwind v2 in " +
1068 FrameInfo.Function->getName());
1069 return false;
1070 }
1071 assert(*Offset > 0);
1072 constexpr uint16_t MaxEpilogOffset = 0x0fff;
1073 if (*Offset > MaxEpilogOffset) {
1074 Asm->getContext().reportError(
1075 Loc, "Epilog offset is too large for Unwind v2 in " +
1076 FrameInfo.Function->getName());
1077 return false;
1078 }
1079
1080 // Validate that all epilogs are the same size.
1081 auto Size = GetOptionalAbsDifference(*Asm, EpilogEnd, UnwindV2Start);
1082 if (Size != (EpilogSize - 1)) {
1083 Asm->getContext().reportError(
1084 Loc, "Size of this epilog does not match size of last epilog in " +
1085 FrameInfo.Function->getName());
1086 return false;
1087 }
1088
1089 auto HighBits = *Offset >> 8;
1090 Res = MCValue::get((HighBits << 12) | (Win64EH::UOP_Epilog << 8) |
1091 (*Offset & 0xFF));
1092 return true;
1093}
1094
1095bool MCUnwindV3EpilogOffsetTargetExpr::evaluateAsRelocatableImpl(
1096 MCValue &Res, const MCAssembler *Asm) const {
1097 // The first epilog descriptor is encoded relative to the fragment tail (the
1098 // first byte past the end of the fragment); subsequent descriptors are
1099 // encoded relative to the previous epilog's start. Both bases yield a
1100 // non-positive offset, as required by the V3 "same sign" rule.
1101 const MCSymbol *Base = PrevEpilogStart ? PrevEpilogStart : FrameInfo.End;
1102 if (!Base) {
1103 Asm->getContext().reportError(
1104 Loc, "Missing fragment end for V3 epilog offset in " +
1105 FrameInfo.Function->getName());
1106 return false;
1107 }
1108
1109 auto Offset = GetOptionalAbsDifference(*Asm, EpilogStart, Base);
1110 if (!Offset) {
1111 Asm->getContext().reportError(
1112 Loc, "Failed to evaluate epilog offset for V3 unwind info in " +
1113 FrameInfo.Function->getName());
1114 return false;
1115 }
1116 if (*Offset < INT16_MIN || *Offset > INT16_MAX) {
1117 Asm->getContext().reportError(
1118 Loc, "Epilog offset " + Twine(*Offset) +
1119 " out of signed 16-bit range for V3 encoding in " +
1120 FrameInfo.Function->getName());
1121 return false;
1122 }
1123
1124 Res = MCValue::get(*Offset);
1125 return true;
1126}
1127
1129 // Emit the unwind info structs first.
1130 for (const auto &CFI : Streamer.getWinFrameInfos()) {
1131 MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection);
1132 Streamer.switchSection(XData);
1133 ::EmitUnwindInfo(Streamer, CFI.get());
1134 }
1135
1136 // Now emit RUNTIME_FUNCTION entries.
1137 for (const auto &CFI : Streamer.getWinFrameInfos()) {
1138 MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection);
1139 Streamer.switchSection(PData);
1140 EmitRuntimeFunction(Streamer, CFI.get());
1141 }
1142}
1143
1146 bool HandlerData) const {
1147 // Switch sections (the static function above is meant to be called from
1148 // here and from Emit().
1149 MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection);
1150 Streamer.switchSection(XData);
1151
1153}
1154
1156 const MCSymbol *RHS, int Div) {
1157 MCContext &Context = Streamer.getContext();
1158 const MCExpr *Expr =
1160 MCSymbolRefExpr::create(RHS, Context), Context);
1161 if (Div != 1)
1162 Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(Div, Context),
1163 Context);
1164 return Expr;
1165}
1166
1167static std::optional<int64_t> GetOptionalAbsDifference(MCStreamer &Streamer,
1168 const MCSymbol *LHS,
1169 const MCSymbol *RHS) {
1172}
1173
1175 const MCSymbol *RHS) {
1176 std::optional<int64_t> MaybeDiff =
1178 if (!MaybeDiff)
1179 report_fatal_error("Failed to evaluate function length in SEH unwind info");
1180 return *MaybeDiff;
1181}
1182
1184 bool IsPrologue) {
1185 auto EndC = llvm::find_if(Insns, [](const WinEH::Instruction &Instruction) {
1186 return Instruction.Operation == Win64EH::UOP_EndC;
1187 });
1188 if (EndC == Insns.end())
1189 return Insns.size() - 1;
1190 return IsPrologue ? std::distance(EndC + 1, Insns.end())
1191 : std::distance(Insns.begin(), EndC);
1192}
1193
1196 const MCSymbol *Begin, const MCSymbol *End,
1197 StringRef Name, bool IsPrologue) {
1198 if (!End)
1199 return;
1200 std::optional<int64_t> MaybeDistance =
1202 if (!MaybeDistance)
1203 return;
1204 uint32_t Distance = (uint32_t)*MaybeDistance;
1205
1206 for (const auto &I : Insns) {
1207 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
1208 default:
1209 break;
1215 // Can't reason about these opcodes and how they map to actual
1216 // instructions.
1217 return;
1218 }
1219 }
1220 uint32_t InstructionBytes = 4 * ARM64CountOfInstructions(Insns, IsPrologue);
1221 if (Distance != InstructionBytes) {
1222 StringRef Type = IsPrologue ? "prologue" : "epilogue";
1223 Streamer.getContext().reportError(
1224 SMLoc(), "Incorrect size for " + Name + " " + Type + ": " +
1225 Twine(Distance) +
1226 " bytes of instructions in range, but .seh directives "
1227 "corresponding to " +
1228 Twine(InstructionBytes) + " bytes\n");
1229 }
1230}
1231
1233 uint32_t Count = 0;
1234 for (const auto &I : Insns) {
1235 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
1236 default:
1237 llvm_unreachable("Unsupported ARM64 unwind code");
1239 Count += 1;
1240 break;
1242 Count += 2;
1243 break;
1245 Count += 4;
1246 break;
1248 Count += 1;
1249 break;
1251 Count += 1;
1252 break;
1254 Count += 1;
1255 break;
1257 Count += 2;
1258 break;
1260 Count += 2;
1261 break;
1263 Count += 2;
1264 break;
1266 Count += 2;
1267 break;
1269 Count += 2;
1270 break;
1272 Count += 2;
1273 break;
1275 Count += 2;
1276 break;
1278 Count += 2;
1279 break;
1281 Count += 2;
1282 break;
1283 case Win64EH::UOP_SetFP:
1284 Count += 1;
1285 break;
1286 case Win64EH::UOP_AddFP:
1287 Count += 2;
1288 break;
1289 case Win64EH::UOP_Nop:
1290 Count += 1;
1291 break;
1292 case Win64EH::UOP_End:
1293 case Win64EH::UOP_EndC:
1294 Count += 1;
1295 break;
1297 Count += 1;
1298 break;
1300 Count += 1;
1301 break;
1303 Count += 1;
1304 break;
1306 Count += 1;
1307 break;
1309 Count += 1;
1310 break;
1312 Count += 1;
1313 break;
1315 Count += 1;
1316 break;
1318 Count += 2;
1319 break;
1334 Count += 3;
1335 break;
1336 }
1337 }
1338 return Count;
1339}
1340
1341// Unwind opcode encodings and restrictions are documented at
1342// https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1343static void ARM64EmitUnwindCode(MCStreamer &streamer,
1344 const WinEH::Instruction &inst) {
1345 uint8_t b, reg;
1346 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
1347 default:
1348 llvm_unreachable("Unsupported ARM64 unwind code");
1350 b = (inst.Offset >> 4) & 0x1F;
1351 streamer.emitInt8(b);
1352 break;
1354 uint16_t hw = (inst.Offset >> 4) & 0x7FF;
1355 b = 0xC0;
1356 b |= (hw >> 8);
1357 streamer.emitInt8(b);
1358 b = hw & 0xFF;
1359 streamer.emitInt8(b);
1360 break;
1361 }
1363 uint32_t w;
1364 b = 0xE0;
1365 streamer.emitInt8(b);
1366 w = inst.Offset >> 4;
1367 b = (w & 0x00FF0000) >> 16;
1368 streamer.emitInt8(b);
1369 b = (w & 0x0000FF00) >> 8;
1370 streamer.emitInt8(b);
1371 b = w & 0x000000FF;
1372 streamer.emitInt8(b);
1373 break;
1374 }
1375 case Win64EH::UOP_SetFP:
1376 b = 0xE1;
1377 streamer.emitInt8(b);
1378 break;
1379 case Win64EH::UOP_AddFP:
1380 b = 0xE2;
1381 streamer.emitInt8(b);
1382 b = (inst.Offset >> 3);
1383 streamer.emitInt8(b);
1384 break;
1385 case Win64EH::UOP_Nop:
1386 b = 0xE3;
1387 streamer.emitInt8(b);
1388 break;
1390 b = 0x20;
1391 b |= (inst.Offset >> 3) & 0x1F;
1392 streamer.emitInt8(b);
1393 break;
1395 b = 0x80;
1396 b |= ((inst.Offset >> 3) - 1) & 0x3F;
1397 streamer.emitInt8(b);
1398 break;
1400 b = 0x40;
1401 b |= (inst.Offset >> 3) & 0x3F;
1402 streamer.emitInt8(b);
1403 break;
1405 assert(inst.Register >= 19 && "Saved reg must be >= 19");
1406 reg = inst.Register - 19;
1407 b = 0xD0 | ((reg & 0xC) >> 2);
1408 streamer.emitInt8(b);
1409 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
1410 streamer.emitInt8(b);
1411 break;
1413 assert(inst.Register >= 19 && "Saved reg must be >= 19");
1414 reg = inst.Register - 19;
1415 b = 0xD4 | ((reg & 0x8) >> 3);
1416 streamer.emitInt8(b);
1417 b = ((reg & 0x7) << 5) | ((inst.Offset >> 3) - 1);
1418 streamer.emitInt8(b);
1419 break;
1421 assert(inst.Register >= 19 && "Saved registers must be >= 19");
1422 reg = inst.Register - 19;
1423 b = 0xC8 | ((reg & 0xC) >> 2);
1424 streamer.emitInt8(b);
1425 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
1426 streamer.emitInt8(b);
1427 break;
1429 assert(inst.Register >= 19 && "Saved registers must be >= 19");
1430 reg = inst.Register - 19;
1431 b = 0xCC | ((reg & 0xC) >> 2);
1432 streamer.emitInt8(b);
1433 b = ((reg & 0x3) << 6) | ((inst.Offset >> 3) - 1);
1434 streamer.emitInt8(b);
1435 break;
1437 assert(inst.Register >= 19 && "Saved reg must be >= 19");
1438 reg = inst.Register - 19;
1439 assert((reg % 2) == 0 && "Saved reg must be 19+2*X");
1440 reg /= 2;
1441 b = 0xD6 | ((reg & 0x7) >> 2);
1442 streamer.emitInt8(b);
1443 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
1444 streamer.emitInt8(b);
1445 break;
1447 assert(inst.Register >= 8 && "Saved dreg must be >= 8");
1448 reg = inst.Register - 8;
1449 b = 0xDC | ((reg & 0x4) >> 2);
1450 streamer.emitInt8(b);
1451 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
1452 streamer.emitInt8(b);
1453 break;
1455 assert(inst.Register >= 8 && "Saved dreg must be >= 8");
1456 reg = inst.Register - 8;
1457 b = 0xDE;
1458 streamer.emitInt8(b);
1459 b = ((reg & 0x7) << 5) | ((inst.Offset >> 3) - 1);
1460 streamer.emitInt8(b);
1461 break;
1463 assert(inst.Register >= 8 && "Saved dregs must be >= 8");
1464 reg = inst.Register - 8;
1465 b = 0xD8 | ((reg & 0x4) >> 2);
1466 streamer.emitInt8(b);
1467 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
1468 streamer.emitInt8(b);
1469 break;
1471 assert(inst.Register >= 8 && "Saved dregs must be >= 8");
1472 reg = inst.Register - 8;
1473 b = 0xDA | ((reg & 0x4) >> 2);
1474 streamer.emitInt8(b);
1475 b = ((reg & 0x3) << 6) | ((inst.Offset >> 3) - 1);
1476 streamer.emitInt8(b);
1477 break;
1478 case Win64EH::UOP_End:
1479 b = 0xE4;
1480 streamer.emitInt8(b);
1481 break;
1482 case Win64EH::UOP_EndC:
1483 streamer.emitInt8(0xE5);
1484 break;
1486 b = 0xE6;
1487 streamer.emitInt8(b);
1488 break;
1490 b = 0xE8;
1491 streamer.emitInt8(b);
1492 break;
1494 b = 0xE9;
1495 streamer.emitInt8(b);
1496 break;
1498 b = 0xEA;
1499 streamer.emitInt8(b);
1500 break;
1502 b = 0xEB;
1503 streamer.emitInt8(b);
1504 break;
1506 b = 0xEC;
1507 streamer.emitInt8(b);
1508 break;
1510 b = 0xFC;
1511 streamer.emitInt8(b);
1512 break;
1525 // This assumes the opcodes are listed in the enum in a particular order.
1527 int Writeback = Op / 6;
1528 int Paired = Op % 2;
1529 int Mode = (Op / 2) % 3;
1530 int Offset = inst.Offset >> 3;
1531 if (Writeback || Paired || Mode == 2)
1532 Offset >>= 1;
1533 if (Writeback)
1534 --Offset;
1535 b = 0xE7;
1536 streamer.emitInt8(b);
1537 assert(inst.Register < 32);
1538 b = inst.Register | (Writeback << 5) | (Paired << 6);
1539 streamer.emitInt8(b);
1540 b = Offset | (Mode << 6);
1541 streamer.emitInt8(b);
1542 break;
1543 }
1544 case Win64EH::UOP_AllocZ: {
1545 b = 0xDF;
1546 streamer.emitInt8(b);
1547 b = inst.Offset;
1548 streamer.emitInt8(b);
1549 break;
1550 }
1551 case Win64EH::UOP_SaveZReg: {
1552 assert(inst.Register >= 8 && inst.Register <= 23);
1553 assert(inst.Offset < 256);
1554 b = 0xE7;
1555 streamer.emitInt8(b);
1556 reg = inst.Register - 8;
1557 b = ((inst.Offset & 0xC0) >> 1) | reg;
1558 streamer.emitInt8(b);
1559 b = 0xC0 | (inst.Offset & 0x3F);
1560 streamer.emitInt8(b);
1561 break;
1562 }
1563 case Win64EH::UOP_SavePReg: {
1564 assert(inst.Register >= 4 && inst.Register <= 15);
1565 assert(inst.Offset < 256);
1566 b = 0xE7;
1567 streamer.emitInt8(b);
1568 reg = inst.Register;
1569 b = ((inst.Offset & 0xC0) >> 1) | 0x10 | reg;
1570 streamer.emitInt8(b);
1571 b = 0xC0 | (inst.Offset & 0x3F);
1572 streamer.emitInt8(b);
1573 break;
1574 }
1575 }
1576}
1577
1578// Returns the epilog symbol of an epilog with the exact same unwind code
1579// sequence, if it exists. Otherwise, returns nullptr.
1580// EpilogInstrs - Unwind codes for the current epilog.
1581// Epilogs - Epilogs that potentialy match the current epilog.
1582static MCSymbol*
1583FindMatchingEpilog(const std::vector<WinEH::Instruction>& EpilogInstrs,
1584 const std::vector<MCSymbol *>& Epilogs,
1585 const WinEH::FrameInfo *info) {
1586 for (auto *EpilogStart : Epilogs) {
1587 auto InstrsIter = info->EpilogMap.find(EpilogStart);
1588 assert(InstrsIter != info->EpilogMap.end() &&
1589 "Epilog not found in EpilogMap");
1590 const auto &Instrs = InstrsIter->second.Instructions;
1591
1592 if (Instrs.size() != EpilogInstrs.size())
1593 continue;
1594
1595 bool Match = true;
1596 for (unsigned i = 0; i < Instrs.size(); ++i)
1597 if (Instrs[i] != EpilogInstrs[i]) {
1598 Match = false;
1599 break;
1600 }
1601
1602 if (Match)
1603 return EpilogStart;
1604 }
1605 return nullptr;
1606}
1607
1608static void simplifyARM64Opcodes(std::vector<WinEH::Instruction> &Instructions,
1609 bool Reverse) {
1610 unsigned PrevOffset = -1;
1611 unsigned PrevRegister = -1;
1612
1613 // Iterate over instructions in a forward order (for prologues),
1614 // backwards for epilogues (i.e. always reverse compared to how the
1615 // opcodes are stored).
1616 for (WinEH::Instruction &Inst :
1617 llvm::reverse_conditionally(Instructions, Reverse)) {
1618 // Convert 2-byte opcodes into equivalent 1-byte ones.
1619 if (Inst.Operation == Win64EH::UOP_SaveRegP && Inst.Register == 29) {
1620 Inst.Operation = Win64EH::UOP_SaveFPLR;
1621 Inst.Register = -1;
1622 } else if (Inst.Operation == Win64EH::UOP_SaveRegPX &&
1623 Inst.Register == 29) {
1624 Inst.Operation = Win64EH::UOP_SaveFPLRX;
1625 Inst.Register = -1;
1626 } else if (Inst.Operation == Win64EH::UOP_SaveRegPX &&
1627 Inst.Register == 19 && Inst.Offset <= 248) {
1628 Inst.Operation = Win64EH::UOP_SaveR19R20X;
1629 Inst.Register = -1;
1630 } else if (Inst.Operation == Win64EH::UOP_AddFP && Inst.Offset == 0) {
1631 Inst.Operation = Win64EH::UOP_SetFP;
1632 } else if (Inst.Operation == Win64EH::UOP_SaveRegP &&
1633 Inst.Register == PrevRegister + 2 &&
1634 Inst.Offset == PrevOffset + 16) {
1635 Inst.Operation = Win64EH::UOP_SaveNext;
1636 Inst.Register = -1;
1637 Inst.Offset = 0;
1638 // Intentionally not creating UOP_SaveNext for float register pairs,
1639 // as current versions of Windows (up to at least 20.04) is buggy
1640 // regarding SaveNext for float pairs.
1641 }
1642 // Update info about the previous instruction, for detecting if
1643 // the next one can be made a UOP_SaveNext
1644 if (Inst.Operation == Win64EH::UOP_SaveR19R20X) {
1645 PrevOffset = 0;
1646 PrevRegister = 19;
1647 } else if (Inst.Operation == Win64EH::UOP_SaveRegPX) {
1648 PrevOffset = 0;
1649 PrevRegister = Inst.Register;
1650 } else if (Inst.Operation == Win64EH::UOP_SaveRegP) {
1651 PrevOffset = Inst.Offset;
1652 PrevRegister = Inst.Register;
1653 } else if (Inst.Operation == Win64EH::UOP_SaveNext) {
1654 PrevRegister += 2;
1655 PrevOffset += 16;
1656 } else {
1657 PrevRegister = -1;
1658 PrevOffset = -1;
1659 }
1660 }
1661}
1662
1663// Check if an epilog exists as a subset of the end of a prolog (backwards).
1666 // Can't find an epilog as a subset if it is longer than the prolog.
1667 if (Epilog.size() > Prolog.size())
1668 return -1;
1669
1670 // Check that the epilog actually is a perfect match for the end (backwrds)
1671 // of the prolog.
1672 for (int I = Epilog.size() - 1; I >= 0; I--) {
1673 if (Prolog[I] != Epilog[Epilog.size() - 1 - I])
1674 return -1;
1675 }
1676
1677 if (Epilog.size() == Prolog.size())
1678 return 0;
1679
1680 // If the epilog was a subset of the prolog, find its offset.
1681 return ARM64CountOfUnwindCodes(Prolog.drop_front(Epilog.size()));
1682}
1683
1687 int PrologCodeBytes) {
1688 // Can only pack if there's one single epilog
1689 if (Seg->Epilogs.size() != 1)
1690 return -1;
1691
1692 MCSymbol *Sym = Seg->Epilogs.begin()->first;
1693 const std::vector<WinEH::Instruction> &Epilog =
1694 info->EpilogMap[Sym].Instructions;
1695
1696 // Check that the epilog actually is at the very end of the function,
1697 // otherwise it can't be packed.
1698 uint32_t DistanceFromEnd =
1699 (uint32_t)(Seg->Offset + Seg->Length - Seg->Epilogs.begin()->second);
1700 if (DistanceFromEnd / 4 != Epilog.size())
1701 return -1;
1702
1703 int RetVal = -1;
1704 // Even if we don't end up sharing opcodes with the prolog, we can still
1705 // write the offset as a packed offset, if the single epilog is located at
1706 // the end of the function and the offset (pointing after the prolog) fits
1707 // as a packed offset.
1708 if (PrologCodeBytes <= 31 &&
1709 PrologCodeBytes + ARM64CountOfUnwindCodes(Epilog) <= 124)
1710 RetVal = PrologCodeBytes;
1711
1713 if (Offset < 0)
1714 return RetVal;
1715
1716 // Check that the offset and prolog size fits in the first word; it's
1717 // unclear whether the epilog count in the extension word can be taken
1718 // as packed epilog offset.
1719 if (Offset > 31 || PrologCodeBytes > 124)
1720 return RetVal;
1721
1722 // As we choose to express the epilog as part of the prolog, remove the
1723 // epilog from the map, so we don't try to emit its opcodes.
1724 info->EpilogMap.erase(Sym);
1725 return Offset;
1726}
1727
1729 int PackedEpilogOffset) {
1730 if (PackedEpilogOffset == 0) {
1731 // Fully symmetric prolog and epilog, should be ok for packed format.
1732 // For CR=3, the corresponding synthesized epilog actually lacks the
1733 // SetFP opcode, but unwinding should work just fine despite that
1734 // (if at the SetFP opcode, the unwinder considers it as part of the
1735 // function body and just unwinds the full prolog instead).
1736 } else if (PackedEpilogOffset == 1) {
1737 // One single case of differences between prolog and epilog is allowed:
1738 // The epilog can lack a single SetFP that is the last opcode in the
1739 // prolog, for the CR=3 case.
1740 if (info->Instructions.back().Operation != Win64EH::UOP_SetFP)
1741 return false;
1742 } else {
1743 // Too much difference between prolog and epilog.
1744 return false;
1745 }
1746 unsigned RegI = 0, RegF = 0;
1747 int Predecrement = 0;
1748 enum {
1749 Start,
1750 Start2,
1751 Start3,
1752 IntRegs,
1753 FloatRegs,
1754 InputArgs,
1755 StackAdjust,
1756 FrameRecord,
1757 End
1758 } Location = Start;
1759 bool StandaloneLR = false, FPLRPair = false;
1760 bool PAC = false;
1761 int StackOffset = 0;
1762 int Nops = 0;
1763 // Iterate over the prolog and check that all opcodes exactly match
1764 // the canonical order and form. A more lax check could verify that
1765 // all saved registers are in the expected locations, but not enforce
1766 // the order - that would work fine when unwinding from within
1767 // functions, but not be exactly right if unwinding happens within
1768 // prologs/epilogs.
1769 for (auto It = info->Instructions.begin(), EndIt = info->Instructions.end();
1770 It != EndIt; It++) {
1771 const WinEH::Instruction &Inst = *It;
1772 switch (Inst.Operation) {
1773 case Win64EH::UOP_End:
1774 if (Location != Start)
1775 return false;
1776 Location = Start2;
1777 break;
1779 if (Location != Start2)
1780 return false;
1781 PAC = true;
1782 Location = Start3;
1783 break;
1785 if (Location != Start2 && Location != Start3)
1786 return false;
1787 Predecrement = Inst.Offset;
1788 RegI = 2;
1789 Location = IntRegs;
1790 break;
1792 if (Location != Start2 && Location != Start3)
1793 return false;
1794 Predecrement = Inst.Offset;
1795 if (Inst.Register == 19)
1796 RegI += 1;
1797 else if (Inst.Register == 30)
1798 StandaloneLR = true;
1799 else
1800 return false;
1801 // Odd register; can't be any further int registers.
1802 Location = FloatRegs;
1803 break;
1805 // Can't have this in a canonical prologue. Either this has been
1806 // canonicalized into SaveR19R20X or SaveFPLRX, or it's an unsupported
1807 // register pair.
1808 // It can't be canonicalized into SaveR19R20X if the offset is
1809 // larger than 248 bytes, but even with the maximum case with
1810 // RegI=10/RegF=8/CR=1/H=1, we end up with SavSZ = 216, which should
1811 // fit into SaveR19R20X.
1812 // The unwinding opcodes can't describe the otherwise seemingly valid
1813 // case for RegI=1 CR=1, that would start with a
1814 // "stp x19, lr, [sp, #-...]!" as that fits neither SaveRegPX nor
1815 // SaveLRPair.
1816 return false;
1818 if (Location != IntRegs || Inst.Offset != 8 * RegI ||
1819 Inst.Register != 19 + RegI)
1820 return false;
1821 RegI += 2;
1822 break;
1824 if (Location != IntRegs || Inst.Offset != 8 * RegI)
1825 return false;
1826 if (Inst.Register == 19 + RegI)
1827 RegI += 1;
1828 else if (Inst.Register == 30)
1829 StandaloneLR = true;
1830 else
1831 return false;
1832 // Odd register; can't be any further int registers.
1833 Location = FloatRegs;
1834 break;
1836 if (Location != IntRegs || Inst.Offset != 8 * RegI ||
1837 Inst.Register != 19 + RegI)
1838 return false;
1839 RegI += 1;
1840 StandaloneLR = true;
1841 Location = FloatRegs;
1842 break;
1844 // Packed unwind can't handle prologs that only save one single
1845 // float register.
1846 return false;
1848 if (Location != FloatRegs || RegF == 0 || Inst.Register != 8 + RegF ||
1849 Inst.Offset != 8 * (RegI + (StandaloneLR ? 1 : 0) + RegF))
1850 return false;
1851 RegF += 1;
1852 Location = InputArgs;
1853 break;
1855 if ((Location != Start2 && Location != Start3) || Inst.Register != 8)
1856 return false;
1857 Predecrement = Inst.Offset;
1858 RegF = 2;
1859 Location = FloatRegs;
1860 break;
1862 if ((Location != IntRegs && Location != FloatRegs) ||
1863 Inst.Register != 8 + RegF ||
1864 Inst.Offset != 8 * (RegI + (StandaloneLR ? 1 : 0) + RegF))
1865 return false;
1866 RegF += 2;
1867 Location = FloatRegs;
1868 break;
1870 if (Location == IntRegs)
1871 RegI += 2;
1872 else if (Location == FloatRegs)
1873 RegF += 2;
1874 else
1875 return false;
1876 break;
1877 case Win64EH::UOP_Nop:
1878 if (Location != IntRegs && Location != FloatRegs && Location != InputArgs)
1879 return false;
1880 Location = InputArgs;
1881 Nops++;
1882 break;
1885 if (Location != Start2 && Location != Start3 && Location != IntRegs &&
1886 Location != FloatRegs && Location != InputArgs &&
1887 Location != StackAdjust)
1888 return false;
1889 // Becuase there's no save_lrpair_x opcode, the case of CR=01,
1890 // RegI=1 is handled as a special case with a pair of instructions; an
1891 // alloc followed by a regular save_lrpair. So when encountering an
1892 // alloc here, check if this is the start of such an instruction pair.
1893 if (Location == Start2) { // Can't have this at Start3, after PACSignLR
1894 auto NextIt = It + 1;
1895 if (NextIt != EndIt) {
1896 const WinEH::Instruction &NextInst = *NextIt;
1897 if (NextInst.Operation == Win64EH::UOP_SaveLRPair &&
1898 NextInst.Offset == 0 && NextInst.Register == 19) {
1899 assert(Predecrement == 0);
1900 assert(RegI == 0);
1901 assert(!StandaloneLR);
1902 Predecrement = Inst.Offset;
1903 RegI = 1;
1904 StandaloneLR = true;
1905 Location = FloatRegs;
1906 It++; // Consume both the Alloc and the SaveLRPair
1907 continue;
1908 }
1909 }
1910 }
1911 // Can have either a single decrement, or a pair of decrements with
1912 // 4080 and another decrement.
1913 if (StackOffset == 0)
1914 StackOffset = Inst.Offset;
1915 else if (StackOffset != 4080)
1916 return false;
1917 else
1918 StackOffset += Inst.Offset;
1919 Location = StackAdjust;
1920 break;
1922 // Not allowing FPLRX after StackAdjust; if a StackAdjust is used, it
1923 // should be followed by a FPLR instead.
1924 if (Location != Start2 && Location != Start3 && Location != IntRegs &&
1925 Location != FloatRegs && Location != InputArgs)
1926 return false;
1927 StackOffset = Inst.Offset;
1928 Location = FrameRecord;
1929 FPLRPair = true;
1930 break;
1932 // This can only follow after a StackAdjust
1933 if (Location != StackAdjust || Inst.Offset != 0)
1934 return false;
1935 Location = FrameRecord;
1936 FPLRPair = true;
1937 break;
1938 case Win64EH::UOP_SetFP:
1939 if (Location != FrameRecord)
1940 return false;
1941 Location = End;
1942 break;
1955 // These are never canonical; they don't show up with the usual Arm64
1956 // calling convention.
1957 return false;
1959 // Allocations this large can't be represented in packed unwind (and
1960 // usually don't fit the canonical form anyway because we need to use
1961 // __chkstk to allocate the stack space).
1962 return false;
1963 case Win64EH::UOP_AddFP:
1964 // "add x29, sp, #N" doesn't show up in the canonical pattern (except for
1965 // N=0, which is UOP_SetFP).
1966 return false;
1970 // Canonical prologues don't support spilling SVE registers.
1971 return false;
1977 // These are special opcodes that aren't normally generated.
1978 return false;
1979 default:
1980 report_fatal_error("Unknown Arm64 unwind opcode");
1981 }
1982 }
1983 if (RegI > 10 || RegF > 8)
1984 return false;
1985 if (StandaloneLR && FPLRPair)
1986 return false;
1987 if (FPLRPair && Location != End)
1988 return false;
1989 if (Nops != 0 && Nops != 4)
1990 return false;
1991 if (PAC && !FPLRPair)
1992 return false;
1993 int H = Nops == 4;
1994 // For packed unwind info with the H bit set, the prolog and epilog
1995 // actually shouldn't be symmetrical; the epilog shouldn't have any
1996 // nop instructions/opcodes while the prolog has them. We currently
1997 // require exactly symmetrical prologs/epilogs, which is wrong for this
1998 // case - therefore, don't emit packed unwind info for this case.
1999 // See https://github.com/llvm/llvm-project/issues/54879 for details.
2000 //
2001 // Additionally - older versions of Windows also deviated from the
2002 // documentation here; older versions of Windows (at least up until
2003 // 10.0.22000.2176) incorrectly did assume that the epilog has matching
2004 // nop instructions. This is fixed at least in version 10.0.26100.6899.
2005 // As long as we can't assume that the generated code always will run on
2006 // a new enough version, don't emit the packed format here, even if the
2007 // implementation would be fixed to match for the asymmetrical form
2008 // according to the documentation.
2009 if (H)
2010 return false;
2011 // Older versions of Windows (at least in 10.0.22000.2176) incorrectly
2012 // unwind packed unwind info with CR=01, RegI=1, RegF>0, see
2013 // https://github.com/llvm/llvm-project/issues/169588#issuecomment-3584907886.
2014 // This issue only exists in older versions; current versions
2015 // (10.0.26100.6899) do handle it correctly. As long as we can't be sure
2016 // that we won't run on older versions, avoid producing the packed form
2017 // here.
2018 if (StandaloneLR && RegI == 1 && RegF > 0)
2019 return false;
2020 int IntSZ = 8 * RegI;
2021 if (StandaloneLR)
2022 IntSZ += 8;
2023 int FpSZ = 8 * RegF; // RegF not yet decremented
2024 int SavSZ = (IntSZ + FpSZ + 8 * 8 * H + 0xF) & ~0xF;
2025 if (Predecrement != SavSZ)
2026 return false;
2027 if (FPLRPair && StackOffset < 16)
2028 return false;
2029 if (StackOffset % 16)
2030 return false;
2031 uint32_t FrameSize = (StackOffset + SavSZ) / 16;
2032 if (FrameSize > 0x1FF)
2033 return false;
2034 assert(RegF != 1 && "One single float reg not allowed");
2035 if (RegF > 0)
2036 RegF--; // Convert from actual number of registers, to value stored
2037 assert(FuncLength <= 0x7FF && "FuncLength should have been checked earlier");
2038 int Flag = 0x01; // Function segments not supported yet
2039 int CR = PAC ? 2 : FPLRPair ? 3 : StandaloneLR ? 1 : 0;
2040 info->PackedInfo |= Flag << 0;
2041 info->PackedInfo |= (FuncLength & 0x7FF) << 2;
2042 info->PackedInfo |= (RegF & 0x7) << 13;
2043 info->PackedInfo |= (RegI & 0xF) << 16;
2044 info->PackedInfo |= (H & 0x1) << 20;
2045 info->PackedInfo |= (CR & 0x3) << 21;
2046 info->PackedInfo |= (FrameSize & 0x1FF) << 23;
2047 return true;
2048}
2049
2053 uint32_t &TotalCodeBytes,
2054 MapVector<MCSymbol *, uint32_t> &EpilogInfo) {
2055
2056 std::vector<MCSymbol *> EpilogStarts;
2057 for (auto &I : Seg->Epilogs)
2058 EpilogStarts.push_back(I.first);
2059
2060 // Epilogs processed so far.
2061 std::vector<MCSymbol *> AddedEpilogs;
2062 for (auto *S : EpilogStarts) {
2063 MCSymbol *EpilogStart = S;
2064 auto &EpilogInstrs = info->EpilogMap[S].Instructions;
2065 uint32_t CodeBytes = ARM64CountOfUnwindCodes(EpilogInstrs);
2066
2067 MCSymbol* MatchingEpilog =
2068 FindMatchingEpilog(EpilogInstrs, AddedEpilogs, info);
2069 int PrologOffset;
2070 if (MatchingEpilog) {
2071 assert(EpilogInfo.contains(MatchingEpilog) &&
2072 "Duplicate epilog not found");
2073 EpilogInfo[EpilogStart] = EpilogInfo.lookup(MatchingEpilog);
2074 // Clear the unwind codes in the EpilogMap, so that they don't get output
2075 // in ARM64EmitUnwindInfoForSegment().
2076 EpilogInstrs.clear();
2077 } else if ((PrologOffset = getARM64OffsetInProlog(Prolog, EpilogInstrs)) >=
2078 0) {
2079 EpilogInfo[EpilogStart] = PrologOffset;
2080 // Clear the unwind codes in the EpilogMap, so that they don't get output
2081 // in ARM64EmitUnwindInfoForSegment().
2082 EpilogInstrs.clear();
2083 } else {
2084 EpilogInfo[EpilogStart] = TotalCodeBytes;
2085 TotalCodeBytes += CodeBytes;
2086 AddedEpilogs.push_back(EpilogStart);
2087 }
2088 }
2089}
2090
2093 int64_t RawFuncLength) {
2094 if (info->PrologEnd)
2095 checkARM64Instructions(streamer, info->Instructions, info->Begin,
2096 info->PrologEnd, info->Function->getName(), true);
2097 struct EpilogStartEnd {
2098 MCSymbol *Start;
2099 int64_t Offset;
2100 int64_t End;
2101 };
2102 // Record Start and End of each epilog.
2104 for (auto &I : info->EpilogMap) {
2105 MCSymbol *Start = I.first;
2106 auto &Instrs = I.second.Instructions;
2107 int64_t Offset = GetAbsDifference(streamer, Start, info->Begin);
2108 checkARM64Instructions(streamer, Instrs, Start, I.second.End,
2109 info->Function->getName(), false);
2110 assert((Epilogs.size() == 0 || Offset >= Epilogs.back().End) &&
2111 "Epilogs should be monotonically ordered");
2112 Epilogs.push_back(
2113 {Start, Offset,
2114 Offset + (int64_t)ARM64CountOfInstructions(Instrs, false) * 4});
2115 }
2116
2117 unsigned E = 0;
2118 int64_t SegLimit = 0xFFFFC;
2119 int64_t SegOffset = 0;
2120
2121 if (RawFuncLength > SegLimit) {
2122
2123 int64_t RemainingLength = RawFuncLength;
2124
2125 while (RemainingLength > SegLimit) {
2126 // Try divide the function into segments, requirements:
2127 // 1. Segment length <= 0xFFFFC;
2128 // 2. Each Prologue or Epilogue must be fully within a segment.
2129 int64_t SegLength = SegLimit;
2130 int64_t SegEnd = SegOffset + SegLength;
2131 // Keep record on symbols and offsets of epilogs in this segment.
2132 MapVector<MCSymbol *, int64_t> EpilogsInSegment;
2133
2134 while (E < Epilogs.size() && Epilogs[E].End < SegEnd) {
2135 // Epilogs within current segment.
2136 EpilogsInSegment[Epilogs[E].Start] = Epilogs[E].Offset;
2137 ++E;
2138 }
2139
2140 // At this point, we have:
2141 // 1. Put all epilogs in segments already. No action needed here; or
2142 // 2. Found an epilog that will cross segments boundry. We need to
2143 // move back current segment's end boundry, so the epilog is entirely
2144 // in the next segment; or
2145 // 3. Left at least one epilog that is entirely after this segment.
2146 // It'll be handled by the next iteration, or the last segment.
2147 if (E < Epilogs.size() && Epilogs[E].Offset <= SegEnd)
2148 // Move back current Segment's end boundry.
2149 SegLength = Epilogs[E].Offset - SegOffset;
2150
2151 auto Seg = WinEH::FrameInfo::Segment(
2152 SegOffset, SegLength, /* HasProlog */!SegOffset);
2153 Seg.Epilogs = std::move(EpilogsInSegment);
2154 info->Segments.push_back(Seg);
2155
2156 SegOffset += SegLength;
2157 RemainingLength -= SegLength;
2158 }
2159 }
2160
2161 // Add the last segment when RawFuncLength > 0xFFFFC,
2162 // or the only segment otherwise.
2163 auto LastSeg =
2164 WinEH::FrameInfo::Segment(SegOffset, RawFuncLength - SegOffset,
2165 /* HasProlog */!SegOffset);
2166 for (; E < Epilogs.size(); ++E)
2167 LastSeg.Epilogs[Epilogs[E].Start] = Epilogs[E].Offset;
2168 info->Segments.push_back(LastSeg);
2169}
2170
2174 bool TryPacked = true) {
2175 MCContext &context = streamer.getContext();
2176 MCSymbol *Label = context.createTempSymbol();
2177
2178 streamer.emitValueToAlignment(Align(4));
2179 streamer.emitLabel(Label);
2180 Seg.Symbol = Label;
2181 // Use the 1st segemnt's label as function's.
2182 if (Seg.Offset == 0)
2183 info->Symbol = Label;
2184
2185 bool HasProlog = Seg.HasProlog;
2186 bool HasEpilogs = (Seg.Epilogs.size() != 0);
2187 SmallVector<WinEH::Instruction> PhantomProlog;
2189 if (!HasProlog) {
2190 for (const WinEH::Instruction &Inst : Prolog)
2191 if (Inst.Operation != Win64EH::UOP_EndC)
2192 PhantomProlog.push_back(Inst);
2193 PhantomProlog.emplace_back(Win64EH::UOP_EndC, nullptr, -1, 0);
2194 Prolog = PhantomProlog;
2195 }
2196
2197 uint32_t SegLength = (uint32_t)Seg.Length / 4;
2198 uint32_t PrologCodeBytes = ARM64CountOfUnwindCodes(Prolog);
2199
2200 int PackedEpilogOffset = HasEpilogs
2201 ? checkARM64PackedEpilog(streamer, info, &Seg,
2202 Prolog, PrologCodeBytes)
2203 : -1;
2204
2205 // TODO:
2206 // 1. Enable packed unwind info (.pdata only) for multi-segment functions.
2207 // 2. Emit packed unwind info (.pdata only) for segments that have neithor
2208 // prolog nor epilog.
2209 if (info->Segments.size() == 1 && PackedEpilogOffset >= 0 &&
2210 uint32_t(PackedEpilogOffset) < PrologCodeBytes &&
2211 !info->HandlesExceptions && SegLength <= 0x7ff && TryPacked) {
2212 // Matching prolog/epilog and no exception handlers; check if the
2213 // prolog matches the patterns that can be described by the packed
2214 // format.
2215
2216 // info->Symbol was already set even if we didn't actually write any
2217 // unwind info there. Keep using that as indicator that this unwind
2218 // info has been generated already.
2219 if (tryARM64PackedUnwind(info, SegLength, PackedEpilogOffset))
2220 return;
2221 }
2222
2223 if (!HasProlog && !HasEpilogs) {
2224 // If a segment has neither prolog nor epilog, "With full .xdata record,
2225 // Epilog Count = 1. Epilog Start Index points to end_c."
2226 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling#function-fragments
2227 // TODO: We can remove this if testing shows zero epilog scope is ok with
2228 // MS unwinder.
2229 // Pack the fake epilog into phantom prolog.
2230 PackedEpilogOffset = 0;
2231 }
2232
2233 uint32_t TotalCodeBytes = PrologCodeBytes;
2234
2235 // Process epilogs.
2237 ARM64ProcessEpilogs(info, &Seg, Prolog, TotalCodeBytes, EpilogInfo);
2238
2239 // Code Words, Epilog count, E, X, Vers, Function Length
2240 uint32_t row1 = 0x0;
2241 uint32_t CodeWords = TotalCodeBytes / 4;
2242 uint32_t CodeWordsMod = TotalCodeBytes % 4;
2243 if (CodeWordsMod)
2244 CodeWords++;
2245 uint32_t EpilogCount =
2246 PackedEpilogOffset >= 0 ? PackedEpilogOffset : Seg.Epilogs.size();
2247 bool ExtensionWord = EpilogCount > 31 || TotalCodeBytes > 124;
2248 if (!ExtensionWord) {
2249 row1 |= (EpilogCount & 0x1F) << 22;
2250 row1 |= (CodeWords & 0x1F) << 27;
2251 }
2252 if (info->HandlesExceptions) // X
2253 row1 |= 1 << 20;
2254 if (PackedEpilogOffset >= 0) // E
2255 row1 |= 1 << 21;
2256 row1 |= SegLength & 0x3FFFF;
2257 streamer.emitInt32(row1);
2258
2259 // Extended Code Words, Extended Epilog Count
2260 if (ExtensionWord) {
2261 // FIXME: We should be able to split unwind info into multiple sections.
2262 if (CodeWords > 0xFF || EpilogCount > 0xFFFF)
2264 "SEH unwind data splitting is only implemented for large functions, "
2265 "cases of too many code words or too many epilogs will be done "
2266 "later");
2267 uint32_t row2 = 0x0;
2268 row2 |= (CodeWords & 0xFF) << 16;
2269 row2 |= (EpilogCount & 0xFFFF);
2270 streamer.emitInt32(row2);
2271 }
2272
2273 if (PackedEpilogOffset < 0) {
2274 // Epilog Start Index, Epilog Start Offset
2275 for (auto &I : EpilogInfo) {
2276 MCSymbol *EpilogStart = I.first;
2277 uint32_t EpilogIndex = I.second;
2278 // Epilog offset within the Segment.
2279 uint32_t EpilogOffset = (uint32_t)(Seg.Epilogs[EpilogStart] - Seg.Offset);
2280 if (EpilogOffset)
2281 EpilogOffset /= 4;
2282 uint32_t row3 = EpilogOffset;
2283 row3 |= (EpilogIndex & 0x3FF) << 22;
2284 streamer.emitInt32(row3);
2285 }
2286 }
2287
2288 // Note that even for segments that have no prolog, we still need to emit
2289 // prolog unwinding opcodes so that the unwinder knows how to unwind from
2290 // such a segment.
2291 // The end_c opcode at the start indicates to the unwinder that the actual
2292 // prolog is outside of the current segment, and the unwinder shouldn't try
2293 // to check for unwinding from a partial prolog.
2294
2295 // Emit prolog unwind instructions (in reverse order).
2296 for (auto Inst : llvm::reverse(Prolog))
2297 ARM64EmitUnwindCode(streamer, Inst);
2298
2299 // Emit epilog unwind instructions
2300 for (auto &I : Seg.Epilogs) {
2301 auto &EpilogInstrs = info->EpilogMap[I.first].Instructions;
2302 for (const WinEH::Instruction &inst : EpilogInstrs)
2303 ARM64EmitUnwindCode(streamer, inst);
2304 }
2305
2306 int32_t BytesMod = CodeWords * 4 - TotalCodeBytes;
2307 assert(BytesMod >= 0);
2308 for (int i = 0; i < BytesMod; i++)
2309 streamer.emitInt8(0xE3);
2310
2311 if (info->HandlesExceptions)
2312 streamer.emitValue(
2313 MCSymbolRefExpr::create(info->ExceptionHandler,
2315 4);
2316}
2317
2318// Populate the .xdata section. The format of .xdata on ARM64 is documented at
2319// https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
2321 bool TryPacked = true) {
2322 // If this UNWIND_INFO already has a symbol, it's already been emitted.
2323 if (info->Symbol)
2324 return;
2325 // If there's no unwind info here (not even a terminating UOP_End), the
2326 // unwind info is considered bogus and skipped. If this was done in
2327 // response to an explicit .seh_handlerdata, the associated trailing
2328 // handler data is left orphaned in the xdata section.
2329 if (info->empty()) {
2330 info->EmitAttempted = true;
2331 return;
2332 }
2333 if (info->EmitAttempted) {
2334 // If we tried to emit unwind info before (due to an explicit
2335 // .seh_handlerdata directive), but skipped it (because there was no
2336 // valid information to emit at the time), and it later got valid unwind
2337 // opcodes, we can't emit it here, because the trailing handler data
2338 // was already emitted elsewhere in the xdata section.
2339 streamer.getContext().reportError(
2340 SMLoc(), "Earlier .seh_handlerdata for " + info->Function->getName() +
2341 " skipped due to no unwind info at the time "
2342 "(.seh_handlerdata too early?), but the function later "
2343 "did get unwind info that can't be emitted");
2344 return;
2345 }
2346
2347 simplifyARM64Opcodes(info->Instructions, false);
2348 for (auto &I : info->EpilogMap)
2349 simplifyARM64Opcodes(I.second.Instructions, true);
2350
2351 int64_t RawFuncLength;
2352 if (!info->FuncletOrFuncEnd) {
2353 report_fatal_error("FuncletOrFuncEnd not set");
2354 } else {
2355 // FIXME: GetAbsDifference tries to compute the length of the function
2356 // immediately, before the whole file is emitted, but in general
2357 // that's impossible: the size in bytes of certain assembler directives
2358 // like .align and .fill is not known until the whole file is parsed and
2359 // relaxations are applied. Currently, GetAbsDifference fails with a fatal
2360 // error in that case. (We mostly don't hit this because inline assembly
2361 // specifying those directives is rare, and we don't normally try to
2362 // align loops on AArch64.)
2363 //
2364 // There are two potential approaches to delaying the computation. One,
2365 // we could emit something like ".word (endfunc-beginfunc)/4+0x10800000",
2366 // as long as we have some conservative estimate we could use to prove
2367 // that we don't need to split the unwind data. Emitting the constant
2368 // is straightforward, but there's no existing code for estimating the
2369 // size of the function.
2370 //
2371 // The other approach would be to use a dedicated, relaxable fragment,
2372 // which could grow to accommodate splitting the unwind data if
2373 // necessary. This is more straightforward, since it automatically works
2374 // without any new infrastructure, and it's consistent with how we handle
2375 // relaxation in other contexts. But it would require some refactoring
2376 // to move parts of the pdata/xdata emission into the implementation of
2377 // a fragment. We could probably continue to encode the unwind codes
2378 // here, but we'd have to emit the pdata, the xdata header, and the
2379 // epilogue scopes later, since they depend on whether the we need to
2380 // split the unwind data.
2381 //
2382 // If this is fixed, remove code in AArch64ISelLowering.cpp that
2383 // disables loop alignment on Windows.
2384 RawFuncLength = GetAbsDifference(streamer, info->FuncletOrFuncEnd,
2385 info->Begin);
2386 }
2387
2388 ARM64FindSegmentsInFunction(streamer, info, RawFuncLength);
2389
2390 info->PrologCodeBytes = ARM64CountOfUnwindCodes(info->Instructions);
2391 for (auto &S : info->Segments)
2392 ARM64EmitUnwindInfoForSegment(streamer, info, S, TryPacked);
2393
2394 // Clear prolog instructions after unwind info is emitted for all segments.
2395 info->Instructions.clear();
2396}
2397
2399 uint32_t Count = 0;
2400 for (const auto &I : Insns) {
2401 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
2402 default:
2403 llvm_unreachable("Unsupported ARM unwind code");
2405 Count += 1;
2406 break;
2408 Count += 3;
2409 break;
2411 Count += 4;
2412 break;
2414 Count += 2;
2415 break;
2417 Count += 3;
2418 break;
2420 Count += 4;
2421 break;
2423 Count += 2;
2424 break;
2426 Count += 1;
2427 break;
2429 Count += 1;
2430 break;
2432 Count += 1;
2433 break;
2435 Count += 1;
2436 break;
2438 Count += 2;
2439 break;
2441 Count += 2;
2442 break;
2444 Count += 2;
2445 break;
2447 Count += 2;
2448 break;
2449 case Win64EH::UOP_Nop:
2451 case Win64EH::UOP_End:
2454 Count += 1;
2455 break;
2456 case Win64EH::UOP_Custom: {
2457 int J;
2458 for (J = 3; J > 0; J--)
2459 if (I.Offset & (0xffu << (8 * J)))
2460 break;
2461 Count += J + 1;
2462 break;
2463 }
2464 }
2465 }
2466 return Count;
2467}
2468
2470 bool *HasCustom = nullptr) {
2471 uint32_t Count = 0;
2472 for (const auto &I : Insns) {
2473 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
2474 default:
2475 llvm_unreachable("Unsupported ARM unwind code");
2479 Count += 2;
2480 break;
2484 Count += 4;
2485 break;
2488 Count += 4;
2489 break;
2491 Count += 2;
2492 break;
2495 Count += 2;
2496 break;
2500 Count += 4;
2501 break;
2503 Count += 4;
2504 break;
2505 case Win64EH::UOP_Nop:
2507 Count += 2;
2508 break;
2511 Count += 4;
2512 break;
2513 case Win64EH::UOP_End:
2514 // This doesn't map to any instruction
2515 break;
2517 // We can't reason about what instructions this maps to; return a
2518 // phony number to make sure we don't accidentally do epilog packing.
2519 Count += 1000;
2520 if (HasCustom)
2521 *HasCustom = true;
2522 break;
2523 }
2524 }
2525 return Count;
2526}
2527
2530 const MCSymbol *Begin, const MCSymbol *End,
2531 StringRef Name, StringRef Type) {
2532 if (!End)
2533 return;
2534 std::optional<int64_t> MaybeDistance =
2536 if (!MaybeDistance)
2537 return;
2538 uint32_t Distance = (uint32_t)*MaybeDistance;
2539 bool HasCustom = false;
2540 uint32_t InstructionBytes = ARMCountOfInstructionBytes(Insns, &HasCustom);
2541 if (HasCustom)
2542 return;
2543 if (Distance != InstructionBytes) {
2544 Streamer.getContext().reportError(
2545 SMLoc(), "Incorrect size for " + Name + " " + Type + ": " +
2546 Twine(Distance) +
2547 " bytes of instructions in range, but .seh directives "
2548 "corresponding to " +
2549 Twine(InstructionBytes) + " bytes\n");
2550 }
2551}
2552
2553static bool isARMTerminator(const WinEH::Instruction &inst) {
2554 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
2555 case Win64EH::UOP_End:
2558 return true;
2559 default:
2560 return false;
2561 }
2562}
2563
2564// Unwind opcode encodings and restrictions are documented at
2565// https://docs.microsoft.com/en-us/cpp/build/arm-exception-handling
2566static void ARMEmitUnwindCode(MCStreamer &streamer,
2567 const WinEH::Instruction &inst) {
2568 uint32_t w, lr;
2569 int i;
2570 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
2571 default:
2572 llvm_unreachable("Unsupported ARM unwind code");
2574 assert((inst.Offset & 3) == 0);
2575 assert(inst.Offset / 4 <= 0x7f);
2576 streamer.emitInt8(inst.Offset / 4);
2577 break;
2579 assert((inst.Register & ~0x5fff) == 0);
2580 lr = (inst.Register >> 14) & 1;
2581 w = 0x8000 | (inst.Register & 0x1fff) | (lr << 13);
2582 streamer.emitInt8((w >> 8) & 0xff);
2583 streamer.emitInt8((w >> 0) & 0xff);
2584 break;
2586 assert(inst.Register <= 0x0f);
2587 streamer.emitInt8(0xc0 | inst.Register);
2588 break;
2590 assert(inst.Register >= 4 && inst.Register <= 7);
2591 assert(inst.Offset <= 1);
2592 streamer.emitInt8(0xd0 | (inst.Register - 4) | (inst.Offset << 2));
2593 break;
2595 assert(inst.Register >= 8 && inst.Register <= 11);
2596 assert(inst.Offset <= 1);
2597 streamer.emitInt8(0xd8 | (inst.Register - 8) | (inst.Offset << 2));
2598 break;
2600 assert(inst.Register >= 8 && inst.Register <= 15);
2601 streamer.emitInt8(0xe0 | (inst.Register - 8));
2602 break;
2604 assert((inst.Offset & 3) == 0);
2605 assert(inst.Offset / 4 <= 0x3ff);
2606 w = 0xe800 | (inst.Offset / 4);
2607 streamer.emitInt8((w >> 8) & 0xff);
2608 streamer.emitInt8((w >> 0) & 0xff);
2609 break;
2611 assert((inst.Register & ~0x40ff) == 0);
2612 lr = (inst.Register >> 14) & 1;
2613 w = 0xec00 | (inst.Register & 0x0ff) | (lr << 8);
2614 streamer.emitInt8((w >> 8) & 0xff);
2615 streamer.emitInt8((w >> 0) & 0xff);
2616 break;
2618 assert((inst.Offset & 3) == 0);
2619 assert(inst.Offset / 4 <= 0x0f);
2620 streamer.emitInt8(0xef);
2621 streamer.emitInt8(inst.Offset / 4);
2622 break;
2624 assert(inst.Register <= 15);
2625 assert(inst.Offset <= 15);
2626 assert(inst.Register <= inst.Offset);
2627 streamer.emitInt8(0xf5);
2628 streamer.emitInt8((inst.Register << 4) | inst.Offset);
2629 break;
2631 assert(inst.Register >= 16 && inst.Register <= 31);
2632 assert(inst.Offset >= 16 && inst.Offset <= 31);
2633 assert(inst.Register <= inst.Offset);
2634 streamer.emitInt8(0xf6);
2635 streamer.emitInt8(((inst.Register - 16) << 4) | (inst.Offset - 16));
2636 break;
2638 assert((inst.Offset & 3) == 0);
2639 assert(inst.Offset / 4 <= 0xffff);
2640 w = inst.Offset / 4;
2641 streamer.emitInt8(0xf7);
2642 streamer.emitInt8((w >> 8) & 0xff);
2643 streamer.emitInt8((w >> 0) & 0xff);
2644 break;
2646 assert((inst.Offset & 3) == 0);
2647 assert(inst.Offset / 4 <= 0xffffff);
2648 w = inst.Offset / 4;
2649 streamer.emitInt8(0xf8);
2650 streamer.emitInt8((w >> 16) & 0xff);
2651 streamer.emitInt8((w >> 8) & 0xff);
2652 streamer.emitInt8((w >> 0) & 0xff);
2653 break;
2655 assert((inst.Offset & 3) == 0);
2656 assert(inst.Offset / 4 <= 0xffff);
2657 w = inst.Offset / 4;
2658 streamer.emitInt8(0xf9);
2659 streamer.emitInt8((w >> 8) & 0xff);
2660 streamer.emitInt8((w >> 0) & 0xff);
2661 break;
2663 assert((inst.Offset & 3) == 0);
2664 assert(inst.Offset / 4 <= 0xffffff);
2665 w = inst.Offset / 4;
2666 streamer.emitInt8(0xfa);
2667 streamer.emitInt8((w >> 16) & 0xff);
2668 streamer.emitInt8((w >> 8) & 0xff);
2669 streamer.emitInt8((w >> 0) & 0xff);
2670 break;
2671 case Win64EH::UOP_Nop:
2672 streamer.emitInt8(0xfb);
2673 break;
2675 streamer.emitInt8(0xfc);
2676 break;
2678 streamer.emitInt8(0xfd);
2679 break;
2681 streamer.emitInt8(0xfe);
2682 break;
2683 case Win64EH::UOP_End:
2684 streamer.emitInt8(0xff);
2685 break;
2687 for (i = 3; i > 0; i--)
2688 if (inst.Offset & (0xffu << (8 * i)))
2689 break;
2690 for (; i >= 0; i--)
2691 streamer.emitInt8((inst.Offset >> (8 * i)) & 0xff);
2692 break;
2693 }
2694}
2695
2696// Check if an epilog exists as a subset of the end of a prolog (backwards).
2697// An epilog may end with one out of three different end opcodes; if this
2698// is the first epilog that shares opcodes with the prolog, we can tolerate
2699// that this opcode differs (and the caller will update the prolog to use
2700// the same end opcode as the epilog). If another epilog already shares
2701// opcodes with the prolog, the ending opcode must be a strict match.
2702static int getARMOffsetInProlog(const std::vector<WinEH::Instruction> &Prolog,
2703 const std::vector<WinEH::Instruction> &Epilog,
2704 bool CanTweakProlog) {
2705 // Can't find an epilog as a subset if it is longer than the prolog.
2706 if (Epilog.size() > Prolog.size())
2707 return -1;
2708
2709 // Check that the epilog actually is a perfect match for the end (backwrds)
2710 // of the prolog.
2711 // If we can adjust the prolog afterwards, don't check that the end opcodes
2712 // match.
2713 int EndIdx = CanTweakProlog ? 1 : 0;
2714 for (int I = Epilog.size() - 1; I >= EndIdx; I--) {
2715 // TODO: Could also allow minor mismatches, e.g. "add sp, #16" vs
2716 // "push {r0-r3}".
2717 if (Prolog[I] != Epilog[Epilog.size() - 1 - I])
2718 return -1;
2719 }
2720
2721 if (CanTweakProlog) {
2722 // Check that both prolog and epilog end with an expected end opcode.
2723 if (Prolog.front().Operation != Win64EH::UOP_End)
2724 return -1;
2725 if (Epilog.back().Operation != Win64EH::UOP_End &&
2726 Epilog.back().Operation != Win64EH::UOP_EndNop &&
2727 Epilog.back().Operation != Win64EH::UOP_WideEndNop)
2728 return -1;
2729 }
2730
2731 // If the epilog was a subset of the prolog, find its offset.
2732 if (Epilog.size() == Prolog.size())
2733 return 0;
2735 &Prolog[Epilog.size()], Prolog.size() - Epilog.size()));
2736}
2737
2739 int PrologCodeBytes) {
2740 // Can only pack if there's one single epilog
2741 if (info->EpilogMap.size() != 1)
2742 return -1;
2743
2744 const WinEH::FrameInfo::Epilog &EpilogInfo = info->EpilogMap.begin()->second;
2745 // Can only pack if the epilog is unconditional
2746 if (EpilogInfo.Condition != 0xe) // ARMCC::AL
2747 return -1;
2748
2749 const std::vector<WinEH::Instruction> &Epilog = EpilogInfo.Instructions;
2750 // Make sure we have at least the trailing end opcode
2751 if (info->Instructions.empty() || Epilog.empty())
2752 return -1;
2753
2754 // Check that the epilog actually is at the very end of the function,
2755 // otherwise it can't be packed.
2756 std::optional<int64_t> MaybeDistance = GetOptionalAbsDifference(
2757 streamer, info->FuncletOrFuncEnd, info->EpilogMap.begin()->first);
2758 if (!MaybeDistance)
2759 return -1;
2760 uint32_t DistanceFromEnd = (uint32_t)*MaybeDistance;
2761 uint32_t InstructionBytes = ARMCountOfInstructionBytes(Epilog);
2762 if (DistanceFromEnd != InstructionBytes)
2763 return -1;
2764
2765 int RetVal = -1;
2766 // Even if we don't end up sharing opcodes with the prolog, we can still
2767 // write the offset as a packed offset, if the single epilog is located at
2768 // the end of the function and the offset (pointing after the prolog) fits
2769 // as a packed offset.
2770 if (PrologCodeBytes <= 31 &&
2771 PrologCodeBytes + ARMCountOfUnwindCodes(Epilog) <= 63)
2772 RetVal = PrologCodeBytes;
2773
2774 int Offset =
2775 getARMOffsetInProlog(info->Instructions, Epilog, /*CanTweakProlog=*/true);
2776 if (Offset < 0)
2777 return RetVal;
2778
2779 // Check that the offset and prolog size fits in the first word; it's
2780 // unclear whether the epilog count in the extension word can be taken
2781 // as packed epilog offset.
2782 if (Offset > 31 || PrologCodeBytes > 63)
2783 return RetVal;
2784
2785 // Replace the regular end opcode of the prolog with the one from the
2786 // epilog.
2787 info->Instructions.front() = Epilog.back();
2788
2789 // As we choose to express the epilog as part of the prolog, remove the
2790 // epilog from the map, so we don't try to emit its opcodes.
2791 info->EpilogMap.clear();
2792 return Offset;
2793}
2794
2795static bool parseRegMask(unsigned Mask, bool &HasLR, bool &HasR11,
2796 unsigned &Folded, int &IntRegs) {
2797 if (Mask & (1 << 14)) {
2798 HasLR = true;
2799 Mask &= ~(1 << 14);
2800 }
2801 if (Mask & (1 << 11)) {
2802 HasR11 = true;
2803 Mask &= ~(1 << 11);
2804 }
2805 Folded = 0;
2806 IntRegs = -1;
2807 if (!Mask)
2808 return true;
2809 int First = 0;
2810 // Shift right until we have the bits at the bottom
2811 while ((Mask & 1) == 0) {
2812 First++;
2813 Mask >>= 1;
2814 }
2815 if ((Mask & (Mask + 1)) != 0)
2816 return false; // Not a consecutive series of bits? Can't be packed.
2817 // Count the bits
2818 int N = 0;
2819 while (Mask & (1 << N))
2820 N++;
2821 if (First < 4) {
2822 if (First + N < 4)
2823 return false;
2824 Folded = 4 - First;
2825 N -= Folded;
2826 First = 4;
2827 }
2828 if (First > 4)
2829 return false; // Can't be packed
2830 if (N >= 1)
2831 IntRegs = N - 1;
2832 return true;
2833}
2834
2836 uint32_t FuncLength) {
2837 int Step = 0;
2838 bool Homing = false;
2839 bool HasR11 = false;
2840 bool HasChain = false;
2841 bool HasLR = false;
2842 int IntRegs = -1; // r4 - r(4+N)
2843 int FloatRegs = -1; // d8 - d(8+N)
2844 unsigned PF = 0; // Number of extra pushed registers
2845 unsigned StackAdjust = 0;
2846 // Iterate over the prolog and check that all opcodes exactly match
2847 // the canonical order and form.
2848 for (const WinEH::Instruction &Inst : info->Instructions) {
2849 switch (Inst.Operation) {
2850 default:
2851 llvm_unreachable("Unsupported ARM unwind code");
2859 // Can't be packed
2860 return false;
2862 // Can't be packed; we can't rely on restoring sp from r11 when
2863 // unwinding a packed prologue.
2864 return false;
2866 // Can't be present in a packed prologue
2867 return false;
2868
2869 case Win64EH::UOP_End:
2872 if (Step != 0)
2873 return false;
2874 Step = 1;
2875 break;
2876
2879 // push {r4-r11,lr}
2880 if (Step != 1 && Step != 2)
2881 return false;
2882 assert(Inst.Register >= 4 && Inst.Register <= 11); // r4-rX
2883 assert(Inst.Offset <= 1); // Lr
2884 IntRegs = Inst.Register - 4;
2885 if (Inst.Register == 11) {
2886 HasR11 = true;
2887 IntRegs--;
2888 }
2889 if (Inst.Offset)
2890 HasLR = true;
2891 Step = 3;
2892 break;
2893
2895 if (Step == 1 && Inst.Register == 0x0f) {
2896 // push {r0-r3}
2897 Homing = true;
2898 Step = 2;
2899 break;
2900 }
2901 [[fallthrough]];
2903 if (Step != 1 && Step != 2)
2904 return false;
2905 // push {r4-r9,r11,lr}
2906 // push {r11,lr}
2907 // push {r1-r5}
2908 if (!parseRegMask(Inst.Register, HasLR, HasR11, PF, IntRegs))
2909 return false;
2910 Step = 3;
2911 break;
2912
2913 case Win64EH::UOP_Nop:
2914 // mov r11, sp
2915 if (Step != 3 || !HasR11 || IntRegs >= 0 || PF > 0)
2916 return false;
2917 HasChain = true;
2918 Step = 4;
2919 break;
2921 // add.w r11, sp, #xx
2922 if (Step != 3 || !HasR11 || (IntRegs < 0 && PF == 0))
2923 return false;
2924 HasChain = true;
2925 Step = 4;
2926 break;
2927
2929 if (Step != 1 && Step != 2 && Step != 3 && Step != 4)
2930 return false;
2931 assert(Inst.Register >= 8 && Inst.Register <= 15);
2932 if (Inst.Register == 15)
2933 return false; // Can't pack this case, R==7 means no IntRegs
2934 if (IntRegs >= 0)
2935 return false;
2936 FloatRegs = Inst.Register - 8;
2937 Step = 5;
2938 break;
2939
2942 if (Step != 1 && Step != 2 && Step != 3 && Step != 4 && Step != 5)
2943 return false;
2944 if (PF > 0) // Can't have both folded and explicit stack allocation
2945 return false;
2946 if (Inst.Offset / 4 >= 0x3f4)
2947 return false;
2948 StackAdjust = Inst.Offset / 4;
2949 Step = 6;
2950 break;
2951 }
2952 }
2953 if (HasR11 && !HasChain) {
2954 if (IntRegs + 4 == 10) {
2955 // r11 stored, but not chaining; can be packed if already saving r4-r10
2956 // and we can fit r11 into this range.
2957 IntRegs++;
2958 HasR11 = false;
2959 } else
2960 return false;
2961 }
2962 if (HasChain && !HasLR)
2963 return false;
2964
2965 // Packed uneind info can't express multiple epilogues.
2966 if (info->EpilogMap.size() > 1)
2967 return false;
2968
2969 unsigned EF = 0;
2970 int Ret = 0;
2971 if (info->EpilogMap.size() == 0) {
2972 Ret = 3; // No epilogue
2973 } else {
2974 // As the prologue and epilogue aren't exact mirrors of each other,
2975 // we have to check the epilogue too and see if it matches what we've
2976 // concluded from the prologue.
2977 const WinEH::FrameInfo::Epilog &EpilogInfo =
2978 info->EpilogMap.begin()->second;
2979 if (EpilogInfo.Condition != 0xe) // ARMCC::AL
2980 return false;
2981 const std::vector<WinEH::Instruction> &Epilog = EpilogInfo.Instructions;
2982 std::optional<int64_t> MaybeDistance = GetOptionalAbsDifference(
2983 streamer, info->FuncletOrFuncEnd, info->EpilogMap.begin()->first);
2984 if (!MaybeDistance)
2985 return false;
2986 uint32_t DistanceFromEnd = (uint32_t)*MaybeDistance;
2987 uint32_t InstructionBytes = ARMCountOfInstructionBytes(Epilog);
2988 if (DistanceFromEnd != InstructionBytes)
2989 return false;
2990
2991 bool GotStackAdjust = false;
2992 bool GotFloatRegs = false;
2993 bool GotIntRegs = false;
2994 bool GotHomingRestore = false;
2995 bool GotLRRestore = false;
2996 bool NeedsReturn = false;
2997 bool GotReturn = false;
2998
2999 Step = 6;
3000 for (const WinEH::Instruction &Inst : Epilog) {
3001 switch (Inst.Operation) {
3002 default:
3003 llvm_unreachable("Unsupported ARM unwind code");
3012 case Win64EH::UOP_Nop:
3014 // Can't be packed in an epilogue
3015 return false;
3016
3019 if (Inst.Offset / 4 >= 0x3f4)
3020 return false;
3021 if (Step == 6) {
3022 if (Homing && FloatRegs < 0 && IntRegs < 0 && StackAdjust == 0 &&
3023 PF == 0 && Inst.Offset == 16) {
3024 GotHomingRestore = true;
3025 Step = 10;
3026 } else {
3027 if (StackAdjust > 0) {
3028 // Got stack adjust in prologue too; must match.
3029 if (StackAdjust != Inst.Offset / 4)
3030 return false;
3031 GotStackAdjust = true;
3032 } else if (PF == Inst.Offset / 4) {
3033 // Folded prologue, non-folded epilogue
3034 StackAdjust = Inst.Offset / 4;
3035 GotStackAdjust = true;
3036 } else {
3037 // StackAdjust == 0 in prologue, mismatch
3038 return false;
3039 }
3040 Step = 7;
3041 }
3042 } else if (Step == 7 || Step == 8 || Step == 9) {
3043 if (!Homing || Inst.Offset != 16)
3044 return false;
3045 GotHomingRestore = true;
3046 Step = 10;
3047 } else
3048 return false;
3049 break;
3050
3052 if (Step != 6 && Step != 7)
3053 return false;
3054 assert(Inst.Register >= 8 && Inst.Register <= 15);
3055 if (FloatRegs != (int)(Inst.Register - 8))
3056 return false;
3057 GotFloatRegs = true;
3058 Step = 8;
3059 break;
3060
3063 // push {r4-r11,lr}
3064 if (Step != 6 && Step != 7 && Step != 8)
3065 return false;
3066 assert(Inst.Register >= 4 && Inst.Register <= 11); // r4-rX
3067 assert(Inst.Offset <= 1); // Lr
3068 if (Homing && HasLR) {
3069 // If homing and LR is backed up, we can either restore LR here
3070 // and return with Ret == 1 or 2, or return with SaveLR below
3071 if (Inst.Offset) {
3072 GotLRRestore = true;
3073 NeedsReturn = true;
3074 } else {
3075 // Expecting a separate SaveLR below
3076 }
3077 } else {
3078 if (HasLR != (Inst.Offset == 1))
3079 return false;
3080 }
3081 GotLRRestore = Inst.Offset == 1;
3082 if (IntRegs < 0) // This opcode must include r4
3083 return false;
3084 int Expected = IntRegs;
3085 if (HasChain) {
3086 // Can't express r11 here unless IntRegs describe r4-r10
3087 if (IntRegs != 6)
3088 return false;
3089 Expected++;
3090 }
3091 if (Expected != (int)(Inst.Register - 4))
3092 return false;
3093 GotIntRegs = true;
3094 Step = 9;
3095 break;
3096 }
3097
3100 if (Step != 6 && Step != 7 && Step != 8)
3101 return false;
3102 // push {r4-r9,r11,lr}
3103 // push {r11,lr}
3104 // push {r1-r5}
3105 bool CurHasLR = false, CurHasR11 = false;
3106 int Regs;
3107 if (!parseRegMask(Inst.Register, CurHasLR, CurHasR11, EF, Regs))
3108 return false;
3109 if (EF > 0) {
3110 if (EF != PF && EF != StackAdjust)
3111 return false;
3112 }
3113 if (Homing && HasLR) {
3114 // If homing and LR is backed up, we can either restore LR here
3115 // and return with Ret == 1 or 2, or return with SaveLR below
3116 if (CurHasLR) {
3117 GotLRRestore = true;
3118 NeedsReturn = true;
3119 } else {
3120 // Expecting a separate SaveLR below
3121 }
3122 } else {
3123 if (CurHasLR != HasLR)
3124 return false;
3125 GotLRRestore = CurHasLR;
3126 }
3127 int Expected = IntRegs;
3128 if (HasChain) {
3129 // If we have chaining, the mask must have included r11.
3130 if (!CurHasR11)
3131 return false;
3132 } else if (Expected == 7) {
3133 // If we don't have chaining, the mask could still include r11,
3134 // expressed as part of IntRegs Instead.
3135 Expected--;
3136 if (!CurHasR11)
3137 return false;
3138 } else {
3139 // Neither HasChain nor r11 included in IntRegs, must not have r11
3140 // here either.
3141 if (CurHasR11)
3142 return false;
3143 }
3144 if (Expected != Regs)
3145 return false;
3146 GotIntRegs = true;
3147 Step = 9;
3148 break;
3149 }
3150
3152 if (Step != 6 && Step != 7 && Step != 8 && Step != 9)
3153 return false;
3154 if (!Homing || Inst.Offset != 20 || GotLRRestore)
3155 return false;
3156 GotLRRestore = true;
3157 GotHomingRestore = true;
3158 Step = 10;
3159 break;
3160
3163 GotReturn = true;
3164 Ret = (Inst.Operation == Win64EH::UOP_EndNop) ? 1 : 2;
3165 [[fallthrough]];
3166 case Win64EH::UOP_End:
3167 if (Step != 6 && Step != 7 && Step != 8 && Step != 9 && Step != 10)
3168 return false;
3169 Step = 11;
3170 break;
3171 }
3172 }
3173
3174 if (Step != 11)
3175 return false;
3176 if (StackAdjust > 0 && !GotStackAdjust && EF == 0)
3177 return false;
3178 if (FloatRegs >= 0 && !GotFloatRegs)
3179 return false;
3180 if (IntRegs >= 0 && !GotIntRegs)
3181 return false;
3182 if (Homing && !GotHomingRestore)
3183 return false;
3184 if (HasLR && !GotLRRestore)
3185 return false;
3186 if (NeedsReturn && !GotReturn)
3187 return false;
3188 }
3189
3190 assert(PF == 0 || EF == 0 ||
3191 StackAdjust == 0); // Can't have adjust in all three
3192 if (PF > 0 || EF > 0) {
3193 StackAdjust = PF > 0 ? (PF - 1) : (EF - 1);
3194 assert(StackAdjust <= 3);
3195 StackAdjust |= 0x3f0;
3196 if (PF > 0)
3197 StackAdjust |= 1 << 2;
3198 if (EF > 0)
3199 StackAdjust |= 1 << 3;
3200 }
3201
3202 assert(FuncLength <= 0x7FF && "FuncLength should have been checked earlier");
3203 int Flag = info->Fragment ? 0x02 : 0x01;
3204 int H = Homing ? 1 : 0;
3205 int L = HasLR ? 1 : 0;
3206 int C = HasChain ? 1 : 0;
3207 assert(IntRegs < 0 || FloatRegs < 0);
3208 unsigned Reg, R;
3209 if (IntRegs >= 0) {
3210 Reg = IntRegs;
3211 assert(Reg <= 7);
3212 R = 0;
3213 } else if (FloatRegs >= 0) {
3214 Reg = FloatRegs;
3215 assert(Reg < 7);
3216 R = 1;
3217 } else {
3218 // No int or float regs stored (except possibly R11,LR)
3219 Reg = 7;
3220 R = 1;
3221 }
3222 info->PackedInfo |= Flag << 0;
3223 info->PackedInfo |= (FuncLength & 0x7FF) << 2;
3224 info->PackedInfo |= (Ret & 0x3) << 13;
3225 info->PackedInfo |= H << 15;
3226 info->PackedInfo |= Reg << 16;
3227 info->PackedInfo |= R << 19;
3228 info->PackedInfo |= L << 20;
3229 info->PackedInfo |= C << 21;
3230 assert(StackAdjust <= 0x3ff);
3231 info->PackedInfo |= StackAdjust << 22;
3232 return true;
3233}
3234
3235// Populate the .xdata section. The format of .xdata on ARM is documented at
3236// https://docs.microsoft.com/en-us/cpp/build/arm-exception-handling
3238 bool TryPacked = true) {
3239 // If this UNWIND_INFO already has a symbol, it's already been emitted.
3240 if (info->Symbol)
3241 return;
3242 // If there's no unwind info here (not even a terminating UOP_End), the
3243 // unwind info is considered bogus and skipped. If this was done in
3244 // response to an explicit .seh_handlerdata, the associated trailing
3245 // handler data is left orphaned in the xdata section.
3246 if (info->empty()) {
3247 info->EmitAttempted = true;
3248 return;
3249 }
3250 if (info->EmitAttempted) {
3251 // If we tried to emit unwind info before (due to an explicit
3252 // .seh_handlerdata directive), but skipped it (because there was no
3253 // valid information to emit at the time), and it later got valid unwind
3254 // opcodes, we can't emit it here, because the trailing handler data
3255 // was already emitted elsewhere in the xdata section.
3256 streamer.getContext().reportError(
3257 SMLoc(), "Earlier .seh_handlerdata for " + info->Function->getName() +
3258 " skipped due to no unwind info at the time "
3259 "(.seh_handlerdata too early?), but the function later "
3260 "did get unwind info that can't be emitted");
3261 return;
3262 }
3263
3264 MCContext &context = streamer.getContext();
3265 MCSymbol *Label = context.createTempSymbol();
3266
3267 streamer.emitValueToAlignment(Align(4));
3268 streamer.emitLabel(Label);
3269 info->Symbol = Label;
3270
3271 if (!info->PrologEnd)
3272 streamer.getContext().reportError(SMLoc(), "Prologue in " +
3273 info->Function->getName() +
3274 " not correctly terminated");
3275
3276 if (info->PrologEnd && !info->Fragment)
3277 checkARMInstructions(streamer, info->Instructions, info->Begin,
3278 info->PrologEnd, info->Function->getName(),
3279 "prologue");
3280 for (auto &I : info->EpilogMap) {
3281 MCSymbol *EpilogStart = I.first;
3282 auto &Epilog = I.second;
3283 checkARMInstructions(streamer, Epilog.Instructions, EpilogStart, Epilog.End,
3284 info->Function->getName(), "epilogue");
3285 if (Epilog.Instructions.empty() ||
3286 !isARMTerminator(Epilog.Instructions.back()))
3287 streamer.getContext().reportError(
3288 SMLoc(), "Epilogue in " + info->Function->getName() +
3289 " not correctly terminated");
3290 }
3291
3292 std::optional<int64_t> RawFuncLength;
3293 const MCExpr *FuncLengthExpr = nullptr;
3294 if (!info->FuncletOrFuncEnd) {
3295 report_fatal_error("FuncletOrFuncEnd not set");
3296 } else {
3297 // As the size of many thumb2 instructions isn't known until later,
3298 // we can't always rely on being able to calculate the absolute
3299 // length of the function here. If we can't calculate it, defer it
3300 // to a relocation.
3301 //
3302 // In such a case, we won't know if the function is too long so that
3303 // the unwind info would need to be split (but this isn't implemented
3304 // anyway).
3305 RawFuncLength =
3306 GetOptionalAbsDifference(streamer, info->FuncletOrFuncEnd, info->Begin);
3307 if (!RawFuncLength)
3308 FuncLengthExpr =
3309 GetSubDivExpr(streamer, info->FuncletOrFuncEnd, info->Begin, 2);
3310 }
3311 uint32_t FuncLength = 0;
3312 if (RawFuncLength)
3313 FuncLength = (uint32_t)*RawFuncLength / 2;
3314 if (FuncLength > 0x3FFFF)
3315 report_fatal_error("SEH unwind data splitting not yet implemented");
3316 uint32_t PrologCodeBytes = ARMCountOfUnwindCodes(info->Instructions);
3317 uint32_t TotalCodeBytes = PrologCodeBytes;
3318
3319 if (!info->HandlesExceptions && RawFuncLength && FuncLength <= 0x7ff &&
3320 TryPacked) {
3321 // No exception handlers; check if the prolog and epilog matches the
3322 // patterns that can be described by the packed format. If we don't
3323 // know the exact function length yet, we can't do this.
3324
3325 // info->Symbol was already set even if we didn't actually write any
3326 // unwind info there. Keep using that as indicator that this unwind
3327 // info has been generated already.
3328
3329 if (tryARMPackedUnwind(streamer, info, FuncLength))
3330 return;
3331 }
3332
3333 int PackedEpilogOffset =
3334 checkARMPackedEpilog(streamer, info, PrologCodeBytes);
3335
3336 // Process epilogs.
3338 // Epilogs processed so far.
3339 std::vector<MCSymbol *> AddedEpilogs;
3340
3341 bool CanTweakProlog = true;
3342 for (auto &I : info->EpilogMap) {
3343 MCSymbol *EpilogStart = I.first;
3344 auto &EpilogInstrs = I.second.Instructions;
3345 uint32_t CodeBytes = ARMCountOfUnwindCodes(EpilogInstrs);
3346
3347 MCSymbol *MatchingEpilog =
3348 FindMatchingEpilog(EpilogInstrs, AddedEpilogs, info);
3349 int PrologOffset;
3350 if (MatchingEpilog) {
3351 assert(EpilogInfo.contains(MatchingEpilog) &&
3352 "Duplicate epilog not found");
3353 EpilogInfo[EpilogStart] = EpilogInfo.lookup(MatchingEpilog);
3354 // Clear the unwind codes in the EpilogMap, so that they don't get output
3355 // in the logic below.
3356 EpilogInstrs.clear();
3357 } else if ((PrologOffset = getARMOffsetInProlog(
3358 info->Instructions, EpilogInstrs, CanTweakProlog)) >= 0) {
3359 if (CanTweakProlog) {
3360 // Replace the regular end opcode of the prolog with the one from the
3361 // epilog.
3362 info->Instructions.front() = EpilogInstrs.back();
3363 // Later epilogs need a strict match for the end opcode.
3364 CanTweakProlog = false;
3365 }
3366 EpilogInfo[EpilogStart] = PrologOffset;
3367 // Clear the unwind codes in the EpilogMap, so that they don't get output
3368 // in the logic below.
3369 EpilogInstrs.clear();
3370 } else {
3371 EpilogInfo[EpilogStart] = TotalCodeBytes;
3372 TotalCodeBytes += CodeBytes;
3373 AddedEpilogs.push_back(EpilogStart);
3374 }
3375 }
3376
3377 // Code Words, Epilog count, F, E, X, Vers, Function Length
3378 uint32_t row1 = 0x0;
3379 uint32_t CodeWords = TotalCodeBytes / 4;
3380 uint32_t CodeWordsMod = TotalCodeBytes % 4;
3381 if (CodeWordsMod)
3382 CodeWords++;
3383 uint32_t EpilogCount =
3384 PackedEpilogOffset >= 0 ? PackedEpilogOffset : info->EpilogMap.size();
3385 bool ExtensionWord = EpilogCount > 31 || CodeWords > 15;
3386 if (!ExtensionWord) {
3387 row1 |= (EpilogCount & 0x1F) << 23;
3388 row1 |= (CodeWords & 0x0F) << 28;
3389 }
3390 if (info->HandlesExceptions) // X
3391 row1 |= 1 << 20;
3392 if (PackedEpilogOffset >= 0) // E
3393 row1 |= 1 << 21;
3394 if (info->Fragment) // F
3395 row1 |= 1 << 22;
3396 row1 |= FuncLength & 0x3FFFF;
3397 if (RawFuncLength)
3398 streamer.emitInt32(row1);
3399 else
3400 streamer.emitValue(
3401 MCBinaryExpr::createOr(FuncLengthExpr,
3402 MCConstantExpr::create(row1, context), context),
3403 4);
3404
3405 // Extended Code Words, Extended Epilog Count
3406 if (ExtensionWord) {
3407 // FIXME: We should be able to split unwind info into multiple sections.
3408 if (CodeWords > 0xFF || EpilogCount > 0xFFFF)
3409 report_fatal_error("SEH unwind data splitting not yet implemented");
3410 uint32_t row2 = 0x0;
3411 row2 |= (CodeWords & 0xFF) << 16;
3412 row2 |= (EpilogCount & 0xFFFF);
3413 streamer.emitInt32(row2);
3414 }
3415
3416 if (PackedEpilogOffset < 0) {
3417 // Epilog Start Index, Epilog Start Offset
3418 for (auto &I : EpilogInfo) {
3419 MCSymbol *EpilogStart = I.first;
3420 uint32_t EpilogIndex = I.second;
3421
3422 std::optional<int64_t> MaybeEpilogOffset =
3423 GetOptionalAbsDifference(streamer, EpilogStart, info->Begin);
3424 const MCExpr *OffsetExpr = nullptr;
3425 uint32_t EpilogOffset = 0;
3426 if (MaybeEpilogOffset)
3427 EpilogOffset = *MaybeEpilogOffset / 2;
3428 else
3429 OffsetExpr = GetSubDivExpr(streamer, EpilogStart, info->Begin, 2);
3430
3431 assert(info->EpilogMap.contains(EpilogStart));
3432 unsigned Condition = info->EpilogMap[EpilogStart].Condition;
3433 assert(Condition <= 0xf);
3434
3435 uint32_t row3 = EpilogOffset;
3436 row3 |= Condition << 20;
3437 row3 |= (EpilogIndex & 0x3FF) << 24;
3438 if (MaybeEpilogOffset)
3439 streamer.emitInt32(row3);
3440 else
3441 streamer.emitValue(
3443 OffsetExpr, MCConstantExpr::create(row3, context), context),
3444 4);
3445 }
3446 }
3447
3448 // Emit prolog unwind instructions (in reverse order).
3449 uint8_t numInst = info->Instructions.size();
3450 for (uint8_t c = 0; c < numInst; ++c) {
3451 WinEH::Instruction inst = info->Instructions.back();
3452 info->Instructions.pop_back();
3453 ARMEmitUnwindCode(streamer, inst);
3454 }
3455
3456 // Emit epilog unwind instructions
3457 for (auto &I : info->EpilogMap) {
3458 auto &EpilogInstrs = I.second.Instructions;
3459 for (const WinEH::Instruction &inst : EpilogInstrs)
3460 ARMEmitUnwindCode(streamer, inst);
3461 }
3462
3463 int32_t BytesMod = CodeWords * 4 - TotalCodeBytes;
3464 assert(BytesMod >= 0);
3465 for (int i = 0; i < BytesMod; i++)
3466 streamer.emitInt8(0xFB);
3467
3468 if (info->HandlesExceptions)
3469 streamer.emitValue(
3470 MCSymbolRefExpr::create(info->ExceptionHandler,
3472 4);
3473}
3474
3476 const WinEH::FrameInfo *info) {
3477 MCContext &context = streamer.getContext();
3478
3479 streamer.emitValueToAlignment(Align(4));
3480 for (const auto &S : info->Segments) {
3481 EmitSymbolRefWithOfs(streamer, info->Begin, S.Offset);
3482 if (info->PackedInfo)
3483 streamer.emitInt32(info->PackedInfo);
3484 else
3485 streamer.emitValue(
3487 context),
3488 4);
3489 }
3490}
3491
3492
3494 const WinEH::FrameInfo *info) {
3495 MCContext &context = streamer.getContext();
3496
3497 streamer.emitValueToAlignment(Align(4));
3498 EmitSymbolRefWithOfs(streamer, info->Begin, info->Begin);
3499 if (info->PackedInfo)
3500 streamer.emitInt32(info->PackedInfo);
3501 else
3502 streamer.emitValue(
3504 context),
3505 4);
3506}
3507
3509 // Emit the unwind info structs first.
3510 for (const auto &CFI : Streamer.getWinFrameInfos()) {
3511 WinEH::FrameInfo *Info = CFI.get();
3512 if (Info->empty())
3513 continue;
3514 MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection);
3515 Streamer.switchSection(XData);
3517 }
3518
3519 // Now emit RUNTIME_FUNCTION entries.
3520 for (const auto &CFI : Streamer.getWinFrameInfos()) {
3521 WinEH::FrameInfo *Info = CFI.get();
3522 // ARM64EmitUnwindInfo above clears the info struct, so we can't check
3523 // empty here. But if a Symbol is set, we should create the corresponding
3524 // pdata entry.
3525 if (!Info->Symbol)
3526 continue;
3527 MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection);
3528 Streamer.switchSection(PData);
3530 }
3531}
3532
3535 bool HandlerData) const {
3536 // Called if there's an .seh_handlerdata directive before the end of the
3537 // function. This forces writing the xdata record already here - and
3538 // in this case, the function isn't actually ended already, but the xdata
3539 // record needs to know the function length. In these cases, if the funclet
3540 // end hasn't been marked yet, the xdata function length won't cover the
3541 // whole function, only up to this point.
3542 if (!info->FuncletOrFuncEnd) {
3543 Streamer.switchSection(info->TextSection);
3544 info->FuncletOrFuncEnd = Streamer.emitCFILabel();
3545 }
3546 // Switch sections (the static function above is meant to be called from
3547 // here and from Emit().
3548 MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection);
3549 Streamer.switchSection(XData);
3550 ARM64EmitUnwindInfo(Streamer, info, /* TryPacked = */ !HandlerData);
3551}
3552
3554 // Emit the unwind info structs first.
3555 for (const auto &CFI : Streamer.getWinFrameInfos()) {
3556 WinEH::FrameInfo *Info = CFI.get();
3557 if (Info->empty())
3558 continue;
3559 MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection);
3560 Streamer.switchSection(XData);
3562 }
3563
3564 // Now emit RUNTIME_FUNCTION entries.
3565 for (const auto &CFI : Streamer.getWinFrameInfos()) {
3566 WinEH::FrameInfo *Info = CFI.get();
3567 // ARMEmitUnwindInfo above clears the info struct, so we can't check
3568 // empty here. But if a Symbol is set, we should create the corresponding
3569 // pdata entry.
3570 if (!Info->Symbol)
3571 continue;
3572 MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection);
3573 Streamer.switchSection(PData);
3575 }
3576}
3577
3580 bool HandlerData) const {
3581 // Called if there's an .seh_handlerdata directive before the end of the
3582 // function. This forces writing the xdata record already here - and
3583 // in this case, the function isn't actually ended already, but the xdata
3584 // record needs to know the function length. In these cases, if the funclet
3585 // end hasn't been marked yet, the xdata function length won't cover the
3586 // whole function, only up to this point.
3587 if (!info->FuncletOrFuncEnd) {
3588 Streamer.switchSection(info->TextSection);
3589 info->FuncletOrFuncEnd = Streamer.emitCFILabel();
3590 }
3591 // Switch sections (the static function above is meant to be called from
3592 // here and from Emit().
3593 MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection);
3594 Streamer.switchSection(XData);
3595 ARMEmitUnwindInfo(Streamer, info, /* TryPacked = */ !HandlerData);
3596}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
@ Scaled
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
lazy value info
static void ARM64EmitUnwindInfoForSegment(MCStreamer &streamer, WinEH::FrameInfo *info, WinEH::FrameInfo::Segment &Seg, bool TryPacked=true)
static uint32_t ARMCountOfUnwindCodes(ArrayRef< WinEH::Instruction > Insns)
static uint32_t ARM64CountOfUnwindCodes(ArrayRef< WinEH::Instruction > Insns)
static void checkARMInstructions(MCStreamer &Streamer, ArrayRef< WinEH::Instruction > Insns, const MCSymbol *Begin, const MCSymbol *End, StringRef Name, StringRef Type)
static bool isARMTerminator(const WinEH::Instruction &inst)
static void ARM64EmitUnwindCode(MCStreamer &streamer, const WinEH::Instruction &inst)
static void ARM64ProcessEpilogs(WinEH::FrameInfo *info, WinEH::FrameInfo::Segment *Seg, ArrayRef< WinEH::Instruction > Prolog, uint32_t &TotalCodeBytes, MapVector< MCSymbol *, uint32_t > &EpilogInfo)
static void simplifyARM64Opcodes(std::vector< WinEH::Instruction > &Instructions, bool Reverse)
static void ARMEmitUnwindCode(MCStreamer &streamer, const WinEH::Instruction &inst)
static bool EpilogIpOffsetsMatch(const WinEH::FrameInfo::Epilog &A, const WinEH::FrameInfo::Epilog &B, const MCAssembler &Asm)
Compare the relative IP offset arrays of two epilogs.
static std::optional< int64_t > GetOptionalAbsDifference(const MCAssembler &Assembler, const MCSymbol *LHS, const MCSymbol *RHS)
static void checkARM64Instructions(MCStreamer &Streamer, ArrayRef< WinEH::Instruction > Insns, const MCSymbol *Begin, const MCSymbol *End, StringRef Name, bool IsPrologue)
static int checkARM64PackedEpilog(MCStreamer &streamer, WinEH::FrameInfo *info, WinEH::FrameInfo::Segment *Seg, ArrayRef< WinEH::Instruction > Prolog, int PrologCodeBytes)
static void ARMEmitRuntimeFunction(MCStreamer &streamer, const WinEH::FrameInfo *info)
static bool tryARM64PackedUnwind(WinEH::FrameInfo *info, uint32_t FuncLength, int PackedEpilogOffset)
static void EmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info)
static void EmitUnwindCode(MCStreamer &streamer, const MCSymbol *begin, WinEH::Instruction &inst)
static void ARM64EmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info, bool TryPacked=true)
static int getARMOffsetInProlog(const std::vector< WinEH::Instruction > &Prolog, const std::vector< WinEH::Instruction > &Epilog, bool CanTweakProlog)
static void ARM64EmitRuntimeFunction(MCStreamer &streamer, const WinEH::FrameInfo *info)
static void EmitSymbolRefWithOfs(MCStreamer &streamer, const MCSymbol *Base, int64_t Offset)
static bool parseRegMask(unsigned Mask, bool &HasLR, bool &HasR11, unsigned &Folded, int &IntRegs)
static int checkARMPackedEpilog(MCStreamer &streamer, WinEH::FrameInfo *info, int PrologCodeBytes)
static void EmitAbsDifference16(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS)
Emit a 16-bit (2-byte LE) label difference.
static int64_t GetAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS)
static void ARM64FindSegmentsInFunction(MCStreamer &streamer, WinEH::FrameInfo *info, int64_t RawFuncLength)
static bool tryARMPackedUnwind(MCStreamer &streamer, WinEH::FrameInfo *info, uint32_t FuncLength)
static void EmitUnwindInfoV3(MCStreamer &Streamer, WinEH::FrameInfo *Info)
Emit V3 UNWIND_INFO for a single frame.
static MCSymbol * FindMatchingEpilog(const std::vector< WinEH::Instruction > &EpilogInstrs, const std::vector< MCSymbol * > &Epilogs, const WinEH::FrameInfo *info)
static void EmitRuntimeFunction(MCStreamer &streamer, const WinEH::FrameInfo *info)
static const MCExpr * GetSubDivExpr(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS, int Div)
static void EmitAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS)
static void ARMEmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info, bool TryPacked=true)
static uint32_t ARMCountOfInstructionBytes(ArrayRef< WinEH::Instruction > Insns, bool *HasCustom=nullptr)
static uint32_t ARM64CountOfInstructions(ArrayRef< WinEH::Instruction > Insns, bool IsPrologue)
static std::optional< uint16_t > FindInPool(ArrayRef< uint8_t > Haystack, ArrayRef< uint8_t > Needle)
Try to find Needle as a contiguous subsequence within Haystack.
static int getARM64OffsetInProlog(ArrayRef< WinEH::Instruction > Prolog, ArrayRef< WinEH::Instruction > Epilog)
static uint8_t CountOfUnwindCodes(std::vector< WinEH::Instruction > &Insns)
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
Register Reg
static void printImpl(const MCAsmInfo &MAI, raw_ostream &OS, const MCSpecifierExpr &Expr)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static const MCPhysReg IntRegs[32]
std::unique_ptr< MCStreamer > && Streamer
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Tagged union holding either a T or a Error.
Definition Error.h:485
MCContext & getContext() const
static const MCBinaryExpr * createLShr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:422
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:342
static const MCBinaryExpr * createOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:407
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:352
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:427
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:83
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
LLVM_ABI void reportError(SMLoc L, const Twine &Msg)
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
Streaming object file generation interface.
MCAssembler & getAssembler()
void appendContents(ArrayRef< char > Contents)
void addFixup(const MCExpr *Value, MCFixupKind Kind)
void ensureHeadroom(size_t Headroom)
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:580
Streaming machine code generation interface.
Definition MCStreamer.h:222
MCContext & getContext() const
Definition MCStreamer.h:326
void emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc())
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
virtual void emitValueToAlignment(Align Alignment, int64_t Fill=0, uint8_t FillLen=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
void emitInt16(uint64_t Value)
Definition MCStreamer.h:768
void emitInt32(uint64_t Value)
Definition MCStreamer.h:769
void emitInt8(uint64_t Value)
Definition MCStreamer.h:767
Represent a reference to a symbol from inside an expression.
Definition MCExpr.h:190
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition MCSymbol.cpp:59
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
MCFragment * getFragment() const
Definition MCSymbol.h:345
static MCValue get(const MCSymbol *SymA, const MCSymbol *SymB=nullptr, int64_t Val=0, uint32_t Specifier=0)
Definition MCValue.h:56
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
Represents a location in source code.
Definition SMLoc.h:22
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
void EmitUnwindInfo(MCStreamer &Streamer, WinEH::FrameInfo *FI, bool HandlerData) const override
void Emit(MCStreamer &Streamer) const override
This emits the unwind info sections (.pdata and .xdata in PE/COFF).
void Emit(MCStreamer &Streamer) const override
This emits the unwind info sections (.pdata and .xdata in PE/COFF).
void EmitUnwindInfo(MCStreamer &Streamer, WinEH::FrameInfo *FI, bool HandlerData) const override
void Emit(MCStreamer &Streamer) const override
This emits the unwind info sections (.pdata and .xdata in PE/COFF).
void EmitUnwindInfo(MCStreamer &Streamer, WinEH::FrameInfo *FI, bool HandlerData) const override
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ EPILOG_INFO_LARGE
When set, the extended descriptor uses EPILOG_INFO_LARGE_EX_V3 (16-bit IpOffsetOfLastInstruction) and...
Definition Win64EH.h:262
@ UNW_TerminateHandler
UNW_TerminateHandler - Specifies that this function has a termination handler.
Definition Win64EH.h:152
@ UNW_FlagLarge
UNW_FlagLarge - V3 only.
Definition Win64EH.h:159
@ UNW_ExceptionHandler
UNW_ExceptionHandler - Specifies that this function has an exception handler.
Definition Win64EH.h:149
@ UNW_ChainInfo
UNW_ChainInfo - Specifies that this UnwindInfo structure is chained to another one.
Definition Win64EH.h:155
UnwindOpcodes
UnwindOpcodes - Enumeration whose values specify a single operation in the prolog of a function.
Definition Win64EH.h:30
@ UOP_SaveAnyRegDPX
Definition Win64EH.h:80
@ UOP_SaveRegsR4R7LR
Definition Win64EH.h:103
@ UOP_ClearUnwoundToCall
Definition Win64EH.h:69
@ UOP_SaveNonVolBig
Definition Win64EH.h:39
@ UOP_WideAllocMedium
Definition Win64EH.h:97
@ UOP_SaveAnyRegDX
Definition Win64EH.h:79
@ UOP_SaveFRegD0D15
Definition Win64EH.h:108
@ UOP_SaveAnyRegQP
Definition Win64EH.h:76
@ UOP_SaveAnyRegD
Definition Win64EH.h:73
@ UOP_WideSaveRegsR4R11LR
Definition Win64EH.h:104
@ UOP_SaveAnyRegIPX
Definition Win64EH.h:78
@ UOP_WideAllocHuge
Definition Win64EH.h:99
@ UOP_SaveAnyRegQX
Definition Win64EH.h:81
@ UOP_SaveAnyRegIX
Definition Win64EH.h:77
@ UOP_SaveXMM128Big
Definition Win64EH.h:43
@ UOP_SaveAnyRegQ
Definition Win64EH.h:75
@ UOP_SaveAnyRegDP
Definition Win64EH.h:74
@ UOP_SaveFRegD8D15
Definition Win64EH.h:105
@ UOP_PushMachFrame
Definition Win64EH.h:44
@ UOP_SaveR19R20X
Definition Win64EH.h:48
@ UOP_SaveAnyRegQPX
Definition Win64EH.h:82
@ UOP_WideAllocLarge
Definition Win64EH.h:98
@ UOP_WideSaveRegMask
Definition Win64EH.h:101
@ UOP_AllocMedium
Definition Win64EH.h:47
@ UOP_SaveAnyRegIP
Definition Win64EH.h:72
@ UOP_SaveFRegD16D31
Definition Win64EH.h:109
@ UOP_SaveAnyRegI
Definition Win64EH.h:71
@ WOD_SAVE_XMM128_FAR
Definition Win64EH.h:252
@ WOD_PUSH_CANONICAL_FRAME
Definition Win64EH.h:246
@ WOD_PUSH_CONSECUTIVE_2
Definition Win64EH.h:250
@ WOD_SAVE_NONVOL_FAR
Definition Win64EH.h:248
LLVM_ABI void EncodeWOD(const WinEH::Instruction &Inst, SmallVectorImpl< uint8_t > &Out)
Encode a single WinEH::Instruction as V3 WOD bytes.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
auto reverse_conditionally(ContainerTy &&C, bool ShouldReverse)
Return a range that conditionally reverses C.
Definition STLExtras.h:1439
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ FK_Data_1
A one-byte fixup.
Definition MCFixup.h:38
@ FK_Data_2
A two-byte fixup.
Definition MCFixup.h:39
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
MapVector< MCSymbol *, int64_t > Epilogs
Definition MCWinEH.h:86
const MCSymbol * Function
Definition MCWinEH.h:51
const MCSymbol * End
Definition MCWinEH.h:48
const MCSymbol * Label
Definition MCWinEH.h:24