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