1//===-- X86AsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly --------===//
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// This file contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to X86 machine code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86AsmPrinter.h"
15#include "MCTargetDesc/X86ATTInstPrinter.h"
16#include "MCTargetDesc/X86BaseInfo.h"
17#include "MCTargetDesc/X86MCTargetDesc.h"
18#include "MCTargetDesc/X86TargetStreamer.h"
19#include "TargetInfo/X86TargetInfo.h"
20#include "X86.h"
21#include "X86InstrInfo.h"
22#include "X86MachineFunctionInfo.h"
23#include "X86Subtarget.h"
24#include "llvm-c/Visibility.h"
25#include "llvm/Analysis/StaticDataProfileInfo.h"
26#include "llvm/BinaryFormat/COFF.h"
27#include "llvm/BinaryFormat/ELF.h"
28#include "llvm/CodeGen/AsmPrinterAnalysis.h"
29#include "llvm/CodeGen/MachineConstantPool.h"
30#include "llvm/CodeGen/MachineModuleInfoImpls.h"
31#include "llvm/CodeGen/MachinePassManager.h"
32#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
33#include "llvm/CodeGenTypes/MachineValueType.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/InlineAsm.h"
36#include "llvm/IR/InstIterator.h"
37#include "llvm/IR/Mangler.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/Type.h"
40#include "llvm/MC/MCAsmInfo.h"
41#include "llvm/MC/MCCodeEmitter.h"
42#include "llvm/MC/MCContext.h"
43#include "llvm/MC/MCExpr.h"
44#include "llvm/MC/MCInst.h"
45#include "llvm/MC/MCInstBuilder.h"
46#include "llvm/MC/MCSectionCOFF.h"
47#include "llvm/MC/MCSectionELF.h"
48#include "llvm/MC/MCSectionMachO.h"
49#include "llvm/MC/MCStreamer.h"
50#include "llvm/MC/MCSymbol.h"
51#include "llvm/MC/TargetRegistry.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Target/TargetMachine.h"
55
56using namespace llvm;
57
58X86AsmPrinter::X86AsmPrinter(TargetMachine &TM,
59 std::unique_ptr<MCStreamer> Streamer)
60 : AsmPrinter(TM, std::move(Streamer), ID), FM(*this) {
61 GetPSI = [this](Module &M) -> ProfileSummaryInfo * {
62 if (auto *PSIW = getAnalysisIfAvailable<ProfileSummaryInfoWrapperPass>())
63 return &PSIW->getPSI();
64 return nullptr;
65 };
66 GetSDPI = [this](Module &M) -> StaticDataProfileInfo * {
67 if (auto *SDPIW =
68 getAnalysisIfAvailable<StaticDataProfileInfoWrapperPass>())
69 return &SDPIW->getStaticDataProfileInfo();
70 return nullptr;
71 };
72}
73
74//===----------------------------------------------------------------------===//
75// Primitive Helper Functions.
76//===----------------------------------------------------------------------===//
77
78/// runOnMachineFunction - Emit the function body.
79///
80bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
81 PSI = GetPSI(*MF.getFunction().getParent());
82 SDPI = GetSDPI(*MF.getFunction().getParent());
83
84 Subtarget = &MF.getSubtarget<X86Subtarget>();
85
86 SMShadowTracker.startFunction(MF);
87 CodeEmitter.reset(p: TM.getTarget().createMCCodeEmitter(
88 II: *Subtarget->getInstrInfo(), Ctx&: MF.getContext()));
89
90 const Module *M = MF.getFunction().getParent();
91 EmitFPOData = Subtarget->isTargetWin32() && M->getCodeViewFlag();
92
93 IndCSPrefix = M->getModuleFlag(Key: "indirect_branch_cs_prefix");
94
95 SetupMachineFunction(MF);
96
97 if (Subtarget->isTargetCOFF()) {
98 bool Local = MF.getFunction().hasLocalLinkage();
99 OutStreamer->beginCOFFSymbolDef(Symbol: CurrentFnSym);
100 OutStreamer->emitCOFFSymbolStorageClass(
101 StorageClass: Local ? COFF::IMAGE_SYM_CLASS_STATIC : COFF::IMAGE_SYM_CLASS_EXTERNAL);
102 OutStreamer->emitCOFFSymbolType(Type: COFF::IMAGE_SYM_DTYPE_FUNCTION
103 << COFF::SCT_COMPLEX_TYPE_SHIFT);
104 OutStreamer->endCOFFSymbolDef();
105 }
106
107 // Emit the rest of the function body.
108 emitFunctionBody();
109
110 // Emit the XRay table for this function.
111 emitXRayTable();
112
113 EmitFPOData = false;
114
115 IndCSPrefix = false;
116
117 // We didn't modify anything.
118 return false;
119}
120
121void X86AsmPrinter::emitFunctionBodyStart() {
122 if (EmitFPOData) {
123 auto *XTS =
124 static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
125 XTS->emitFPOProc(
126 ProcSym: CurrentFnSym,
127 ParamsSize: MF->getInfo<X86MachineFunctionInfo>()->getArgumentStackSize());
128 }
129}
130
131void X86AsmPrinter::emitFunctionBodyEnd() {
132 if (EmitFPOData) {
133 auto *XTS =
134 static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
135 XTS->emitFPOEndProc();
136 }
137}
138
139uint32_t X86AsmPrinter::MaskKCFIType(uint32_t Value) {
140 // If the type hash matches an invalid pattern, mask the value.
141 const uint32_t InvalidValues[] = {
142 0xFA1E0FF3, /* ENDBR64 */
143 0xFB1E0FF3, /* ENDBR32 */
144 };
145 for (uint32_t N : InvalidValues) {
146 // LowerKCFI_CHECK emits -Value for indirect call checks, so we must also
147 // mask that. Note that -(Value + 1) == ~Value.
148 if (N == Value || -N == Value)
149 return Value + 1;
150 }
151 return Value;
152}
153
154void X86AsmPrinter::EmitKCFITypePadding(const MachineFunction &MF,
155 bool HasType) {
156 // Keep the function entry aligned, taking patchable-function-prefix into
157 // account if set.
158 int64_t PrefixBytes = MF.getFunction().getFnAttributeAsParsedInteger(
159 Kind: "patchable-function-prefix");
160
161 // Also take the type identifier into account if we're emitting
162 // one. Otherwise, just pad with nops. The X86::MOV32ri instruction emitted
163 // in X86AsmPrinter::emitKCFITypeId is 5 bytes long.
164 if (HasType)
165 PrefixBytes += 5;
166
167 emitNops(N: offsetToAlignment(Value: PrefixBytes, Alignment: MF.getPreferredAlignment()));
168}
169
170/// emitKCFITypeId - Emit the KCFI type information in architecture specific
171/// format.
172void X86AsmPrinter::emitKCFITypeId(const MachineFunction &MF) {
173 const Function &F = MF.getFunction();
174 if (!F.getParent()->getModuleFlag(Key: "kcfi"))
175 return;
176
177 ConstantInt *Type = nullptr;
178 if (const MDNode *MD = F.getMetadata(KindID: LLVMContext::MD_kcfi_type))
179 Type = mdconst::extract<ConstantInt>(MD: MD->getOperand(I: 0));
180
181 // If we don't have a type to emit, just emit padding if needed to maintain
182 // the same alignment for all functions.
183 if (!Type) {
184 EmitKCFITypePadding(MF, /*HasType=*/false);
185 return;
186 }
187
188 // Emit a function symbol for the type data to avoid unreachable instruction
189 // warnings from binary validation tools, and use the same linkage and
190 // visibility as the parent function. Note that using local linkage would
191 // result in duplicate symbols for weak parent functions.
192 MCSymbol *FnSym = OutContext.getOrCreateSymbol(Name: "__cfi_" + MF.getName());
193 emitLinkage(GV: &MF.getFunction(), GVSym: FnSym);
194 emitVisibility(Sym: FnSym, Visibility: F.getVisibility());
195 if (MAI.hasDotTypeDotSizeDirective())
196 OutStreamer->emitSymbolAttribute(Symbol: FnSym, Attribute: MCSA_ELF_TypeFunction);
197 OutStreamer->emitLabel(Symbol: FnSym);
198
199 // Embed the type hash in the X86::MOV32ri instruction to avoid special
200 // casing object file parsers.
201 EmitKCFITypePadding(MF);
202 unsigned DestReg = X86::EAX;
203
204 const Module *M = F.getParent();
205 if (M->getModuleFlag(Key: "kcfi-arity")) {
206 // The ArityToRegMap assumes the 64-bit SysV ABI.
207 [[maybe_unused]] const auto &Triple = M->getTargetTriple();
208 assert(Triple.isX86_64() && !Triple.isOSWindows());
209
210 // Determine the function's arity (i.e., the number of arguments) at the ABI
211 // level by counting the number of parameters that are passed
212 // as registers, such as pointers and 64-bit (or smaller) integers. The
213 // Linux x86-64 ABI allows up to 6 integer parameters to be passed in GPRs.
214 // Additional parameters or parameters larger than 64 bits may be passed on
215 // the stack, in which case the arity is denoted as 7. Floating-point
216 // arguments passed in XMM0-XMM7 are not counted toward arity because
217 // floating-point values are not relevant to enforcing kCFI at this time.
218 const unsigned ArityToRegMap[8] = {X86::EAX, X86::ECX, X86::EDX, X86::EBX,
219 X86::ESP, X86::EBP, X86::ESI, X86::EDI};
220 int Arity;
221 if (MF.getInfo<X86MachineFunctionInfo>()->getArgumentStackSize() > 0) {
222 Arity = 7;
223 } else {
224 Arity = 0;
225 for (const auto &LI : MF.getRegInfo().liveins()) {
226 auto Reg = LI.first;
227 if (X86::GR8RegClass.contains(Reg) || X86::GR16RegClass.contains(Reg) ||
228 X86::GR32RegClass.contains(Reg) ||
229 X86::GR64RegClass.contains(Reg)) {
230 ++Arity;
231 }
232 }
233 }
234 DestReg = ArityToRegMap[Arity];
235 }
236
237 EmitAndCountInstruction(Inst&: MCInstBuilder(X86::MOV32ri)
238 .addReg(Reg: DestReg)
239 .addImm(Val: MaskKCFIType(Value: Type->getZExtValue())));
240
241 if (MAI.hasDotTypeDotSizeDirective()) {
242 MCSymbol *EndSym = OutContext.createTempSymbol(Name: "cfi_func_end");
243 OutStreamer->emitLabel(Symbol: EndSym);
244
245 const MCExpr *SizeExp = MCBinaryExpr::createSub(
246 LHS: MCSymbolRefExpr::create(Symbol: EndSym, Ctx&: OutContext),
247 RHS: MCSymbolRefExpr::create(Symbol: FnSym, Ctx&: OutContext), Ctx&: OutContext);
248 OutStreamer->emitELFSize(Symbol: FnSym, Value: SizeExp);
249 }
250}
251
252/// PrintSymbolOperand - Print a raw symbol reference operand. This handles
253/// jump tables, constant pools, global address and external symbols, all of
254/// which print to a label with various suffixes for relocation types etc.
255void X86AsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
256 raw_ostream &O) {
257 switch (MO.getType()) {
258 default: llvm_unreachable("unknown symbol type!");
259 case MachineOperand::MO_ConstantPoolIndex:
260 GetCPISymbol(CPID: MO.getIndex())->print(OS&: O, MAI);
261 printOffset(Offset: MO.getOffset(), OS&: O);
262 break;
263 case MachineOperand::MO_GlobalAddress: {
264 const GlobalValue *GV = MO.getGlobal();
265
266 MCSymbol *GVSym;
267 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
268 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
269 GVSym = getSymbolWithGlobalValueBase(GV, Suffix: "$non_lazy_ptr");
270 else
271 GVSym = getSymbolPreferLocal(GV: *GV);
272
273 // Handle dllimport linkage.
274 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
275 GVSym = OutContext.getOrCreateSymbol(Name: Twine("__imp_") + GVSym->getName());
276 else if (MO.getTargetFlags() == X86II::MO_COFFSTUB)
277 GVSym =
278 OutContext.getOrCreateSymbol(Name: Twine(".refptr.") + GVSym->getName());
279
280 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
281 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
282 MCSymbol *Sym = getSymbolWithGlobalValueBase(GV, Suffix: "$non_lazy_ptr");
283 MachineModuleInfoImpl::StubValueTy &StubSym =
284 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
285 if (!StubSym.getPointer())
286 StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
287 !GV->hasInternalLinkage());
288 }
289
290 // If the name begins with a dollar-sign, enclose it in parens. We do this
291 // to avoid having it look like an integer immediate to the assembler.
292 if (GVSym->getName()[0] != '$')
293 GVSym->print(OS&: O, MAI);
294 else {
295 O << '(';
296 GVSym->print(OS&: O, MAI);
297 O << ')';
298 }
299 printOffset(Offset: MO.getOffset(), OS&: O);
300 break;
301 }
302 }
303
304 switch (MO.getTargetFlags()) {
305 default:
306 llvm_unreachable("Unknown target flag on GV operand");
307 case X86II::MO_NO_FLAG: // No flag.
308 break;
309 case X86II::MO_DARWIN_NONLAZY:
310 case X86II::MO_DLLIMPORT:
311 case X86II::MO_COFFSTUB:
312 // These affect the name of the symbol, not any suffix.
313 break;
314 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
315 O << " + [.-";
316 MF->getPICBaseSymbol()->print(OS&: O, MAI);
317 O << ']';
318 break;
319 case X86II::MO_PIC_BASE_OFFSET:
320 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
321 O << '-';
322 MF->getPICBaseSymbol()->print(OS&: O, MAI);
323 break;
324 case X86II::MO_TLSGD: O << "@TLSGD"; break;
325 case X86II::MO_TLSLD: O << "@TLSLD"; break;
326 case X86II::MO_TLSLDM: O << "@TLSLDM"; break;
327 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
328 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
329 case X86II::MO_TPOFF: O << "@TPOFF"; break;
330 case X86II::MO_DTPOFF: O << "@DTPOFF"; break;
331 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
332 case X86II::MO_GOTNTPOFF: O << "@GOTNTPOFF"; break;
333 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
334 case X86II::MO_GOTPCREL_NORELAX: O << "@GOTPCREL_NORELAX"; break;
335 case X86II::MO_GOT: O << "@GOT"; break;
336 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
337 case X86II::MO_PLT: O << "@PLT"; break;
338 case X86II::MO_TLVP: O << "@TLVP"; break;
339 case X86II::MO_TLVP_PIC_BASE:
340 O << "@TLVP" << '-';
341 MF->getPICBaseSymbol()->print(OS&: O, MAI);
342 break;
343 case X86II::MO_SECREL: O << "@SECREL32"; break;
344 }
345}
346
347void X86AsmPrinter::PrintOperand(const MachineInstr *MI, unsigned OpNo,
348 raw_ostream &O) {
349 const MachineOperand &MO = MI->getOperand(i: OpNo);
350 const bool IsATT = MI->getInlineAsmDialect() == InlineAsm::AD_ATT;
351 switch (MO.getType()) {
352 default: llvm_unreachable("unknown operand type!");
353 case MachineOperand::MO_Register: {
354 if (IsATT)
355 O << '%';
356 O << X86ATTInstPrinter::getRegisterName(Reg: MO.getReg());
357 return;
358 }
359
360 case MachineOperand::MO_Immediate:
361 if (IsATT)
362 O << '$';
363 O << MO.getImm();
364 return;
365
366 case MachineOperand::MO_ConstantPoolIndex:
367 case MachineOperand::MO_GlobalAddress: {
368 switch (MI->getInlineAsmDialect()) {
369 case InlineAsm::AD_ATT:
370 O << '$';
371 break;
372 case InlineAsm::AD_Intel:
373 O << "offset ";
374 break;
375 }
376 PrintSymbolOperand(MO, O);
377 break;
378 }
379 case MachineOperand::MO_BlockAddress: {
380 MCSymbol *Sym = GetBlockAddressSymbol(BA: MO.getBlockAddress());
381 Sym->print(OS&: O, MAI);
382 break;
383 }
384 }
385}
386
387/// PrintModifiedOperand - Print subregisters based on supplied modifier,
388/// deferring to PrintOperand() if no modifier was supplied or if operand is not
389/// a register.
390void X86AsmPrinter::PrintModifiedOperand(const MachineInstr *MI, unsigned OpNo,
391 raw_ostream &O, StringRef Modifier) {
392 const MachineOperand &MO = MI->getOperand(i: OpNo);
393 if (Modifier.empty() || !MO.isReg())
394 return PrintOperand(MI, OpNo, O);
395 if (MI->getInlineAsmDialect() == InlineAsm::AD_ATT)
396 O << '%';
397 Register Reg = MO.getReg();
398 if (Modifier.consume_front(Prefix: "subreg")) {
399 unsigned Size = (Modifier == "64") ? 64
400 : (Modifier == "32") ? 32
401 : (Modifier == "16") ? 16
402 : 8;
403 Reg = getX86SubSuperRegister(Reg, Size);
404 }
405 O << X86ATTInstPrinter::getRegisterName(Reg);
406}
407
408/// PrintPCRelImm - This is used to print an immediate value that ends up
409/// being encoded as a pc-relative value. These print slightly differently, for
410/// example, a $ is not emitted.
411void X86AsmPrinter::PrintPCRelImm(const MachineInstr *MI, unsigned OpNo,
412 raw_ostream &O) {
413 const MachineOperand &MO = MI->getOperand(i: OpNo);
414 switch (MO.getType()) {
415 default: llvm_unreachable("Unknown pcrel immediate operand");
416 case MachineOperand::MO_Register:
417 // pc-relativeness was handled when computing the value in the reg.
418 PrintOperand(MI, OpNo, O);
419 return;
420 case MachineOperand::MO_Immediate:
421 O << MO.getImm();
422 return;
423 case MachineOperand::MO_GlobalAddress:
424 PrintSymbolOperand(MO, O);
425 return;
426 }
427}
428
429void X86AsmPrinter::PrintLeaMemReference(const MachineInstr *MI, unsigned OpNo,
430 raw_ostream &O, StringRef Modifier) {
431 const MachineOperand &BaseReg = MI->getOperand(i: OpNo + X86::AddrBaseReg);
432 const MachineOperand &IndexReg = MI->getOperand(i: OpNo + X86::AddrIndexReg);
433 const MachineOperand &DispSpec = MI->getOperand(i: OpNo + X86::AddrDisp);
434
435 // If we really don't want to print out (rip), don't.
436 bool HasBaseReg = BaseReg.getReg() != 0;
437 if (HasBaseReg && Modifier == "no-rip" && BaseReg.getReg() == X86::RIP)
438 HasBaseReg = false;
439
440 // If we really just want to print out displacement.
441 if ((DispSpec.isGlobal() || DispSpec.isSymbol()) && Modifier == "disp-only")
442 HasBaseReg = false;
443
444 // HasParenPart - True if we will print out the () part of the mem ref.
445 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
446
447 switch (DispSpec.getType()) {
448 default:
449 llvm_unreachable("unknown operand type!");
450 case MachineOperand::MO_Immediate: {
451 int DispVal = DispSpec.getImm();
452 if (DispVal || !HasParenPart)
453 O << DispVal;
454 break;
455 }
456 case MachineOperand::MO_GlobalAddress:
457 case MachineOperand::MO_ConstantPoolIndex:
458 PrintSymbolOperand(MO: DispSpec, O);
459 break;
460 }
461
462 if (Modifier == "H")
463 O << "+8";
464
465 if (HasParenPart) {
466 assert(IndexReg.getReg() != X86::ESP &&
467 "X86 doesn't allow scaling by ESP");
468
469 O << '(';
470 if (HasBaseReg)
471 PrintModifiedOperand(MI, OpNo: OpNo + X86::AddrBaseReg, O, Modifier);
472
473 if (IndexReg.getReg()) {
474 O << ',';
475 PrintModifiedOperand(MI, OpNo: OpNo + X86::AddrIndexReg, O, Modifier);
476 unsigned ScaleVal = MI->getOperand(i: OpNo + X86::AddrScaleAmt).getImm();
477 if (ScaleVal != 1)
478 O << ',' << ScaleVal;
479 }
480 O << ')';
481 }
482}
483
484static bool isSimpleReturn(const MachineInstr &MI) {
485 // We exclude all tail calls here which set both isReturn and isCall.
486 return MI.getDesc().isReturn() && !MI.getDesc().isCall();
487}
488
489static bool isIndirectBranchOrTailCall(const MachineInstr &MI) {
490 unsigned Opc = MI.getOpcode();
491 return MI.getDesc().isIndirectBranch() /*Make below code in a good shape*/ ||
492 Opc == X86::TAILJMPr || Opc == X86::TAILJMPm ||
493 Opc == X86::TAILJMPr64 || Opc == X86::TAILJMPm64 ||
494 Opc == X86::TCRETURNri || Opc == X86::TCRETURN_WIN64ri ||
495 Opc == X86::TCRETURN_HIPE32ri || Opc == X86::TCRETURNmi ||
496 Opc == X86::TCRETURN_WINmi64 || Opc == X86::TCRETURNri64 ||
497 Opc == X86::TCRETURNmi64 || Opc == X86::TCRETURNri64_ImpCall ||
498 Opc == X86::TAILJMPr64_REX || Opc == X86::TAILJMPm64_REX;
499}
500
501void X86AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
502 if (Subtarget->hardenSlsRet() || Subtarget->hardenSlsIJmp()) {
503 auto I = MBB.getLastNonDebugInstr();
504 if (I != MBB.end()) {
505 if ((Subtarget->hardenSlsRet() && isSimpleReturn(MI: *I)) ||
506 (Subtarget->hardenSlsIJmp() && isIndirectBranchOrTailCall(MI: *I))) {
507 MCInst TmpInst;
508 TmpInst.setOpcode(X86::INT3);
509 EmitToStreamer(S&: *OutStreamer, Inst: TmpInst);
510 }
511 }
512 }
513 if (SplitChainedAtEndOfBlock) {
514 OutStreamer->emitWinCFISplitChained();
515 // Splitting into a new unwind info implicitly starts a prolog. We have no
516 // instructions to add to the prolog, so immediately end it.
517 OutStreamer->emitWinCFIEndProlog();
518 SplitChainedAtEndOfBlock = false;
519 }
520 AsmPrinter::emitBasicBlockEnd(MBB);
521 SMShadowTracker.emitShadowPadding(OutStreamer&: *OutStreamer, STI: getSubtargetInfo());
522}
523
524void X86AsmPrinter::PrintMemReference(const MachineInstr *MI, unsigned OpNo,
525 raw_ostream &O, StringRef Modifier) {
526 assert(isMem(*MI, OpNo) && "Invalid memory reference!");
527 const MachineOperand &Segment = MI->getOperand(i: OpNo + X86::AddrSegmentReg);
528 if (Segment.getReg()) {
529 PrintModifiedOperand(MI, OpNo: OpNo + X86::AddrSegmentReg, O, Modifier);
530 O << ':';
531 }
532 PrintLeaMemReference(MI, OpNo, O, Modifier);
533}
534
535void X86AsmPrinter::PrintIntelMemReference(const MachineInstr *MI,
536 unsigned OpNo, raw_ostream &O,
537 StringRef Modifier) {
538 const MachineOperand &BaseReg = MI->getOperand(i: OpNo + X86::AddrBaseReg);
539 unsigned ScaleVal = MI->getOperand(i: OpNo + X86::AddrScaleAmt).getImm();
540 const MachineOperand &IndexReg = MI->getOperand(i: OpNo + X86::AddrIndexReg);
541 const MachineOperand &DispSpec = MI->getOperand(i: OpNo + X86::AddrDisp);
542 const MachineOperand &SegReg = MI->getOperand(i: OpNo + X86::AddrSegmentReg);
543
544 // If we really don't want to print out (rip), don't.
545 bool HasBaseReg = BaseReg.getReg() != 0;
546 if (HasBaseReg && Modifier == "no-rip" && BaseReg.getReg() == X86::RIP)
547 HasBaseReg = false;
548
549 // If we really just want to print out displacement.
550 if ((DispSpec.isGlobal() || DispSpec.isSymbol()) && Modifier == "disp-only") {
551 HasBaseReg = false;
552 }
553
554 // If this has a segment register, print it.
555 if (SegReg.getReg()) {
556 PrintOperand(MI, OpNo: OpNo + X86::AddrSegmentReg, O);
557 O << ':';
558 }
559
560 O << '[';
561
562 bool NeedPlus = false;
563 if (HasBaseReg) {
564 PrintOperand(MI, OpNo: OpNo + X86::AddrBaseReg, O);
565 NeedPlus = true;
566 }
567
568 if (IndexReg.getReg()) {
569 if (NeedPlus) O << " + ";
570 if (ScaleVal != 1)
571 O << ScaleVal << '*';
572 PrintOperand(MI, OpNo: OpNo + X86::AddrIndexReg, O);
573 NeedPlus = true;
574 }
575
576 if (!DispSpec.isImm()) {
577 if (NeedPlus) O << " + ";
578 // Do not add `offset` operator. Matches the behaviour of
579 // X86IntelInstPrinter::printMemReference.
580 PrintSymbolOperand(MO: DispSpec, O);
581 } else {
582 int64_t DispVal = DispSpec.getImm();
583 if (DispVal || (!IndexReg.getReg() && !HasBaseReg)) {
584 if (NeedPlus) {
585 if (DispVal > 0)
586 O << " + ";
587 else {
588 O << " - ";
589 DispVal = -DispVal;
590 }
591 }
592 O << DispVal;
593 }
594 }
595 O << ']';
596}
597
598const MCSubtargetInfo *X86AsmPrinter::getIFuncMCSubtargetInfo() const {
599 assert(Subtarget);
600 return Subtarget;
601}
602
603void X86AsmPrinter::emitMachOIFuncStubBody(Module &M, const GlobalIFunc &GI,
604 MCSymbol *LazyPointer) {
605 // _ifunc:
606 // jmpq *lazy_pointer(%rip)
607
608 OutStreamer->emitInstruction(
609 Inst: MCInstBuilder(X86::JMP32m)
610 .addReg(Reg: X86::RIP)
611 .addImm(Val: 1)
612 .addReg(Reg: 0)
613 .addOperand(Op: MCOperand::createExpr(
614 Val: MCSymbolRefExpr::create(Symbol: LazyPointer, Ctx&: OutContext)))
615 .addReg(Reg: 0),
616 STI: *Subtarget);
617}
618
619void X86AsmPrinter::emitMachOIFuncStubHelperBody(Module &M,
620 const GlobalIFunc &GI,
621 MCSymbol *LazyPointer) {
622 // _ifunc.stub_helper:
623 // push %rax
624 // push %rdi
625 // push %rsi
626 // push %rdx
627 // push %rcx
628 // push %r8
629 // push %r9
630 // callq foo
631 // movq %rax,lazy_pointer(%rip)
632 // pop %r9
633 // pop %r8
634 // pop %rcx
635 // pop %rdx
636 // pop %rsi
637 // pop %rdi
638 // pop %rax
639 // jmpq *lazy_pointer(%rip)
640
641 for (int Reg :
642 {X86::RAX, X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9})
643 OutStreamer->emitInstruction(Inst: MCInstBuilder(X86::PUSH64r).addReg(Reg),
644 STI: *Subtarget);
645
646 OutStreamer->emitInstruction(
647 Inst: MCInstBuilder(X86::CALL64pcrel32)
648 .addOperand(Op: MCOperand::createExpr(Val: lowerConstant(CV: GI.getResolver()))),
649 STI: *Subtarget);
650
651 OutStreamer->emitInstruction(
652 Inst: MCInstBuilder(X86::MOV64mr)
653 .addReg(Reg: X86::RIP)
654 .addImm(Val: 1)
655 .addReg(Reg: 0)
656 .addOperand(Op: MCOperand::createExpr(
657 Val: MCSymbolRefExpr::create(Symbol: LazyPointer, Ctx&: OutContext)))
658 .addReg(Reg: 0)
659 .addReg(Reg: X86::RAX),
660 STI: *Subtarget);
661
662 for (int Reg :
663 {X86::R9, X86::R8, X86::RCX, X86::RDX, X86::RSI, X86::RDI, X86::RAX})
664 OutStreamer->emitInstruction(Inst: MCInstBuilder(X86::POP64r).addReg(Reg),
665 STI: *Subtarget);
666
667 OutStreamer->emitInstruction(
668 Inst: MCInstBuilder(X86::JMP32m)
669 .addReg(Reg: X86::RIP)
670 .addImm(Val: 1)
671 .addReg(Reg: 0)
672 .addOperand(Op: MCOperand::createExpr(
673 Val: MCSymbolRefExpr::create(Symbol: LazyPointer, Ctx&: OutContext)))
674 .addReg(Reg: 0),
675 STI: *Subtarget);
676}
677
678static bool printAsmMRegister(const X86AsmPrinter &P, const MachineInstr &MI,
679 const MachineOperand &MO, char Mode,
680 raw_ostream &O) {
681 Register Reg = MO.getReg();
682 bool EmitPercent = MI.getInlineAsmDialect() == InlineAsm::AD_ATT;
683
684 if (!X86::GR8RegClass.contains(Reg) &&
685 !X86::GR16RegClass.contains(Reg) &&
686 !X86::GR32RegClass.contains(Reg) &&
687 !X86::GR64RegClass.contains(Reg))
688 return true;
689
690 switch (Mode) {
691 default: return true; // Unknown mode.
692 case 'b': // Print QImode register
693 Reg = getX86SubSuperRegister(Reg, Size: 8);
694 break;
695 case 'h': // Print QImode high register
696 Reg = getX86SubSuperRegister(Reg, Size: 8, High: true);
697 if (!Reg.isValid())
698 return true;
699 break;
700 case 'w': // Print HImode register
701 Reg = getX86SubSuperRegister(Reg, Size: 16);
702 break;
703 case 'k': // Print SImode register
704 Reg = getX86SubSuperRegister(Reg, Size: 32);
705 break;
706 case 'V':
707 EmitPercent = false;
708 [[fallthrough]];
709 case 'q':
710 // Print 64-bit register names if 64-bit integer registers are available.
711 // Otherwise, print 32-bit register names.
712 Reg = getX86SubSuperRegister(Reg, Size: P.getSubtarget().is64Bit() ? 64 : 32);
713 break;
714 }
715
716 if (EmitPercent)
717 O << '%';
718
719 O << X86ATTInstPrinter::getRegisterName(Reg);
720 return false;
721}
722
723static bool printAsmVRegister(const MachineInstr &MI, const MachineOperand &MO,
724 char Mode, raw_ostream &O) {
725 Register Reg = MO.getReg();
726 bool EmitPercent = MI.getInlineAsmDialect() == InlineAsm::AD_ATT;
727
728 unsigned Index;
729 if (X86::VR128XRegClass.contains(Reg))
730 Index = Reg - X86::XMM0;
731 else if (X86::VR256XRegClass.contains(Reg))
732 Index = Reg - X86::YMM0;
733 else if (X86::VR512RegClass.contains(Reg))
734 Index = Reg - X86::ZMM0;
735 else
736 return true;
737
738 switch (Mode) {
739 default: // Unknown mode.
740 return true;
741 case 'x': // Print V4SFmode register
742 Reg = X86::XMM0 + Index;
743 break;
744 case 't': // Print V8SFmode register
745 Reg = X86::YMM0 + Index;
746 break;
747 case 'g': // Print V16SFmode register
748 Reg = X86::ZMM0 + Index;
749 break;
750 }
751
752 if (EmitPercent)
753 O << '%';
754
755 O << X86ATTInstPrinter::getRegisterName(Reg);
756 return false;
757}
758
759/// PrintAsmOperand - Print out an operand for an inline asm expression.
760///
761bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
762 const char *ExtraCode, raw_ostream &O) {
763 // Does this asm operand have a single letter operand modifier?
764 if (ExtraCode && ExtraCode[0]) {
765 if (ExtraCode[1] != 0) return true; // Unknown modifier.
766
767 const MachineOperand &MO = MI->getOperand(i: OpNo);
768 const bool IsIntel = MI->getInlineAsmDialect() == InlineAsm::AD_Intel;
769
770 switch (ExtraCode[0]) {
771 default:
772 // See if this is a generic print operand
773 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS&: O);
774 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
775 switch (MO.getType()) {
776 default:
777 return true;
778 case MachineOperand::MO_Immediate:
779 O << MO.getImm();
780 return false;
781 case MachineOperand::MO_ConstantPoolIndex:
782 case MachineOperand::MO_JumpTableIndex:
783 case MachineOperand::MO_ExternalSymbol:
784 llvm_unreachable("unexpected operand type!");
785 case MachineOperand::MO_GlobalAddress:
786 PrintSymbolOperand(MO, O);
787 if (Subtarget->is64Bit())
788 O << "(%rip)";
789 return false;
790 case MachineOperand::MO_Register:
791 O << (IsIntel ? '[' : '(');
792 PrintOperand(MI, OpNo, O);
793 O << (IsIntel ? ']' : ')');
794 return false;
795 }
796
797 case 'c': // Don't print "$" before a global var name or constant.
798 switch (MO.getType()) {
799 default:
800 PrintOperand(MI, OpNo, O);
801 break;
802 case MachineOperand::MO_Immediate:
803 O << MO.getImm();
804 break;
805 case MachineOperand::MO_ConstantPoolIndex:
806 case MachineOperand::MO_JumpTableIndex:
807 case MachineOperand::MO_ExternalSymbol:
808 llvm_unreachable("unexpected operand type!");
809 case MachineOperand::MO_GlobalAddress:
810 PrintSymbolOperand(MO, O);
811 break;
812 }
813 return false;
814
815 case 'A': // Print '*' before a register (it must be a register)
816 if (MO.isReg()) {
817 if (!IsIntel)
818 O << '*';
819 PrintOperand(MI, OpNo, O);
820 return false;
821 }
822 return true;
823
824 case 'b': // Print QImode register
825 case 'h': // Print QImode high register
826 case 'w': // Print HImode register
827 case 'k': // Print SImode register
828 case 'q': // Print DImode register
829 case 'V': // Print native register without '%'
830 if (MO.isReg())
831 return printAsmMRegister(P: *this, MI: *MI, MO, Mode: ExtraCode[0], O);
832 PrintOperand(MI, OpNo, O);
833 return false;
834
835 case 'x': // Print V4SFmode register
836 case 't': // Print V8SFmode register
837 case 'g': // Print V16SFmode register
838 if (MO.isReg())
839 return printAsmVRegister(MI: *MI, MO, Mode: ExtraCode[0], O);
840 PrintOperand(MI, OpNo, O);
841 return false;
842
843 case 'p': {
844 const MachineOperand &MO = MI->getOperand(i: OpNo);
845 if (MO.getType() != MachineOperand::MO_GlobalAddress)
846 return true;
847 PrintSymbolOperand(MO, O);
848 return false;
849 }
850
851 case 'P': // This is the operand of a call, treat specially.
852 PrintPCRelImm(MI, OpNo, O);
853 return false;
854
855 case 'n': // Negate the immediate or print a '-' before the operand.
856 // Note: this is a temporary solution. It should be handled target
857 // independently as part of the 'MC' work.
858 if (MO.isImm()) {
859 O << -MO.getImm();
860 return false;
861 }
862 O << '-';
863 }
864 }
865
866 PrintOperand(MI, OpNo, O);
867 return false;
868}
869
870bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
871 const char *ExtraCode,
872 raw_ostream &O) {
873 if (ExtraCode && ExtraCode[0]) {
874 if (ExtraCode[1] != 0) return true; // Unknown modifier.
875
876 switch (ExtraCode[0]) {
877 default: return true; // Unknown modifier.
878 case 'a': {
879 // Print as address — only valid with 'p' constraint.
880 const InlineAsm::Flag Flags(MI->getOperand(i: OpNo - 1).getImm());
881 if (Flags.getMemoryConstraintID() != InlineAsm::ConstraintCode::p)
882 return true;
883 break;
884 }
885 case 'b': // Print QImode register
886 case 'h': // Print QImode high register
887 case 'w': // Print HImode register
888 case 'k': // Print SImode register
889 case 'q': // Print SImode register
890 // These only apply to registers, ignore on mem.
891 break;
892 case 'H':
893 if (MI->getInlineAsmDialect() == InlineAsm::AD_Intel) {
894 return true; // Unsupported modifier in Intel inline assembly.
895 } else {
896 PrintMemReference(MI, OpNo, O, Modifier: "H");
897 }
898 return false;
899 // Print memory only with displacement. The Modifer 'P' is used in inline
900 // asm to present a call symbol or a global symbol which can not use base
901 // reg or index reg.
902 case 'P':
903 if (MI->getInlineAsmDialect() == InlineAsm::AD_Intel) {
904 PrintIntelMemReference(MI, OpNo, O, Modifier: "disp-only");
905 } else {
906 PrintMemReference(MI, OpNo, O, Modifier: "disp-only");
907 }
908 return false;
909 }
910 } else {
911 // Constraint 'p' requires modifier 'a'.
912 const InlineAsm::Flag Flags(MI->getOperand(i: OpNo - 1).getImm());
913 if (Flags.getMemoryConstraintID() == InlineAsm::ConstraintCode::p)
914 return true;
915 }
916 if (MI->getInlineAsmDialect() == InlineAsm::AD_Intel) {
917 PrintIntelMemReference(MI, OpNo, O);
918 } else {
919 PrintMemReference(MI, OpNo, O);
920 }
921 return false;
922}
923
924void X86AsmPrinter::emitStartOfAsmFile(Module &M) {
925 const Triple &TT = M.getTargetTriple();
926
927 if (TT.isOSBinFormatELF()) {
928 // Assemble feature flags that may require creation of a note section.
929 unsigned FeatureFlagsAnd = 0;
930 if (M.getModuleFlag(Key: "cf-protection-branch"))
931 FeatureFlagsAnd |= ELF::GNU_PROPERTY_X86_FEATURE_1_IBT;
932 if (M.getModuleFlag(Key: "cf-protection-return"))
933 FeatureFlagsAnd |= ELF::GNU_PROPERTY_X86_FEATURE_1_SHSTK;
934
935 if (FeatureFlagsAnd) {
936 // Emit a .note.gnu.property section with the flags.
937 assert(TT.isX86() && "CFProtection used on invalid architecture!");
938 MCSection *Cur = OutStreamer->getCurrentSectionOnly();
939 MCSection *Nt = MMI->getContext().getELFSection(
940 Section: ".note.gnu.property", Type: ELF::SHT_NOTE, Flags: ELF::SHF_ALLOC);
941 OutStreamer->switchSection(Section: Nt);
942
943 // Emitting note header.
944 const int WordSize = TT.isX86_64() && !TT.isX32() ? 8 : 4;
945 emitAlignment(Alignment: WordSize == 4 ? Align(4) : Align(8));
946 OutStreamer->emitIntValue(Value: 4, Size: 4 /*size*/); // data size for "GNU\0"
947 OutStreamer->emitIntValue(Value: 8 + WordSize, Size: 4 /*size*/); // Elf_Prop size
948 OutStreamer->emitIntValue(Value: ELF::NT_GNU_PROPERTY_TYPE_0, Size: 4 /*size*/);
949 OutStreamer->emitBytes(Data: StringRef("GNU", 4)); // note name
950
951 // Emitting an Elf_Prop for the CET properties.
952 OutStreamer->emitInt32(Value: ELF::GNU_PROPERTY_X86_FEATURE_1_AND);
953 OutStreamer->emitInt32(Value: 4); // data size
954 OutStreamer->emitInt32(Value: FeatureFlagsAnd); // data
955 emitAlignment(Alignment: WordSize == 4 ? Align(4) : Align(8)); // padding
956
957 OutStreamer->switchSection(Section: Cur);
958 }
959 }
960
961 if (TT.isOSBinFormatMachO())
962 OutStreamer->switchSection(Section: getObjFileLowering().getTextSection());
963
964 if (TT.isOSBinFormatCOFF()) {
965 emitCOFFFeatureSymbol(M);
966 emitCOFFReplaceableFunctionData(M);
967
968 if (M.getModuleFlag(Key: "import-call-optimization"))
969 EnableImportCallOptimization = true;
970
971 // Unwind v3 is set for the entire module, not just individual functions.
972 if (M.getWinX64EHUnwindMode() == WinX64EHUnwindMode::V3)
973 OutStreamer->emitWinCFIUnwindVersion(Version: 3);
974 }
975
976 // TODO: Support prefixed registers for the Intel syntax.
977 const bool IntelSyntax =
978 MAI.getOutputAssemblerDialect() == InlineAsm::AD_Intel;
979 OutStreamer->emitSyntaxDirective(Syntax: IntelSyntax ? "intel" : "att",
980 Options: IntelSyntax ? "noprefix" : "");
981
982 // If this is not inline asm and we're in 16-bit
983 // mode prefix assembly with .code16.
984 bool is16 = TT.getEnvironment() == Triple::CODE16;
985 if (M.getModuleInlineAsm().empty() && is16) {
986 auto *XTS =
987 static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
988 XTS->emitCode16();
989 }
990}
991
992static void
993emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
994 MachineModuleInfoImpl::StubValueTy &MCSym) {
995 // L_foo$stub:
996 OutStreamer.emitLabel(Symbol: StubLabel);
997 // .indirect_symbol _foo
998 OutStreamer.emitSymbolAttribute(Symbol: MCSym.getPointer(), Attribute: MCSA_IndirectSymbol);
999
1000 if (MCSym.getInt())
1001 // External to current translation unit.
1002 OutStreamer.emitIntValue(Value: 0, Size: 4/*size*/);
1003 else
1004 // Internal to current translation unit.
1005 //
1006 // When we place the LSDA into the TEXT section, the type info
1007 // pointers need to be indirect and pc-rel. We accomplish this by
1008 // using NLPs; however, sometimes the types are local to the file.
1009 // We need to fill in the value for the NLP in those cases.
1010 OutStreamer.emitValue(
1011 Value: MCSymbolRefExpr::create(Symbol: MCSym.getPointer(), Ctx&: OutStreamer.getContext()),
1012 Size: 4 /*size*/);
1013}
1014
1015static void emitNonLazyStubs(MachineModuleInfo *MMI, MCStreamer &OutStreamer) {
1016
1017 MachineModuleInfoMachO &MMIMacho =
1018 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1019
1020 // Output stubs for dynamically-linked functions.
1021 MachineModuleInfoMachO::SymbolListTy Stubs;
1022
1023 // Output stubs for external and common global variables.
1024 Stubs = MMIMacho.GetGVStubList();
1025 if (!Stubs.empty()) {
1026 OutStreamer.switchSection(Section: MMI->getContext().getMachOSection(
1027 Segment: "__IMPORT", Section: "__pointers", TypeAndAttributes: MachO::S_NON_LAZY_SYMBOL_POINTERS,
1028 K: SectionKind::getMetadata()));
1029
1030 for (auto &Stub : Stubs)
1031 emitNonLazySymbolPointer(OutStreamer, StubLabel: Stub.first, MCSym&: Stub.second);
1032
1033 Stubs.clear();
1034 OutStreamer.addBlankLine();
1035 }
1036}
1037
1038/// True if this module is being built for windows/msvc, and uses floating
1039/// point. This is used to emit an undefined reference to _fltused. This is
1040/// needed in Windows kernel or driver contexts to find and prevent code from
1041/// modifying non-GPR registers.
1042///
1043/// TODO: It would be better if this was computed from MIR by looking for
1044/// selected floating-point instructions.
1045static bool usesMSVCFloatingPoint(const Triple &TT, const Module &M) {
1046 // Only needed for MSVC
1047 if (!TT.isWindowsMSVCEnvironment())
1048 return false;
1049
1050 for (const Function &F : M) {
1051 for (const Instruction &I : instructions(F)) {
1052 if (I.getType()->isFloatingPointTy())
1053 return true;
1054
1055 for (const auto &Op : I.operands()) {
1056 if (Op->getType()->isFloatingPointTy())
1057 return true;
1058 }
1059 }
1060 }
1061
1062 return false;
1063}
1064
1065void X86AsmPrinter::emitEndOfAsmFile(Module &M) {
1066 const Triple &TT = M.getTargetTriple();
1067
1068 if (TT.isOSBinFormatMachO()) {
1069 // Mach-O uses non-lazy symbol stubs to encode per-TU information into
1070 // global table for symbol lookup.
1071 emitNonLazyStubs(MMI, OutStreamer&: *OutStreamer);
1072
1073 // Emit fault map information.
1074 FM.serializeToFaultMapSection();
1075
1076 // This flag tells the linker that no global symbols contain code that fall
1077 // through to other global symbols (e.g. an implementation of multiple entry
1078 // points). If this doesn't occur, the linker can safely perform dead code
1079 // stripping. Since LLVM never generates code that does this, it is always
1080 // safe to set.
1081 OutStreamer->emitSubsectionsViaSymbols();
1082 } else if (TT.isOSBinFormatCOFF()) {
1083 // If import call optimization is enabled, emit the appropriate section.
1084 // We do this whether or not we recorded any items.
1085 if (EnableImportCallOptimization) {
1086 OutStreamer->switchSection(Section: getObjFileLowering().getImportCallSection());
1087
1088 // Section always starts with some magic.
1089 constexpr char ImpCallMagic[12] = "RetpolineV1";
1090 OutStreamer->emitBytes(Data: StringRef{ImpCallMagic, sizeof(ImpCallMagic)});
1091
1092 // Layout of this section is:
1093 // Per section that contains an item to record:
1094 // uint32_t SectionSize: Size in bytes for information in this section.
1095 // uint32_t Section Number
1096 // Per call to imported function in section:
1097 // uint32_t Kind: the kind of item.
1098 // uint32_t InstOffset: the offset of the instr in its parent section.
1099 for (auto &[Section, CallsToImportedFuncs] :
1100 SectionToImportedFunctionCalls) {
1101 unsigned SectionSize =
1102 sizeof(uint32_t) * (2 + 2 * CallsToImportedFuncs.size());
1103 OutStreamer->emitInt32(Value: SectionSize);
1104 OutStreamer->emitCOFFSecNumber(Symbol: Section->getBeginSymbol());
1105 for (auto &[CallsiteSymbol, Kind] : CallsToImportedFuncs) {
1106 OutStreamer->emitInt32(Value: Kind);
1107 OutStreamer->emitCOFFSecOffset(Symbol: CallsiteSymbol);
1108 }
1109 }
1110 }
1111
1112 if (usesMSVCFloatingPoint(TT, M)) {
1113 // In Windows' libcmt.lib, there is a file which is linked in only if the
1114 // symbol _fltused is referenced. Linking this in causes some
1115 // side-effects:
1116 //
1117 // 1. For x86-32, it will set the x87 rounding mode to 53-bit instead of
1118 // 64-bit mantissas at program start.
1119 //
1120 // 2. It links in support routines for floating-point in scanf and printf.
1121 //
1122 // MSVC emits an undefined reference to _fltused when there are any
1123 // floating point operations in the program (including calls). A program
1124 // that only has: `scanf("%f", &global_float);` may fail to trigger this,
1125 // but oh well...that's a documented issue.
1126 StringRef SymbolName = TT.isX86_32() ? "__fltused" : "_fltused";
1127 MCSymbol *S = MMI->getContext().getOrCreateSymbol(Name: SymbolName);
1128 OutStreamer->emitSymbolAttribute(Symbol: S, Attribute: MCSA_Global);
1129 return;
1130 }
1131 } else if (TT.isOSBinFormatELF()) {
1132 FM.serializeToFaultMapSection();
1133 }
1134
1135 // Emit __morestack address if needed for indirect calls.
1136 if (TT.isX86_64() && TM.getCodeModel() == CodeModel::Large) {
1137 if (MCSymbol *AddrSymbol = OutContext.lookupSymbol(Name: "__morestack_addr")) {
1138 Align Alignment(1);
1139 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
1140 DL: getDataLayout(), Kind: SectionKind::getReadOnly(),
1141 /*C=*/nullptr, Alignment, /*F=*/nullptr);
1142 OutStreamer->switchSection(Section: ReadOnlySection);
1143 OutStreamer->emitLabel(Symbol: AddrSymbol);
1144
1145 unsigned PtrSize = MAI.getCodePointerSize();
1146 OutStreamer->emitSymbolValue(Sym: GetExternalSymbolSymbol(Sym: "__morestack"),
1147 Size: PtrSize);
1148 }
1149 }
1150}
1151
1152char X86AsmPrinter::ID = 0;
1153
1154INITIALIZE_PASS(X86AsmPrinter, "x86-asm-printer", "X86 Assembly Printer", false,
1155 false)
1156
1157//===----------------------------------------------------------------------===//
1158// Target Registry Stuff
1159//===----------------------------------------------------------------------===//
1160
1161// Force static initialization.
1162extern "C" LLVM_C_ABI void LLVMInitializeX86AsmPrinter() {
1163 RegisterAsmPrinter<X86AsmPrinter> X(getTheX86_32Target());
1164 RegisterAsmPrinter<X86AsmPrinter> Y(getTheX86_64Target());
1165}
1166
1167PreservedAnalyses X86AsmPrinterBeginPass::run(Module &M,
1168 ModuleAnalysisManager &MAM) {
1169 // Force the computation of SDPI so that it is available for the
1170 // actual pass, where it cannot be explicitly requested.
1171 MAM.getResult<StaticDataProfileInfoAnalysis>(IR&: M);
1172 X86AsmPrinter &AsmPrinter = static_cast<X86AsmPrinter &>(
1173 MAM.getResult<AsmPrinterAnalysis>(IR&: M).getPrinter());
1174 AsmPrinter.GetPSI = [&MAM](Module &M) {
1175 return &MAM.getResult<ProfileSummaryAnalysis>(IR&: M);
1176 };
1177 AsmPrinter.GetSDPI = [&MAM](Module &M) {
1178 return &MAM.getResult<StaticDataProfileInfoAnalysis>(IR&: M)
1179 .getStaticDataProfileInfo();
1180 };
1181 setupModuleAsmPrinter(M, MAM, AsmPrinter);
1182 AsmPrinter.doInitialization(M);
1183 return PreservedAnalyses::all();
1184}
1185
1186PreservedAnalyses X86AsmPrinterPass::run(MachineFunction &MF,
1187 MachineFunctionAnalysisManager &MFAM) {
1188 X86AsmPrinter &AsmPrinter = static_cast<X86AsmPrinter &>(
1189 MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(IR&: MF)
1190 .getCachedResult<AsmPrinterAnalysis>(IR&: *MF.getFunction().getParent())
1191 ->getPrinter());
1192 AsmPrinter.GetPSI = [&MFAM, &MF](Module &M) {
1193 return MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(IR&: MF)
1194 .getCachedResult<ProfileSummaryAnalysis>(IR&: M);
1195 };
1196 AsmPrinter.GetSDPI = [&MFAM, &MF](Module &M) {
1197 return &MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(IR&: MF)
1198 .getCachedResult<StaticDataProfileInfoAnalysis>(
1199 IR&: *MF.getFunction().getParent())
1200 ->getStaticDataProfileInfo();
1201 };
1202 setupMachineFunctionAsmPrinter(MFAM, MF, AsmPrinter);
1203 AsmPrinter.runOnMachineFunction(MF);
1204 return PreservedAnalyses::all();
1205}
1206
1207PreservedAnalyses X86AsmPrinterEndPass::run(Module &M,
1208 ModuleAnalysisManager &MAM) {
1209 X86AsmPrinter &AsmPrinter = static_cast<X86AsmPrinter &>(
1210 MAM.getCachedResult<AsmPrinterAnalysis>(IR&: M)->getPrinter());
1211 AsmPrinter.GetPSI = [&MAM](Module &M) {
1212 return &MAM.getResult<ProfileSummaryAnalysis>(IR&: M);
1213 };
1214 AsmPrinter.GetSDPI = [&MAM](Module &M) {
1215 return &MAM.getResult<StaticDataProfileInfoAnalysis>(IR&: M)
1216 .getStaticDataProfileInfo();
1217 };
1218 setupModuleAsmPrinter(M, MAM, AsmPrinter);
1219 AsmPrinter.doFinalization(M);
1220 return PreservedAnalyses::all();
1221}
1222