LLVM 19.0.0git
PPCAsmPrinter.cpp
Go to the documentation of this file.
1//===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC 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 PowerPC assembly language. This printer is
11// the output mechanism used by `llc'.
12//
13// Documentation at http://developer.apple.com/documentation/DeveloperTools/
14// Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
15//
16//===----------------------------------------------------------------------===//
17
22#include "PPC.h"
23#include "PPCInstrInfo.h"
25#include "PPCSubtarget.h"
26#include "PPCTargetMachine.h"
27#include "PPCTargetStreamer.h"
29#include "llvm/ADT/MapVector.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/Twine.h"
46#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/GlobalValue.h"
49#include "llvm/IR/Module.h"
50#include "llvm/MC/MCAsmInfo.h"
51#include "llvm/MC/MCContext.h"
53#include "llvm/MC/MCExpr.h"
54#include "llvm/MC/MCInst.h"
58#include "llvm/MC/MCStreamer.h"
59#include "llvm/MC/MCSymbol.h"
60#include "llvm/MC/MCSymbolELF.h"
62#include "llvm/MC/SectionKind.h"
66#include "llvm/Support/Debug.h"
67#include "llvm/Support/Error.h"
76#include <algorithm>
77#include <cassert>
78#include <cstdint>
79#include <memory>
80#include <new>
81
82using namespace llvm;
83using namespace llvm::XCOFF;
84
85#define DEBUG_TYPE "asmprinter"
86
87STATISTIC(NumTOCEntries, "Number of Total TOC Entries Emitted.");
88STATISTIC(NumTOCConstPool, "Number of Constant Pool TOC Entries.");
89STATISTIC(NumTOCGlobalInternal,
90 "Number of Internal Linkage Global TOC Entries.");
91STATISTIC(NumTOCGlobalExternal,
92 "Number of External Linkage Global TOC Entries.");
93STATISTIC(NumTOCJumpTable, "Number of Jump Table TOC Entries.");
94STATISTIC(NumTOCThreadLocal, "Number of Thread Local TOC Entries.");
95STATISTIC(NumTOCBlockAddress, "Number of Block Address TOC Entries.");
96STATISTIC(NumTOCEHBlock, "Number of EH Block TOC Entries.");
97
99 "aix-ssp-tb-bit", cl::init(false),
100 cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden);
101
102// Specialize DenseMapInfo to allow
103// std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind> in DenseMap.
104// This specialization is needed here because that type is used as keys in the
105// map representing TOC entries.
106namespace llvm {
107template <>
108struct DenseMapInfo<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>> {
109 using TOCKey = std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>;
110
111 static inline TOCKey getEmptyKey() {
113 }
114 static inline TOCKey getTombstoneKey() {
116 }
117 static unsigned getHashValue(const TOCKey &PairVal) {
120 DenseMapInfo<int>::getHashValue(PairVal.second));
121 }
122 static bool isEqual(const TOCKey &A, const TOCKey &B) { return A == B; }
123};
124} // end namespace llvm
125
126namespace {
127
128enum {
129 // GNU attribute tags for PowerPC ABI
130 Tag_GNU_Power_ABI_FP = 4,
131 Tag_GNU_Power_ABI_Vector = 8,
132 Tag_GNU_Power_ABI_Struct_Return = 12,
133
134 // GNU attribute values for PowerPC float ABI, as combination of two parts
135 Val_GNU_Power_ABI_NoFloat = 0b00,
136 Val_GNU_Power_ABI_HardFloat_DP = 0b01,
137 Val_GNU_Power_ABI_SoftFloat_DP = 0b10,
138 Val_GNU_Power_ABI_HardFloat_SP = 0b11,
139
140 Val_GNU_Power_ABI_LDBL_IBM128 = 0b0100,
141 Val_GNU_Power_ABI_LDBL_64 = 0b1000,
142 Val_GNU_Power_ABI_LDBL_IEEE128 = 0b1100,
143};
144
145class PPCAsmPrinter : public AsmPrinter {
146protected:
147 // For TLS on AIX, we need to be able to identify TOC entries of specific
148 // VariantKind so we can add the right relocations when we generate the
149 // entries. So each entry is represented by a pair of MCSymbol and
150 // VariantKind. For example, we need to be able to identify the following
151 // entry as a TLSGD entry so we can add the @m relocation:
152 // .tc .i[TC],i[TL]@m
153 // By default, VK_None is used for the VariantKind.
155 MCSymbol *>
156 TOC;
157 const PPCSubtarget *Subtarget = nullptr;
158
159 // Keep track of the number of TLS variables and their corresponding
160 // addresses, which is then used for the assembly printing of
161 // non-TOC-based local-exec variables.
162 MapVector<const GlobalValue *, uint64_t> TLSVarsToAddressMapping;
163
164public:
165 explicit PPCAsmPrinter(TargetMachine &TM,
166 std::unique_ptr<MCStreamer> Streamer)
167 : AsmPrinter(TM, std::move(Streamer)) {}
168
169 StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
170
171 enum TOCEntryType {
172 TOCType_ConstantPool,
173 TOCType_GlobalExternal,
174 TOCType_GlobalInternal,
175 TOCType_JumpTable,
176 TOCType_ThreadLocal,
177 TOCType_BlockAddress,
178 TOCType_EHBlock
179 };
180
181 MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym, TOCEntryType Type,
183 MCSymbolRefExpr::VariantKind::VK_None);
184
185 bool doInitialization(Module &M) override {
186 if (!TOC.empty())
187 TOC.clear();
189 }
190
191 void emitInstruction(const MachineInstr *MI) override;
192
193 /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
194 /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
195 /// The \p MI would be INLINEASM ONLY.
196 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
197
198 void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
199 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
200 const char *ExtraCode, raw_ostream &O) override;
201 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
202 const char *ExtraCode, raw_ostream &O) override;
203
204 void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
205 void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
206 void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
207 void EmitAIXTlsCallHelper(const MachineInstr *MI);
208 const MCExpr *getAdjustedFasterLocalExpr(const MachineOperand &MO,
209 int64_t Offset);
210 bool runOnMachineFunction(MachineFunction &MF) override {
211 Subtarget = &MF.getSubtarget<PPCSubtarget>();
212 bool Changed = AsmPrinter::runOnMachineFunction(MF);
214 return Changed;
215 }
216};
217
218/// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
219class PPCLinuxAsmPrinter : public PPCAsmPrinter {
220public:
221 explicit PPCLinuxAsmPrinter(TargetMachine &TM,
222 std::unique_ptr<MCStreamer> Streamer)
223 : PPCAsmPrinter(TM, std::move(Streamer)) {}
224
225 StringRef getPassName() const override {
226 return "Linux PPC Assembly Printer";
227 }
228
229 void emitGNUAttributes(Module &M);
230
231 void emitStartOfAsmFile(Module &M) override;
232 void emitEndOfAsmFile(Module &) override;
233
234 void emitFunctionEntryLabel() override;
235
236 void emitFunctionBodyStart() override;
237 void emitFunctionBodyEnd() override;
238 void emitInstruction(const MachineInstr *MI) override;
239};
240
241class PPCAIXAsmPrinter : public PPCAsmPrinter {
242private:
243 /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern
244 /// linkage for them in AIX.
245 SmallSetVector<MCSymbol *, 8> ExtSymSDNodeSymbols;
246
247 /// A format indicator and unique trailing identifier to form part of the
248 /// sinit/sterm function names.
249 std::string FormatIndicatorAndUniqueModId;
250
251 // Record a list of GlobalAlias associated with a GlobalObject.
252 // This is used for AIX's extra-label-at-definition aliasing strategy.
254 GOAliasMap;
255
256 uint16_t getNumberOfVRSaved();
257 void emitTracebackTable();
258
260
261 void emitGlobalVariableHelper(const GlobalVariable *);
262
263 // Get the offset of an alias based on its AliaseeObject.
264 uint64_t getAliasOffset(const Constant *C);
265
266public:
267 PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
268 : PPCAsmPrinter(TM, std::move(Streamer)) {
269 if (MAI->isLittleEndian())
271 "cannot create AIX PPC Assembly Printer for a little-endian target");
272 }
273
274 StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
275
276 bool doInitialization(Module &M) override;
277
278 void emitXXStructorList(const DataLayout &DL, const Constant *List,
279 bool IsCtor) override;
280
281 void SetupMachineFunction(MachineFunction &MF) override;
282
283 void emitGlobalVariable(const GlobalVariable *GV) override;
284
285 void emitFunctionDescriptor() override;
286
287 void emitFunctionEntryLabel() override;
288
289 void emitFunctionBodyEnd() override;
290
291 void emitPGORefs(Module &M);
292
293 void emitEndOfAsmFile(Module &) override;
294
295 void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
296
297 void emitInstruction(const MachineInstr *MI) override;
298
299 bool doFinalization(Module &M) override;
300
301 void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
302
303 void emitModuleCommandLines(Module &M) override;
304};
305
306} // end anonymous namespace
307
308void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
309 raw_ostream &O) {
310 // Computing the address of a global symbol, not calling it.
311 const GlobalValue *GV = MO.getGlobal();
312 getSymbol(GV)->print(O, MAI);
313 printOffset(MO.getOffset(), O);
314}
315
316void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
317 raw_ostream &O) {
318 const DataLayout &DL = getDataLayout();
319 const MachineOperand &MO = MI->getOperand(OpNo);
320
321 switch (MO.getType()) {
323 // The MI is INLINEASM ONLY and UseVSXReg is always false.
325
326 // Linux assembler (Others?) does not take register mnemonics.
327 // FIXME - What about special registers used in mfspr/mtspr?
329 return;
330 }
332 O << MO.getImm();
333 return;
334
336 MO.getMBB()->getSymbol()->print(O, MAI);
337 return;
339 O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
340 << MO.getIndex();
341 return;
343 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
344 return;
346 PrintSymbolOperand(MO, O);
347 return;
348 }
349
350 default:
351 O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
352 return;
353 }
354}
355
356/// PrintAsmOperand - Print out an operand for an inline asm expression.
357///
358bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
359 const char *ExtraCode, raw_ostream &O) {
360 // Does this asm operand have a single letter operand modifier?
361 if (ExtraCode && ExtraCode[0]) {
362 if (ExtraCode[1] != 0) return true; // Unknown modifier.
363
364 switch (ExtraCode[0]) {
365 default:
366 // See if this is a generic print operand
367 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
368 case 'L': // Write second word of DImode reference.
369 // Verify that this operand has two consecutive registers.
370 if (!MI->getOperand(OpNo).isReg() ||
371 OpNo+1 == MI->getNumOperands() ||
372 !MI->getOperand(OpNo+1).isReg())
373 return true;
374 ++OpNo; // Return the high-part.
375 break;
376 case 'I':
377 // Write 'i' if an integer constant, otherwise nothing. Used to print
378 // addi vs add, etc.
379 if (MI->getOperand(OpNo).isImm())
380 O << "i";
381 return false;
382 case 'x':
383 if(!MI->getOperand(OpNo).isReg())
384 return true;
385 // This operand uses VSX numbering.
386 // If the operand is a VMX register, convert it to a VSX register.
387 Register Reg = MI->getOperand(OpNo).getReg();
388 if (PPC::isVRRegister(Reg))
389 Reg = PPC::VSX32 + (Reg - PPC::V0);
390 else if (PPC::isVFRegister(Reg))
391 Reg = PPC::VSX32 + (Reg - PPC::VF0);
392 const char *RegName;
395 O << RegName;
396 return false;
397 }
398 }
399
400 printOperand(MI, OpNo, O);
401 return false;
402}
403
404// At the moment, all inline asm memory operands are a single register.
405// In any case, the output of this routine should always be just one
406// assembler operand.
407bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
408 const char *ExtraCode,
409 raw_ostream &O) {
410 if (ExtraCode && ExtraCode[0]) {
411 if (ExtraCode[1] != 0) return true; // Unknown modifier.
412
413 switch (ExtraCode[0]) {
414 default: return true; // Unknown modifier.
415 case 'L': // A memory reference to the upper word of a double word op.
416 O << getDataLayout().getPointerSize() << "(";
417 printOperand(MI, OpNo, O);
418 O << ")";
419 return false;
420 case 'y': // A memory reference for an X-form instruction
421 O << "0, ";
422 printOperand(MI, OpNo, O);
423 return false;
424 case 'I':
425 // Write 'i' if an integer constant, otherwise nothing. Used to print
426 // addi vs add, etc.
427 if (MI->getOperand(OpNo).isImm())
428 O << "i";
429 return false;
430 case 'U': // Print 'u' for update form.
431 case 'X': // Print 'x' for indexed form.
432 // FIXME: Currently for PowerPC memory operands are always loaded
433 // into a register, so we never get an update or indexed form.
434 // This is bad even for offset forms, since even if we know we
435 // have a value in -16(r1), we will generate a load into r<n>
436 // and then load from 0(r<n>). Until that issue is fixed,
437 // tolerate 'U' and 'X' but don't output anything.
438 assert(MI->getOperand(OpNo).isReg());
439 return false;
440 }
441 }
442
443 assert(MI->getOperand(OpNo).isReg());
444 O << "0(";
445 printOperand(MI, OpNo, O);
446 O << ")";
447 return false;
448}
449
450static void collectTOCStats(PPCAsmPrinter::TOCEntryType Type) {
451 ++NumTOCEntries;
452 switch (Type) {
453 case PPCAsmPrinter::TOCType_ConstantPool:
454 ++NumTOCConstPool;
455 break;
456 case PPCAsmPrinter::TOCType_GlobalInternal:
457 ++NumTOCGlobalInternal;
458 break;
459 case PPCAsmPrinter::TOCType_GlobalExternal:
460 ++NumTOCGlobalExternal;
461 break;
462 case PPCAsmPrinter::TOCType_JumpTable:
463 ++NumTOCJumpTable;
464 break;
465 case PPCAsmPrinter::TOCType_ThreadLocal:
466 ++NumTOCThreadLocal;
467 break;
468 case PPCAsmPrinter::TOCType_BlockAddress:
469 ++NumTOCBlockAddress;
470 break;
471 case PPCAsmPrinter::TOCType_EHBlock:
472 ++NumTOCEHBlock;
473 break;
474 }
475}
476
478 const TargetMachine &TM,
479 const MachineOperand &MO) {
480 CodeModel::Model ModuleModel = TM.getCodeModel();
481
482 // If the operand is not a global address then there is no
483 // global variable to carry an attribute.
485 return ModuleModel;
486
487 const GlobalValue *GV = MO.getGlobal();
488 assert(GV && "expected global for MO_GlobalAddress");
489
490 return S.getCodeModel(TM, GV);
491}
492
494 switch (CM) {
495 case CodeModel::Large:
497 return;
498 case CodeModel::Small:
500 return;
501 default:
502 report_fatal_error("Invalid code model for AIX");
503 }
504}
505
506/// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
507/// exists for it. If not, create one. Then return a symbol that references
508/// the TOC entry.
509MCSymbol *
510PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym, TOCEntryType Type,
512 // If this is a new TOC entry add statistics about it.
513 if (!TOC.contains({Sym, Kind}))
515
516 MCSymbol *&TOCEntry = TOC[{Sym, Kind}];
517 if (!TOCEntry)
518 TOCEntry = createTempSymbol("C");
519 return TOCEntry;
520}
521
522void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
523 unsigned NumNOPBytes = MI.getOperand(1).getImm();
524
525 auto &Ctx = OutStreamer->getContext();
526 MCSymbol *MILabel = Ctx.createTempSymbol();
527 OutStreamer->emitLabel(MILabel);
528
529 SM.recordStackMap(*MILabel, MI);
530 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
531
532 // Scan ahead to trim the shadow.
533 const MachineBasicBlock &MBB = *MI.getParent();
535 ++MII;
536 while (NumNOPBytes > 0) {
537 if (MII == MBB.end() || MII->isCall() ||
538 MII->getOpcode() == PPC::DBG_VALUE ||
539 MII->getOpcode() == TargetOpcode::PATCHPOINT ||
540 MII->getOpcode() == TargetOpcode::STACKMAP)
541 break;
542 ++MII;
543 NumNOPBytes -= 4;
544 }
545
546 // Emit nops.
547 for (unsigned i = 0; i < NumNOPBytes; i += 4)
548 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
549}
550
551// Lower a patchpoint of the form:
552// [<def>], <id>, <numBytes>, <target>, <numArgs>
553void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
554 auto &Ctx = OutStreamer->getContext();
555 MCSymbol *MILabel = Ctx.createTempSymbol();
556 OutStreamer->emitLabel(MILabel);
557
558 SM.recordPatchPoint(*MILabel, MI);
559 PatchPointOpers Opers(&MI);
560
561 unsigned EncodedBytes = 0;
562 const MachineOperand &CalleeMO = Opers.getCallTarget();
563
564 if (CalleeMO.isImm()) {
565 int64_t CallTarget = CalleeMO.getImm();
566 if (CallTarget) {
567 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
568 "High 16 bits of call target should be zero.");
569 Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
570 EncodedBytes = 0;
571 // Materialize the jump address:
572 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
573 .addReg(ScratchReg)
574 .addImm((CallTarget >> 32) & 0xFFFF));
575 ++EncodedBytes;
576 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
577 .addReg(ScratchReg)
578 .addReg(ScratchReg)
579 .addImm(32).addImm(16));
580 ++EncodedBytes;
581 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
582 .addReg(ScratchReg)
583 .addReg(ScratchReg)
584 .addImm((CallTarget >> 16) & 0xFFFF));
585 ++EncodedBytes;
586 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
587 .addReg(ScratchReg)
588 .addReg(ScratchReg)
589 .addImm(CallTarget & 0xFFFF));
590
591 // Save the current TOC pointer before the remote call.
592 int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
593 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
594 .addReg(PPC::X2)
595 .addImm(TOCSaveOffset)
596 .addReg(PPC::X1));
597 ++EncodedBytes;
598
599 // If we're on ELFv1, then we need to load the actual function pointer
600 // from the function descriptor.
601 if (!Subtarget->isELFv2ABI()) {
602 // Load the new TOC pointer and the function address, but not r11
603 // (needing this is rare, and loading it here would prevent passing it
604 // via a 'nest' parameter.
605 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
606 .addReg(PPC::X2)
607 .addImm(8)
608 .addReg(ScratchReg));
609 ++EncodedBytes;
610 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
611 .addReg(ScratchReg)
612 .addImm(0)
613 .addReg(ScratchReg));
614 ++EncodedBytes;
615 }
616
617 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
618 .addReg(ScratchReg));
619 ++EncodedBytes;
620 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
621 ++EncodedBytes;
622
623 // Restore the TOC pointer after the call.
624 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
625 .addReg(PPC::X2)
626 .addImm(TOCSaveOffset)
627 .addReg(PPC::X1));
628 ++EncodedBytes;
629 }
630 } else if (CalleeMO.isGlobal()) {
631 const GlobalValue *GValue = CalleeMO.getGlobal();
632 MCSymbol *MOSymbol = getSymbol(GValue);
633 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
634
635 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
636 .addExpr(SymVar));
637 EncodedBytes += 2;
638 }
639
640 // Each instruction is 4 bytes.
641 EncodedBytes *= 4;
642
643 // Emit padding.
644 unsigned NumBytes = Opers.getNumPatchBytes();
645 assert(NumBytes >= EncodedBytes &&
646 "Patchpoint can't request size less than the length of a call.");
647 assert((NumBytes - EncodedBytes) % 4 == 0 &&
648 "Invalid number of NOP bytes requested!");
649 for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
650 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
651}
652
653/// This helper function creates the TlsGetAddr/TlsGetMod MCSymbol for AIX. We
654/// will create the csect and use the qual-name symbol instead of creating just
655/// the external symbol.
656static MCSymbol *createMCSymbolForTlsGetAddr(MCContext &Ctx, unsigned MIOpc) {
657 StringRef SymName;
658 switch (MIOpc) {
659 default:
660 SymName = ".__tls_get_addr";
661 break;
662 case PPC::GETtlsTpointer32AIX:
663 SymName = ".__get_tpointer";
664 break;
665 case PPC::GETtlsMOD32AIX:
666 case PPC::GETtlsMOD64AIX:
667 SymName = ".__tls_get_mod";
668 break;
669 }
670 return Ctx
674}
675
676void PPCAsmPrinter::EmitAIXTlsCallHelper(const MachineInstr *MI) {
677 assert(Subtarget->isAIXABI() &&
678 "Only expecting to emit calls to get the thread pointer on AIX!");
679
680 MCSymbol *TlsCall = createMCSymbolForTlsGetAddr(OutContext, MI->getOpcode());
681 const MCExpr *TlsRef =
683 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BLA).addExpr(TlsRef));
684}
685
686/// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
687/// call to __tls_get_addr to the current output stream.
688void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
691 unsigned Opcode = PPC::BL8_NOP_TLS;
692
693 assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI");
694 if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG ||
695 MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) {
697 Opcode = PPC::BL8_NOTOC_TLS;
698 }
699 const Module *M = MF->getFunction().getParent();
700
701 assert(MI->getOperand(0).isReg() &&
702 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
703 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
704 "GETtls[ld]ADDR[32] must define GPR3");
705 assert(MI->getOperand(1).isReg() &&
706 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
707 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
708 "GETtls[ld]ADDR[32] must read GPR3");
709
710 if (Subtarget->isAIXABI()) {
711 // For TLSGD, the variable offset should already be in R4 and the region
712 // handle should already be in R3. We generate an absolute branch to
713 // .__tls_get_addr. For TLSLD, the module handle should already be in R3.
714 // We generate an absolute branch to .__tls_get_mod.
715 Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4;
716 (void)VarOffsetReg;
717 assert((MI->getOpcode() == PPC::GETtlsMOD32AIX ||
718 MI->getOpcode() == PPC::GETtlsMOD64AIX ||
719 (MI->getOperand(2).isReg() &&
720 MI->getOperand(2).getReg() == VarOffsetReg)) &&
721 "GETtls[ld]ADDR[32] must read GPR4");
722 EmitAIXTlsCallHelper(MI);
723 return;
724 }
725
726 MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol("__tls_get_addr");
727
728 if (Subtarget->is32BitELFABI() && isPositionIndependent())
730
731 const MCExpr *TlsRef =
732 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
733
734 // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
735 if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
736 M->getPICLevel() == PICLevel::BigPIC)
738 TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
739 const MachineOperand &MO = MI->getOperand(2);
740 const GlobalValue *GValue = MO.getGlobal();
741 MCSymbol *MOSymbol = getSymbol(GValue);
742 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
743 EmitToStreamer(*OutStreamer,
744 MCInstBuilder(Subtarget->isPPC64() ? Opcode
745 : (unsigned)PPC::BL_TLS)
746 .addExpr(TlsRef)
747 .addExpr(SymVar));
748}
749
750/// Map a machine operand for a TOC pseudo-machine instruction to its
751/// corresponding MCSymbol.
753 AsmPrinter &AP) {
754 switch (MO.getType()) {
756 return AP.getSymbol(MO.getGlobal());
758 return AP.GetCPISymbol(MO.getIndex());
760 return AP.GetJTISymbol(MO.getIndex());
763 default:
764 llvm_unreachable("Unexpected operand type to get symbol.");
765 }
766}
767
768static PPCAsmPrinter::TOCEntryType
770 // Use the target flags to determine if this MO is Thread Local.
771 // If we don't do this it comes out as Global.
773 return PPCAsmPrinter::TOCType_ThreadLocal;
774
775 switch (MO.getType()) {
777 const GlobalValue *GlobalV = MO.getGlobal();
778 GlobalValue::LinkageTypes Linkage = GlobalV->getLinkage();
779 if (Linkage == GlobalValue::ExternalLinkage ||
782 return PPCAsmPrinter::TOCType_GlobalExternal;
783
784 return PPCAsmPrinter::TOCType_GlobalInternal;
785 }
787 return PPCAsmPrinter::TOCType_ConstantPool;
789 return PPCAsmPrinter::TOCType_JumpTable;
791 return PPCAsmPrinter::TOCType_BlockAddress;
792 default:
793 llvm_unreachable("Unexpected operand type to get TOC type.");
794 }
795}
796/// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
797/// the current output stream.
798///
799void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
800 PPC_MC::verifyInstructionPredicates(MI->getOpcode(),
801 getSubtargetInfo().getFeatureBits());
802
803 MCInst TmpInst;
804 const bool IsPPC64 = Subtarget->isPPC64();
805 const bool IsAIX = Subtarget->isAIXABI();
806 const bool HasAIXSmallLocalTLS = Subtarget->hasAIXSmallLocalExecTLS() ||
807 Subtarget->hasAIXSmallLocalDynamicTLS();
808 const Module *M = MF->getFunction().getParent();
809 PICLevel::Level PL = M->getPICLevel();
810
811#ifndef NDEBUG
812 // Validate that SPE and FPU are mutually exclusive in codegen
813 if (!MI->isInlineAsm()) {
814 for (const MachineOperand &MO: MI->operands()) {
815 if (MO.isReg()) {
816 Register Reg = MO.getReg();
817 if (Subtarget->hasSPE()) {
818 if (PPC::F4RCRegClass.contains(Reg) ||
819 PPC::F8RCRegClass.contains(Reg) ||
820 PPC::VFRCRegClass.contains(Reg) ||
821 PPC::VRRCRegClass.contains(Reg) ||
822 PPC::VSFRCRegClass.contains(Reg) ||
823 PPC::VSSRCRegClass.contains(Reg)
824 )
825 llvm_unreachable("SPE targets cannot have FPRegs!");
826 } else {
827 if (PPC::SPERCRegClass.contains(Reg))
828 llvm_unreachable("SPE register found in FPU-targeted code!");
829 }
830 }
831 }
832 }
833#endif
834
835 auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
836 ptrdiff_t OriginalOffset) {
837 // Apply an offset to the TOC-based expression such that the adjusted
838 // notional offset from the TOC base (to be encoded into the instruction's D
839 // or DS field) is the signed 16-bit truncation of the original notional
840 // offset from the TOC base.
841 // This is consistent with the treatment used both by XL C/C++ and
842 // by AIX ld -r.
843 ptrdiff_t Adjustment =
844 OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
846 Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
847 };
848
849 auto getTOCEntryLoadingExprForXCOFF =
850 [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
851 this](const MCSymbol *MOSymbol, const MCExpr *Expr,
853 MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * {
854 const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
855 const auto TOCEntryIter = TOC.find({MOSymbol, VK});
856 assert(TOCEntryIter != TOC.end() &&
857 "Could not find the TOC entry for this symbol.");
858 const ptrdiff_t EntryDistanceFromTOCBase =
859 (TOCEntryIter - TOC.begin()) * EntryByteSize;
860 constexpr int16_t PositiveTOCRange = INT16_MAX;
861
862 if (EntryDistanceFromTOCBase > PositiveTOCRange)
863 return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
864
865 return Expr;
866 };
867 auto GetVKForMO = [&](const MachineOperand &MO) {
868 // For TLS initial-exec and local-exec accesses on AIX, we have one TOC
869 // entry for the symbol (with the variable offset), which is differentiated
870 // by MO_TPREL_FLAG.
871 unsigned Flag = MO.getTargetFlags();
872 if (Flag == PPCII::MO_TPREL_FLAG ||
875 assert(MO.isGlobal() && "Only expecting a global MachineOperand here!\n");
876 TLSModel::Model Model = TM.getTLSModel(MO.getGlobal());
877 if (Model == TLSModel::LocalExec)
878 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSLE;
879 if (Model == TLSModel::InitialExec)
880 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSIE;
881 // On AIX, TLS model opt may have turned local-dynamic accesses into
882 // initial-exec accesses.
883 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
884 if (Model == TLSModel::LocalDynamic &&
885 FuncInfo->isAIXFuncUseTLSIEForLD()) {
887 dbgs() << "Current function uses IE access for default LD vars.\n");
888 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSIE;
889 }
890 llvm_unreachable("Only expecting local-exec or initial-exec accesses!");
891 }
892 // For GD TLS access on AIX, we have two TOC entries for the symbol (one for
893 // the variable offset and the other for the region handle). They are
894 // differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG.
895 if (Flag == PPCII::MO_TLSGDM_FLAG)
896 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM;
898 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD;
899 // For local-dynamic TLS access on AIX, we have one TOC entry for the symbol
900 // (the variable offset) and one shared TOC entry for the module handle.
901 // They are differentiated by MO_TLSLD_FLAG and MO_TLSLDM_FLAG.
902 if (Flag == PPCII::MO_TLSLD_FLAG && IsAIX)
903 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSLD;
904 if (Flag == PPCII::MO_TLSLDM_FLAG && IsAIX)
905 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSML;
906 return MCSymbolRefExpr::VariantKind::VK_None;
907 };
908
909 // Lower multi-instruction pseudo operations.
910 switch (MI->getOpcode()) {
911 default: break;
912 case TargetOpcode::DBG_VALUE:
913 llvm_unreachable("Should be handled target independently");
914 case TargetOpcode::STACKMAP:
915 return LowerSTACKMAP(SM, *MI);
916 case TargetOpcode::PATCHPOINT:
917 return LowerPATCHPOINT(SM, *MI);
918
919 case PPC::MoveGOTtoLR: {
920 // Transform %lr = MoveGOTtoLR
921 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
922 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
923 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
924 // blrl
925 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
926 MCSymbol *GOTSymbol =
927 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
928 const MCExpr *OffsExpr =
931 OutContext),
932 MCConstantExpr::create(4, OutContext),
933 OutContext);
934
935 // Emit the 'bl'.
936 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
937 return;
938 }
939 case PPC::MovePCtoLR:
940 case PPC::MovePCtoLR8: {
941 // Transform %lr = MovePCtoLR
942 // Into this, where the label is the PIC base:
943 // bl L1$pb
944 // L1$pb:
945 MCSymbol *PICBase = MF->getPICBaseSymbol();
946
947 // Emit the 'bl'.
948 EmitToStreamer(*OutStreamer,
949 MCInstBuilder(PPC::BL)
950 // FIXME: We would like an efficient form for this, so we
951 // don't have to do a lot of extra uniquing.
952 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
953
954 // Emit the label.
955 OutStreamer->emitLabel(PICBase);
956 return;
957 }
958 case PPC::UpdateGBR: {
959 // Transform %rd = UpdateGBR(%rt, %ri)
960 // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
961 // add %rd, %rt, %ri
962 // or into (if secure plt mode is on):
963 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
964 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
965 // Get the offset from the GOT Base Register to the GOT
966 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
967 if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
968 unsigned PICR = TmpInst.getOperand(0).getReg();
969 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
970 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
971 : ".LTOC");
972 const MCExpr *PB =
973 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
974
975 const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
976 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
977
978 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
979 EmitToStreamer(
980 *OutStreamer,
981 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
982
983 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
984 EmitToStreamer(
985 *OutStreamer,
986 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
987 return;
988 } else {
989 MCSymbol *PICOffset =
990 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
991 TmpInst.setOpcode(PPC::LWZ);
992 const MCExpr *Exp =
994 const MCExpr *PB =
995 MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
997 OutContext);
998 const MCOperand TR = TmpInst.getOperand(1);
999 const MCOperand PICR = TmpInst.getOperand(0);
1000
1001 // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
1002 TmpInst.getOperand(1) =
1004 TmpInst.getOperand(0) = TR;
1005 TmpInst.getOperand(2) = PICR;
1006 EmitToStreamer(*OutStreamer, TmpInst);
1007
1008 TmpInst.setOpcode(PPC::ADD4);
1009 TmpInst.getOperand(0) = PICR;
1010 TmpInst.getOperand(1) = TR;
1011 TmpInst.getOperand(2) = PICR;
1012 EmitToStreamer(*OutStreamer, TmpInst);
1013 return;
1014 }
1015 }
1016 case PPC::LWZtoc: {
1017 // Transform %rN = LWZtoc @op1, %r2
1018 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1019
1020 // Change the opcode to LWZ.
1021 TmpInst.setOpcode(PPC::LWZ);
1022
1023 const MachineOperand &MO = MI->getOperand(1);
1024 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1025 "Invalid operand for LWZtoc.");
1026
1027 // Map the operand to its corresponding MCSymbol.
1028 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1029
1030 // Create a reference to the GOT entry for the symbol. The GOT entry will be
1031 // synthesized later.
1032 if (PL == PICLevel::SmallPIC && !IsAIX) {
1033 const MCExpr *Exp =
1035 OutContext);
1036 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1037 EmitToStreamer(*OutStreamer, TmpInst);
1038 return;
1039 }
1040
1041 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1042
1043 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
1044 // storage allocated in the TOC which contains the address of
1045 // 'MOSymbol'. Said TOC entry will be synthesized later.
1046 MCSymbol *TOCEntry =
1047 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1048 const MCExpr *Exp =
1050
1051 // AIX uses the label directly as the lwz displacement operand for
1052 // references into the toc section. The displacement value will be generated
1053 // relative to the toc-base.
1054 if (IsAIX) {
1055 assert(
1056 getCodeModel(*Subtarget, TM, MO) == CodeModel::Small &&
1057 "This pseudo should only be selected for 32-bit small code model.");
1058 Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK);
1059 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1060
1061 // Print MO for better readability
1062 if (isVerbose())
1063 OutStreamer->getCommentOS() << MO << '\n';
1064 EmitToStreamer(*OutStreamer, TmpInst);
1065 return;
1066 }
1067
1068 // Create an explicit subtract expression between the local symbol and
1069 // '.LTOC' to manifest the toc-relative offset.
1071 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
1072 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
1073 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1074 EmitToStreamer(*OutStreamer, TmpInst);
1075 return;
1076 }
1077 case PPC::ADDItoc:
1078 case PPC::ADDItoc8: {
1079 assert(IsAIX && TM.getCodeModel() == CodeModel::Small &&
1080 "PseudoOp only valid for small code model AIX");
1081
1082 // Transform %rN = ADDItoc/8 %r2, @op1.
1083 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1084
1085 // Change the opcode to load address.
1086 TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8));
1087
1088 const MachineOperand &MO = MI->getOperand(2);
1089 assert(MO.isGlobal() && "Invalid operand for ADDItoc[8].");
1090
1091 // Map the operand to its corresponding MCSymbol.
1092 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1093
1094 const MCExpr *Exp =
1096
1097 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1098 EmitToStreamer(*OutStreamer, TmpInst);
1099 return;
1100 }
1101 case PPC::LDtocJTI:
1102 case PPC::LDtocCPT:
1103 case PPC::LDtocBA:
1104 case PPC::LDtoc: {
1105 // Transform %x3 = LDtoc @min1, %x2
1106 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1107
1108 // Change the opcode to LD.
1109 TmpInst.setOpcode(PPC::LD);
1110
1111 const MachineOperand &MO = MI->getOperand(1);
1112 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1113 "Invalid operand!");
1114
1115 // Map the operand to its corresponding MCSymbol.
1116 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1117
1118 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1119
1120 // Map the machine operand to its corresponding MCSymbol, then map the
1121 // global address operand to be a reference to the TOC entry we will
1122 // synthesize later.
1123 MCSymbol *TOCEntry =
1124 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1125
1128 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext);
1129 TmpInst.getOperand(1) = MCOperand::createExpr(
1130 IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp);
1131
1132 // Print MO for better readability
1133 if (isVerbose() && IsAIX)
1134 OutStreamer->getCommentOS() << MO << '\n';
1135 EmitToStreamer(*OutStreamer, TmpInst);
1136 return;
1137 }
1138 case PPC::ADDIStocHA: {
1139 const MachineOperand &MO = MI->getOperand(2);
1140
1141 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1142 "Invalid operand for ADDIStocHA.");
1143 assert((IsAIX && !IsPPC64 &&
1144 getCodeModel(*Subtarget, TM, MO) == CodeModel::Large) &&
1145 "This pseudo should only be selected for 32-bit large code model on"
1146 " AIX.");
1147
1148 // Transform %rd = ADDIStocHA %rA, @sym(%r2)
1149 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1150
1151 // Change the opcode to ADDIS.
1152 TmpInst.setOpcode(PPC::ADDIS);
1153
1154 // Map the machine operand to its corresponding MCSymbol.
1155 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1156
1157 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1158
1159 // Map the global address operand to be a reference to the TOC entry we
1160 // will synthesize later. 'TOCEntry' is a label used to reference the
1161 // storage allocated in the TOC which contains the address of 'MOSymbol'.
1162 // If the symbol does not have the toc-data attribute, then we create the
1163 // TOC entry on AIX. If the toc-data attribute is used, the TOC entry
1164 // contains the data rather than the address of the MOSymbol.
1165 if (![](const MachineOperand &MO) {
1166 if (!MO.isGlobal())
1167 return false;
1168
1169 const GlobalVariable *GV = dyn_cast<GlobalVariable>(MO.getGlobal());
1170 if (!GV)
1171 return false;
1172 return GV->hasAttribute("toc-data");
1173 }(MO)) {
1174 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1175 }
1176
1178 MOSymbol, MCSymbolRefExpr::VK_PPC_U, OutContext);
1179 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1180 EmitToStreamer(*OutStreamer, TmpInst);
1181 return;
1182 }
1183 case PPC::LWZtocL: {
1184 const MachineOperand &MO = MI->getOperand(1);
1185
1186 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1187 "Invalid operand for LWZtocL.");
1188 assert(IsAIX && !IsPPC64 &&
1189 getCodeModel(*Subtarget, TM, MO) == CodeModel::Large &&
1190 "This pseudo should only be selected for 32-bit large code model on"
1191 " AIX.");
1192
1193 // Transform %rd = LWZtocL @sym, %rs.
1194 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1195
1196 // Change the opcode to lwz.
1197 TmpInst.setOpcode(PPC::LWZ);
1198
1199 // Map the machine operand to its corresponding MCSymbol.
1200 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1201
1202 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1203
1204 // Always use TOC on AIX. Map the global address operand to be a reference
1205 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
1206 // reference the storage allocated in the TOC which contains the address of
1207 // 'MOSymbol'.
1208 MCSymbol *TOCEntry =
1209 lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1210 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
1212 OutContext);
1213 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1214 EmitToStreamer(*OutStreamer, TmpInst);
1215 return;
1216 }
1217 case PPC::ADDIStocHA8: {
1218 // Transform %xd = ADDIStocHA8 %x2, @sym
1219 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1220
1221 // Change the opcode to ADDIS8. If the global address is the address of
1222 // an external symbol, is a jump table address, is a block address, or is a
1223 // constant pool index with large code model enabled, then generate a TOC
1224 // entry and reference that. Otherwise, reference the symbol directly.
1225 TmpInst.setOpcode(PPC::ADDIS8);
1226
1227 const MachineOperand &MO = MI->getOperand(2);
1228 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1229 "Invalid operand for ADDIStocHA8!");
1230
1231 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1232
1233 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1234
1235 const bool GlobalToc =
1236 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
1237
1238 const CodeModel::Model CM =
1239 IsAIX ? getCodeModel(*Subtarget, TM, MO) : TM.getCodeModel();
1240
1241 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
1242 (MO.isCPI() && CM == CodeModel::Large))
1243 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1244
1246
1247 const MCExpr *Exp =
1248 MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1249
1250 if (!MO.isJTI() && MO.getOffset())
1253 OutContext),
1254 OutContext);
1255
1256 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1257 EmitToStreamer(*OutStreamer, TmpInst);
1258 return;
1259 }
1260 case PPC::LDtocL: {
1261 // Transform %xd = LDtocL @sym, %xs
1262 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1263
1264 // Change the opcode to LD. If the global address is the address of
1265 // an external symbol, is a jump table address, is a block address, or is
1266 // a constant pool index with large code model enabled, then generate a
1267 // TOC entry and reference that. Otherwise, reference the symbol directly.
1268 TmpInst.setOpcode(PPC::LD);
1269
1270 const MachineOperand &MO = MI->getOperand(1);
1271 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
1272 MO.isBlockAddress()) &&
1273 "Invalid operand for LDtocL!");
1274
1276 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1277 "LDtocL used on symbol that could be accessed directly is "
1278 "invalid. Must match ADDIStocHA8."));
1279
1280 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1281
1282 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1283 CodeModel::Model CM =
1284 IsAIX ? getCodeModel(*Subtarget, TM, MO) : TM.getCodeModel();
1285 if (!MO.isCPI() || CM == CodeModel::Large)
1286 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, getTOCEntryTypeForMO(MO), VK);
1287
1289 const MCExpr *Exp =
1290 MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1291 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1292 EmitToStreamer(*OutStreamer, TmpInst);
1293 return;
1294 }
1295 case PPC::ADDItocL:
1296 case PPC::ADDItocL8: {
1297 // Transform %xd = ADDItocL %xs, @sym
1298 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1299
1300 unsigned Op = MI->getOpcode();
1301
1302 // Change the opcode to load address for toc-data.
1303 // ADDItocL is only used for 32-bit toc-data on AIX and will always use LA.
1304 TmpInst.setOpcode(Op == PPC::ADDItocL8 ? (IsAIX ? PPC::LA8 : PPC::ADDI8)
1305 : PPC::LA);
1306
1307 const MachineOperand &MO = MI->getOperand(2);
1308 assert((Op == PPC::ADDItocL8)
1309 ? (MO.isGlobal() || MO.isCPI())
1310 : MO.isGlobal() && "Invalid operand for ADDItocL8.");
1311 assert(!(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1312 "Interposable definitions must use indirect accesses.");
1313
1314 // Map the operand to its corresponding MCSymbol.
1315 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1316
1318 MOSymbol,
1320 OutContext);
1321
1322 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1323 EmitToStreamer(*OutStreamer, TmpInst);
1324 return;
1325 }
1326 case PPC::ADDISgotTprelHA: {
1327 // Transform: %xd = ADDISgotTprelHA %x2, @sym
1328 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1329 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1330 const MachineOperand &MO = MI->getOperand(2);
1331 const GlobalValue *GValue = MO.getGlobal();
1332 MCSymbol *MOSymbol = getSymbol(GValue);
1333 const MCExpr *SymGotTprel =
1335 OutContext);
1336 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1337 .addReg(MI->getOperand(0).getReg())
1338 .addReg(MI->getOperand(1).getReg())
1339 .addExpr(SymGotTprel));
1340 return;
1341 }
1342 case PPC::LDgotTprelL:
1343 case PPC::LDgotTprelL32: {
1344 // Transform %xd = LDgotTprelL @sym, %xs
1345 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1346
1347 // Change the opcode to LD.
1348 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
1349 const MachineOperand &MO = MI->getOperand(1);
1350 const GlobalValue *GValue = MO.getGlobal();
1351 MCSymbol *MOSymbol = getSymbol(GValue);
1353 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
1355 OutContext);
1356 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1357 EmitToStreamer(*OutStreamer, TmpInst);
1358 return;
1359 }
1360
1361 case PPC::PPC32PICGOT: {
1362 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1363 MCSymbol *GOTRef = OutContext.createTempSymbol();
1364 MCSymbol *NextInstr = OutContext.createTempSymbol();
1365
1366 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
1367 // FIXME: We would like an efficient form for this, so we don't have to do
1368 // a lot of extra uniquing.
1369 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
1370 const MCExpr *OffsExpr =
1371 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
1372 MCSymbolRefExpr::create(GOTRef, OutContext),
1373 OutContext);
1374 OutStreamer->emitLabel(GOTRef);
1375 OutStreamer->emitValue(OffsExpr, 4);
1376 OutStreamer->emitLabel(NextInstr);
1377 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
1378 .addReg(MI->getOperand(0).getReg()));
1379 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
1380 .addReg(MI->getOperand(1).getReg())
1381 .addImm(0)
1382 .addReg(MI->getOperand(0).getReg()));
1383 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
1384 .addReg(MI->getOperand(0).getReg())
1385 .addReg(MI->getOperand(1).getReg())
1386 .addReg(MI->getOperand(0).getReg()));
1387 return;
1388 }
1389 case PPC::PPC32GOT: {
1390 MCSymbol *GOTSymbol =
1391 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1392 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1393 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1394 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1395 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1396 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1397 .addReg(MI->getOperand(0).getReg())
1398 .addExpr(SymGotTlsL));
1399 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1400 .addReg(MI->getOperand(0).getReg())
1401 .addReg(MI->getOperand(0).getReg())
1402 .addExpr(SymGotTlsHA));
1403 return;
1404 }
1405 case PPC::ADDIStlsgdHA: {
1406 // Transform: %xd = ADDIStlsgdHA %x2, @sym
1407 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1408 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1409 const MachineOperand &MO = MI->getOperand(2);
1410 const GlobalValue *GValue = MO.getGlobal();
1411 MCSymbol *MOSymbol = getSymbol(GValue);
1412 const MCExpr *SymGotTlsGD =
1414 OutContext);
1415 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1416 .addReg(MI->getOperand(0).getReg())
1417 .addReg(MI->getOperand(1).getReg())
1418 .addExpr(SymGotTlsGD));
1419 return;
1420 }
1421 case PPC::ADDItlsgdL:
1422 // Transform: %xd = ADDItlsgdL %xs, @sym
1423 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l
1424 case PPC::ADDItlsgdL32: {
1425 // Transform: %rd = ADDItlsgdL32 %rs, @sym
1426 // Into: %rd = ADDI %rs, sym@got@tlsgd
1427 const MachineOperand &MO = MI->getOperand(2);
1428 const GlobalValue *GValue = MO.getGlobal();
1429 MCSymbol *MOSymbol = getSymbol(GValue);
1430 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1431 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1433 OutContext);
1434 EmitToStreamer(*OutStreamer,
1435 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1436 .addReg(MI->getOperand(0).getReg())
1437 .addReg(MI->getOperand(1).getReg())
1438 .addExpr(SymGotTlsGD));
1439 return;
1440 }
1441 case PPC::GETtlsMOD32AIX:
1442 case PPC::GETtlsMOD64AIX:
1443 // Transform: %r3 = GETtlsMODNNAIX %r3 (for NN == 32/64).
1444 // Into: BLA .__tls_get_mod()
1445 // Input parameter is a module handle (_$TLSML[TC]@ml) for all variables.
1446 case PPC::GETtlsADDR:
1447 // Transform: %x3 = GETtlsADDR %x3, @sym
1448 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1449 case PPC::GETtlsADDRPCREL:
1450 case PPC::GETtlsADDR32AIX:
1451 case PPC::GETtlsADDR64AIX:
1452 // Transform: %r3 = GETtlsADDRNNAIX %r3, %r4 (for NN == 32/64).
1453 // Into: BLA .__tls_get_addr()
1454 // Unlike on Linux, there is no symbol or relocation needed for this call.
1455 case PPC::GETtlsADDR32: {
1456 // Transform: %r3 = GETtlsADDR32 %r3, @sym
1457 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1458 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1459 return;
1460 }
1461 case PPC::GETtlsTpointer32AIX: {
1462 // Transform: %r3 = GETtlsTpointer32AIX
1463 // Into: BLA .__get_tpointer()
1464 EmitAIXTlsCallHelper(MI);
1465 return;
1466 }
1467 case PPC::ADDIStlsldHA: {
1468 // Transform: %xd = ADDIStlsldHA %x2, @sym
1469 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha
1470 assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1471 const MachineOperand &MO = MI->getOperand(2);
1472 const GlobalValue *GValue = MO.getGlobal();
1473 MCSymbol *MOSymbol = getSymbol(GValue);
1474 const MCExpr *SymGotTlsLD =
1476 OutContext);
1477 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1478 .addReg(MI->getOperand(0).getReg())
1479 .addReg(MI->getOperand(1).getReg())
1480 .addExpr(SymGotTlsLD));
1481 return;
1482 }
1483 case PPC::ADDItlsldL:
1484 // Transform: %xd = ADDItlsldL %xs, @sym
1485 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l
1486 case PPC::ADDItlsldL32: {
1487 // Transform: %rd = ADDItlsldL32 %rs, @sym
1488 // Into: %rd = ADDI %rs, sym@got@tlsld
1489 const MachineOperand &MO = MI->getOperand(2);
1490 const GlobalValue *GValue = MO.getGlobal();
1491 MCSymbol *MOSymbol = getSymbol(GValue);
1492 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1493 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1495 OutContext);
1496 EmitToStreamer(*OutStreamer,
1497 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1498 .addReg(MI->getOperand(0).getReg())
1499 .addReg(MI->getOperand(1).getReg())
1500 .addExpr(SymGotTlsLD));
1501 return;
1502 }
1503 case PPC::GETtlsldADDR:
1504 // Transform: %x3 = GETtlsldADDR %x3, @sym
1505 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1506 case PPC::GETtlsldADDRPCREL:
1507 case PPC::GETtlsldADDR32: {
1508 // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1509 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1510 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1511 return;
1512 }
1513 case PPC::ADDISdtprelHA:
1514 // Transform: %xd = ADDISdtprelHA %xs, @sym
1515 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha
1516 case PPC::ADDISdtprelHA32: {
1517 // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1518 // Into: %rd = ADDIS %rs, sym@dtprel@ha
1519 const MachineOperand &MO = MI->getOperand(2);
1520 const GlobalValue *GValue = MO.getGlobal();
1521 MCSymbol *MOSymbol = getSymbol(GValue);
1522 const MCExpr *SymDtprel =
1524 OutContext);
1525 EmitToStreamer(
1526 *OutStreamer,
1527 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1528 .addReg(MI->getOperand(0).getReg())
1529 .addReg(MI->getOperand(1).getReg())
1530 .addExpr(SymDtprel));
1531 return;
1532 }
1533 case PPC::PADDIdtprel: {
1534 // Transform: %rd = PADDIdtprel %rs, @sym
1535 // Into: %rd = PADDI8 %rs, sym@dtprel
1536 const MachineOperand &MO = MI->getOperand(2);
1537 const GlobalValue *GValue = MO.getGlobal();
1538 MCSymbol *MOSymbol = getSymbol(GValue);
1539 const MCExpr *SymDtprel = MCSymbolRefExpr::create(
1540 MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext);
1541 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8)
1542 .addReg(MI->getOperand(0).getReg())
1543 .addReg(MI->getOperand(1).getReg())
1544 .addExpr(SymDtprel));
1545 return;
1546 }
1547
1548 case PPC::ADDIdtprelL:
1549 // Transform: %xd = ADDIdtprelL %xs, @sym
1550 // Into: %xd = ADDI8 %xs, sym@dtprel@l
1551 case PPC::ADDIdtprelL32: {
1552 // Transform: %rd = ADDIdtprelL32 %rs, @sym
1553 // Into: %rd = ADDI %rs, sym@dtprel@l
1554 const MachineOperand &MO = MI->getOperand(2);
1555 const GlobalValue *GValue = MO.getGlobal();
1556 MCSymbol *MOSymbol = getSymbol(GValue);
1557 const MCExpr *SymDtprel =
1559 OutContext);
1560 EmitToStreamer(*OutStreamer,
1561 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1562 .addReg(MI->getOperand(0).getReg())
1563 .addReg(MI->getOperand(1).getReg())
1564 .addExpr(SymDtprel));
1565 return;
1566 }
1567 case PPC::MFOCRF:
1568 case PPC::MFOCRF8:
1569 if (!Subtarget->hasMFOCRF()) {
1570 // Transform: %r3 = MFOCRF %cr7
1571 // Into: %r3 = MFCR ;; cr7
1572 unsigned NewOpcode =
1573 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1574 OutStreamer->AddComment(PPCInstPrinter::
1575 getRegisterName(MI->getOperand(1).getReg()));
1576 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1577 .addReg(MI->getOperand(0).getReg()));
1578 return;
1579 }
1580 break;
1581 case PPC::MTOCRF:
1582 case PPC::MTOCRF8:
1583 if (!Subtarget->hasMFOCRF()) {
1584 // Transform: %cr7 = MTOCRF %r3
1585 // Into: MTCRF mask, %r3 ;; cr7
1586 unsigned NewOpcode =
1587 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1588 unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1589 ->getEncodingValue(MI->getOperand(0).getReg());
1590 OutStreamer->AddComment(PPCInstPrinter::
1591 getRegisterName(MI->getOperand(0).getReg()));
1592 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1593 .addImm(Mask)
1594 .addReg(MI->getOperand(1).getReg()));
1595 return;
1596 }
1597 break;
1598 case PPC::LD:
1599 case PPC::STD:
1600 case PPC::LWA_32:
1601 case PPC::LWA: {
1602 // Verify alignment is legal, so we don't create relocations
1603 // that can't be supported.
1604 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1605 // For non-TOC-based local-exec TLS accesses with non-zero offsets, the
1606 // machine operand (which is a TargetGlobalTLSAddress) is expected to be
1607 // the same operand for both loads and stores.
1608 for (const MachineOperand &TempMO : MI->operands()) {
1609 if (((TempMO.getTargetFlags() == PPCII::MO_TPREL_FLAG ||
1610 TempMO.getTargetFlags() == PPCII::MO_TLSLD_FLAG)) &&
1611 TempMO.getOperandNo() == 1)
1612 OpNum = 1;
1613 }
1614 const MachineOperand &MO = MI->getOperand(OpNum);
1615 if (MO.isGlobal()) {
1616 const DataLayout &DL = MO.getGlobal()->getDataLayout();
1617 if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1618 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1619 }
1620 // As these load/stores share common code with the following load/stores,
1621 // fall through to the subsequent cases in order to either process the
1622 // non-TOC-based local-exec sequence or to process the instruction normally.
1623 [[fallthrough]];
1624 }
1625 case PPC::LBZ:
1626 case PPC::LBZ8:
1627 case PPC::LHA:
1628 case PPC::LHA8:
1629 case PPC::LHZ:
1630 case PPC::LHZ8:
1631 case PPC::LWZ:
1632 case PPC::LWZ8:
1633 case PPC::STB:
1634 case PPC::STB8:
1635 case PPC::STH:
1636 case PPC::STH8:
1637 case PPC::STW:
1638 case PPC::STW8:
1639 case PPC::LFS:
1640 case PPC::STFS:
1641 case PPC::LFD:
1642 case PPC::STFD:
1643 case PPC::ADDI8: {
1644 // A faster non-TOC-based local-[exec|dynamic] sequence is represented by
1645 // `addi` or a load/store instruction (that directly loads or stores off of
1646 // the thread pointer) with an immediate operand having the
1647 // [MO_TPREL_FLAG|MO_TLSLD_FLAG]. Such instructions do not otherwise arise.
1648 if (!HasAIXSmallLocalTLS)
1649 break;
1650 bool IsMIADDI8 = MI->getOpcode() == PPC::ADDI8;
1651 unsigned OpNum = IsMIADDI8 ? 2 : 1;
1652 const MachineOperand &MO = MI->getOperand(OpNum);
1653 unsigned Flag = MO.getTargetFlags();
1654 if (Flag == PPCII::MO_TPREL_FLAG ||
1657 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1658
1659 const MCExpr *Expr = getAdjustedFasterLocalExpr(MO, MO.getOffset());
1660 if (Expr)
1661 TmpInst.getOperand(OpNum) = MCOperand::createExpr(Expr);
1662
1663 // Change the opcode to load address if the original opcode is an `addi`.
1664 if (IsMIADDI8)
1665 TmpInst.setOpcode(PPC::LA8);
1666
1667 EmitToStreamer(*OutStreamer, TmpInst);
1668 return;
1669 }
1670 // Now process the instruction normally.
1671 break;
1672 }
1673 case PPC::PseudoEIEIO: {
1674 EmitToStreamer(
1675 *OutStreamer,
1676 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1677 EmitToStreamer(
1678 *OutStreamer,
1679 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1680 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::EnforceIEIO));
1681 return;
1682 }
1683 }
1684
1685 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1686 EmitToStreamer(*OutStreamer, TmpInst);
1687}
1688
1689// For non-TOC-based local-[exec|dynamic] variables that have a non-zero offset,
1690// we need to create a new MCExpr that adds the non-zero offset to the address
1691// of the local-[exec|dynamic] variable that will be used in either an addi,
1692// load or store. However, the final displacement for these instructions must be
1693// between [-32768, 32768), so if the TLS address + its non-zero offset is
1694// greater than 32KB, a new MCExpr is produced to accommodate this situation.
1695const MCExpr *
1696PPCAsmPrinter::getAdjustedFasterLocalExpr(const MachineOperand &MO,
1697 int64_t Offset) {
1698 // Non-zero offsets (for loads, stores or `addi`) require additional handling.
1699 // When the offset is zero, there is no need to create an adjusted MCExpr.
1700 if (!Offset)
1701 return nullptr;
1702
1703 assert(MO.isGlobal() && "Only expecting a global MachineOperand here!");
1704 const GlobalValue *GValue = MO.getGlobal();
1705 TLSModel::Model Model = TM.getTLSModel(GValue);
1706 assert((Model == TLSModel::LocalExec || Model == TLSModel::LocalDynamic) &&
1707 "Only local-[exec|dynamic] accesses are handled!");
1708
1709 bool IsGlobalADeclaration = GValue->isDeclarationForLinker();
1710 // Find the GlobalVariable that corresponds to the particular TLS variable
1711 // in the TLS variable-to-address mapping. All TLS variables should exist
1712 // within this map, with the exception of TLS variables marked as extern.
1713 const auto TLSVarsMapEntryIter = TLSVarsToAddressMapping.find(GValue);
1714 if (TLSVarsMapEntryIter == TLSVarsToAddressMapping.end())
1715 assert(IsGlobalADeclaration &&
1716 "Only expecting to find extern TLS variables not present in the TLS "
1717 "variable-to-address map!");
1718
1719 unsigned TLSVarAddress =
1720 IsGlobalADeclaration ? 0 : TLSVarsMapEntryIter->second;
1721 ptrdiff_t FinalAddress = (TLSVarAddress + Offset);
1722 // If the address of the TLS variable + the offset is less than 32KB,
1723 // or if the TLS variable is extern, we simply produce an MCExpr to add the
1724 // non-zero offset to the TLS variable address.
1725 // For when TLS variables are extern, this is safe to do because we can
1726 // assume that the address of extern TLS variables are zero.
1727 const MCExpr *Expr = MCSymbolRefExpr::create(
1728 getSymbol(GValue),
1731 OutContext);
1733 Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
1734 if (FinalAddress >= 32768) {
1735 // Handle the written offset for cases where:
1736 // TLS variable address + Offset > 32KB.
1737
1738 // The assembly that is printed will look like:
1739 // TLSVar@le + Offset - Delta
1740 // where Delta is a multiple of 64KB: ((FinalAddress + 32768) & ~0xFFFF).
1741 ptrdiff_t Delta = ((FinalAddress + 32768) & ~0xFFFF);
1742 // Check that the total instruction displacement fits within [-32768,32768).
1743 [[maybe_unused]] ptrdiff_t InstDisp = TLSVarAddress + Offset - Delta;
1744 assert(
1745 ((InstDisp < 32768) && (InstDisp >= -32768)) &&
1746 "Expecting the instruction displacement for local-[exec|dynamic] TLS "
1747 "variables to be between [-32768, 32768)!");
1749 Expr, MCConstantExpr::create(-Delta, OutContext), OutContext);
1750 }
1751
1752 return Expr;
1753}
1754
1755void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) {
1756 // Emit float ABI into GNU attribute
1757 Metadata *MD = M.getModuleFlag("float-abi");
1758 MDString *FloatABI = dyn_cast_or_null<MDString>(MD);
1759 if (!FloatABI)
1760 return;
1761 StringRef flt = FloatABI->getString();
1762 // TODO: Support emitting soft-fp and hard double/single attributes.
1763 if (flt == "doubledouble")
1764 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1765 Val_GNU_Power_ABI_HardFloat_DP |
1766 Val_GNU_Power_ABI_LDBL_IBM128);
1767 else if (flt == "ieeequad")
1768 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1769 Val_GNU_Power_ABI_HardFloat_DP |
1770 Val_GNU_Power_ABI_LDBL_IEEE128);
1771 else if (flt == "ieeedouble")
1772 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1773 Val_GNU_Power_ABI_HardFloat_DP |
1774 Val_GNU_Power_ABI_LDBL_64);
1775}
1776
1777void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1778 if (!Subtarget->isPPC64())
1779 return PPCAsmPrinter::emitInstruction(MI);
1780
1781 switch (MI->getOpcode()) {
1782 default:
1783 return PPCAsmPrinter::emitInstruction(MI);
1784 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1785 // .begin:
1786 // b .end # lis 0, FuncId[16..32]
1787 // nop # li 0, FuncId[0..15]
1788 // std 0, -8(1)
1789 // mflr 0
1790 // bl __xray_FunctionEntry
1791 // mtlr 0
1792 // .end:
1793 //
1794 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1795 // of instructions change.
1796 MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1797 MCSymbol *EndOfSled = OutContext.createTempSymbol();
1798 OutStreamer->emitLabel(BeginOfSled);
1799 EmitToStreamer(*OutStreamer,
1800 MCInstBuilder(PPC::B).addExpr(
1801 MCSymbolRefExpr::create(EndOfSled, OutContext)));
1802 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1803 EmitToStreamer(
1804 *OutStreamer,
1805 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1806 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1807 EmitToStreamer(*OutStreamer,
1808 MCInstBuilder(PPC::BL8_NOP)
1809 .addExpr(MCSymbolRefExpr::create(
1810 OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1811 OutContext)));
1812 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1813 OutStreamer->emitLabel(EndOfSled);
1814 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1815 break;
1816 }
1817 case TargetOpcode::PATCHABLE_RET: {
1818 unsigned RetOpcode = MI->getOperand(0).getImm();
1819 MCInst RetInst;
1820 RetInst.setOpcode(RetOpcode);
1821 for (const auto &MO : llvm::drop_begin(MI->operands())) {
1822 MCOperand MCOp;
1823 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1824 RetInst.addOperand(MCOp);
1825 }
1826
1827 bool IsConditional;
1828 if (RetOpcode == PPC::BCCLR) {
1829 IsConditional = true;
1830 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1831 RetOpcode == PPC::TCRETURNai8) {
1832 break;
1833 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1834 IsConditional = false;
1835 } else {
1836 EmitToStreamer(*OutStreamer, RetInst);
1837 break;
1838 }
1839
1840 MCSymbol *FallthroughLabel;
1841 if (IsConditional) {
1842 // Before:
1843 // bgtlr cr0
1844 //
1845 // After:
1846 // ble cr0, .end
1847 // .p2align 3
1848 // .begin:
1849 // blr # lis 0, FuncId[16..32]
1850 // nop # li 0, FuncId[0..15]
1851 // std 0, -8(1)
1852 // mflr 0
1853 // bl __xray_FunctionExit
1854 // mtlr 0
1855 // blr
1856 // .end:
1857 //
1858 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1859 // of instructions change.
1860 FallthroughLabel = OutContext.createTempSymbol();
1861 EmitToStreamer(
1862 *OutStreamer,
1863 MCInstBuilder(PPC::BCC)
1864 .addImm(PPC::InvertPredicate(
1865 static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1866 .addReg(MI->getOperand(2).getReg())
1867 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1868 RetInst = MCInst();
1869 RetInst.setOpcode(PPC::BLR8);
1870 }
1871 // .p2align 3
1872 // .begin:
1873 // b(lr)? # lis 0, FuncId[16..32]
1874 // nop # li 0, FuncId[0..15]
1875 // std 0, -8(1)
1876 // mflr 0
1877 // bl __xray_FunctionExit
1878 // mtlr 0
1879 // b(lr)?
1880 //
1881 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1882 // of instructions change.
1883 OutStreamer->emitCodeAlignment(Align(8), &getSubtargetInfo());
1884 MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1885 OutStreamer->emitLabel(BeginOfSled);
1886 EmitToStreamer(*OutStreamer, RetInst);
1887 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1888 EmitToStreamer(
1889 *OutStreamer,
1890 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1891 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1892 EmitToStreamer(*OutStreamer,
1893 MCInstBuilder(PPC::BL8_NOP)
1894 .addExpr(MCSymbolRefExpr::create(
1895 OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1896 OutContext)));
1897 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1898 EmitToStreamer(*OutStreamer, RetInst);
1899 if (IsConditional)
1900 OutStreamer->emitLabel(FallthroughLabel);
1901 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1902 break;
1903 }
1904 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1905 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1906 case TargetOpcode::PATCHABLE_TAIL_CALL:
1907 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1908 // normal function exit from a tail exit.
1909 llvm_unreachable("Tail call is handled in the normal case. See comments "
1910 "around this assert.");
1911 }
1912}
1913
1914void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1915 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1916 PPCTargetStreamer *TS =
1917 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1918 TS->emitAbiVersion(2);
1919 }
1920
1921 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1922 !isPositionIndependent())
1924
1925 if (M.getPICLevel() == PICLevel::SmallPIC)
1927
1928 OutStreamer->switchSection(OutContext.getELFSection(
1930
1931 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1932 MCSymbol *CurrentPos = OutContext.createTempSymbol();
1933
1934 OutStreamer->emitLabel(CurrentPos);
1935
1936 // The GOT pointer points to the middle of the GOT, in order to reference the
1937 // entire 64kB range. 0x8000 is the midpoint.
1938 const MCExpr *tocExpr =
1939 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1940 MCConstantExpr::create(0x8000, OutContext),
1941 OutContext);
1942
1943 OutStreamer->emitAssignment(TOCSym, tocExpr);
1944
1945 OutStreamer->switchSection(getObjFileLowering().getTextSection());
1946}
1947
1948void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1949 // linux/ppc32 - Normal entry label.
1950 if (!Subtarget->isPPC64() &&
1951 (!isPositionIndependent() ||
1952 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1954
1955 if (!Subtarget->isPPC64()) {
1956 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1957 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1958 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1959 MCSymbol *PICBase = MF->getPICBaseSymbol();
1960 OutStreamer->emitLabel(RelocSymbol);
1961
1962 const MCExpr *OffsExpr =
1964 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1965 OutContext),
1966 MCSymbolRefExpr::create(PICBase, OutContext),
1967 OutContext);
1968 OutStreamer->emitValue(OffsExpr, 4);
1969 OutStreamer->emitLabel(CurrentFnSym);
1970 return;
1971 } else
1973 }
1974
1975 // ELFv2 ABI - Normal entry label.
1976 if (Subtarget->isELFv2ABI()) {
1977 // In the Large code model, we allow arbitrary displacements between
1978 // the text section and its associated TOC section. We place the
1979 // full 8-byte offset to the TOC in memory immediately preceding
1980 // the function global entry point.
1981 if (TM.getCodeModel() == CodeModel::Large
1982 && !MF->getRegInfo().use_empty(PPC::X2)) {
1983 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1984
1985 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1986 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1987 const MCExpr *TOCDeltaExpr =
1988 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1989 MCSymbolRefExpr::create(GlobalEPSymbol,
1990 OutContext),
1991 OutContext);
1992
1993 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1994 OutStreamer->emitValue(TOCDeltaExpr, 8);
1995 }
1997 }
1998
1999 // Emit an official procedure descriptor.
2000 MCSectionSubPair Current = OutStreamer->getCurrentSection();
2001 MCSectionELF *Section = OutStreamer->getContext().getELFSection(
2003 OutStreamer->switchSection(Section);
2004 OutStreamer->emitLabel(CurrentFnSym);
2005 OutStreamer->emitValueToAlignment(Align(8));
2006 MCSymbol *Symbol1 = CurrentFnSymForSize;
2007 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
2008 // entry point.
2009 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
2010 8 /*size*/);
2011 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
2012 // Generates a R_PPC64_TOC relocation for TOC base insertion.
2013 OutStreamer->emitValue(
2015 8/*size*/);
2016 // Emit a null environment pointer.
2017 OutStreamer->emitIntValue(0, 8 /* size */);
2018 OutStreamer->switchSection(Current.first, Current.second);
2019}
2020
2021void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
2022 const DataLayout &DL = getDataLayout();
2023
2024 bool isPPC64 = DL.getPointerSizeInBits() == 64;
2025
2026 PPCTargetStreamer *TS =
2027 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2028
2029 // If we are using any values provided by Glibc at fixed addresses,
2030 // we need to ensure that the Glibc used at link time actually provides
2031 // those values. All versions of Glibc that do will define the symbol
2032 // named "__parse_hwcap_and_convert_at_platform".
2033 if (static_cast<const PPCTargetMachine &>(TM).hasGlibcHWCAPAccess())
2034 OutStreamer->emitSymbolValue(
2035 GetExternalSymbolSymbol("__parse_hwcap_and_convert_at_platform"),
2036 MAI->getCodePointerSize());
2037 emitGNUAttributes(M);
2038
2039 if (!TOC.empty()) {
2040 const char *Name = isPPC64 ? ".toc" : ".got2";
2041 MCSectionELF *Section = OutContext.getELFSection(
2043 OutStreamer->switchSection(Section);
2044 if (!isPPC64)
2045 OutStreamer->emitValueToAlignment(Align(4));
2046
2047 for (const auto &TOCMapPair : TOC) {
2048 const MCSymbol *const TOCEntryTarget = TOCMapPair.first.first;
2049 MCSymbol *const TOCEntryLabel = TOCMapPair.second;
2050
2051 OutStreamer->emitLabel(TOCEntryLabel);
2052 if (isPPC64)
2053 TS->emitTCEntry(*TOCEntryTarget, TOCMapPair.first.second);
2054 else
2055 OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
2056 }
2057 }
2058
2059 PPCAsmPrinter::emitEndOfAsmFile(M);
2060}
2061
2062/// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
2063void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
2064 // In the ELFv2 ABI, in functions that use the TOC register, we need to
2065 // provide two entry points. The ABI guarantees that when calling the
2066 // local entry point, r2 is set up by the caller to contain the TOC base
2067 // for this function, and when calling the global entry point, r12 is set
2068 // up by the caller to hold the address of the global entry point. We
2069 // thus emit a prefix sequence along the following lines:
2070 //
2071 // func:
2072 // .Lfunc_gepNN:
2073 // # global entry point
2074 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
2075 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l
2076 // .Lfunc_lepNN:
2077 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
2078 // # local entry point, followed by function body
2079 //
2080 // For the Large code model, we create
2081 //
2082 // .Lfunc_tocNN:
2083 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel
2084 // func:
2085 // .Lfunc_gepNN:
2086 // # global entry point
2087 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
2088 // add r2,r2,r12
2089 // .Lfunc_lepNN:
2090 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
2091 // # local entry point, followed by function body
2092 //
2093 // This ensures we have r2 set up correctly while executing the function
2094 // body, no matter which entry point is called.
2095 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
2096 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
2097 !MF->getRegInfo().use_empty(PPC::R2);
2098 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
2099 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
2100 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
2101 Subtarget->isELFv2ABI() && UsesX2OrR2;
2102
2103 // Only do all that if the function uses R2 as the TOC pointer
2104 // in the first place. We don't need the global entry point if the
2105 // function uses R2 as an allocatable register.
2106 if (NonPCrelGEPRequired || PCrelGEPRequired) {
2107 // Note: The logic here must be synchronized with the code in the
2108 // branch-selection pass which sets the offset of the first block in the
2109 // function. This matters because it affects the alignment.
2110 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
2111 OutStreamer->emitLabel(GlobalEntryLabel);
2112 const MCSymbolRefExpr *GlobalEntryLabelExp =
2113 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
2114
2115 if (TM.getCodeModel() != CodeModel::Large) {
2116 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
2117 const MCExpr *TOCDeltaExpr =
2118 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
2119 GlobalEntryLabelExp, OutContext);
2120
2121 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
2122 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
2123 .addReg(PPC::X2)
2124 .addReg(PPC::X12)
2125 .addExpr(TOCDeltaHi));
2126
2127 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
2128 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
2129 .addReg(PPC::X2)
2130 .addReg(PPC::X2)
2131 .addExpr(TOCDeltaLo));
2132 } else {
2133 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
2134 const MCExpr *TOCOffsetDeltaExpr =
2135 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
2136 GlobalEntryLabelExp, OutContext);
2137
2138 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
2139 .addReg(PPC::X2)
2140 .addExpr(TOCOffsetDeltaExpr)
2141 .addReg(PPC::X12));
2142 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
2143 .addReg(PPC::X2)
2144 .addReg(PPC::X2)
2145 .addReg(PPC::X12));
2146 }
2147
2148 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
2149 OutStreamer->emitLabel(LocalEntryLabel);
2150 const MCSymbolRefExpr *LocalEntryLabelExp =
2151 MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
2152 const MCExpr *LocalOffsetExp =
2153 MCBinaryExpr::createSub(LocalEntryLabelExp,
2154 GlobalEntryLabelExp, OutContext);
2155
2156 PPCTargetStreamer *TS =
2157 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2158 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
2159 } else if (Subtarget->isUsingPCRelativeCalls()) {
2160 // When generating the entry point for a function we have a few scenarios
2161 // based on whether or not that function uses R2 and whether or not that
2162 // function makes calls (or is a leaf function).
2163 // 1) A leaf function that does not use R2 (or treats it as callee-saved
2164 // and preserves it). In this case st_other=0 and both
2165 // the local and global entry points for the function are the same.
2166 // No special entry point code is required.
2167 // 2) A function uses the TOC pointer R2. This function may or may not have
2168 // calls. In this case st_other=[2,6] and the global and local entry
2169 // points are different. Code to correctly setup the TOC pointer in R2
2170 // is put between the global and local entry points. This case is
2171 // covered by the if statatement above.
2172 // 3) A function does not use the TOC pointer R2 but does have calls.
2173 // In this case st_other=1 since we do not know whether or not any
2174 // of the callees clobber R2. This case is dealt with in this else if
2175 // block. Tail calls are considered calls and the st_other should also
2176 // be set to 1 in that case as well.
2177 // 4) The function does not use the TOC pointer but R2 is used inside
2178 // the function. In this case st_other=1 once again.
2179 // 5) This function uses inline asm. We mark R2 as reserved if the function
2180 // has inline asm as we have to assume that it may be used.
2181 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
2182 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
2183 PPCTargetStreamer *TS =
2184 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2185 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
2186 MCConstantExpr::create(1, OutContext));
2187 }
2188 }
2189}
2190
2191/// EmitFunctionBodyEnd - Print the traceback table before the .size
2192/// directive.
2193///
2194void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
2195 // Only the 64-bit target requires a traceback table. For now,
2196 // we only emit the word of zeroes that GDB requires to find
2197 // the end of the function, and zeroes for the eight-byte
2198 // mandatory fields.
2199 // FIXME: We should fill in the eight-byte mandatory fields as described in
2200 // the PPC64 ELF ABI (this is a low-priority item because GDB does not
2201 // currently make use of these fields).
2202 if (Subtarget->isPPC64()) {
2203 OutStreamer->emitIntValue(0, 4/*size*/);
2204 OutStreamer->emitIntValue(0, 8/*size*/);
2205 }
2206}
2207
2208void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
2209 MCSymbol *GVSym) const {
2210
2211 assert(MAI->hasVisibilityOnlyWithLinkage() &&
2212 "AIX's linkage directives take a visibility setting.");
2213
2214 MCSymbolAttr LinkageAttr = MCSA_Invalid;
2215 switch (GV->getLinkage()) {
2217 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
2218 break;
2224 LinkageAttr = MCSA_Weak;
2225 break;
2227 LinkageAttr = MCSA_Extern;
2228 break;
2230 return;
2233 "InternalLinkage should not have other visibility setting.");
2234 LinkageAttr = MCSA_LGlobal;
2235 break;
2237 llvm_unreachable("Should never emit this");
2239 llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
2240 }
2241
2242 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
2243
2244 MCSymbolAttr VisibilityAttr = MCSA_Invalid;
2245 if (!TM.getIgnoreXCOFFVisibility()) {
2248 "Cannot not be both dllexport and non-default visibility");
2249 switch (GV->getVisibility()) {
2250
2251 // TODO: "internal" Visibility needs to go here.
2253 if (GV->hasDLLExportStorageClass())
2254 VisibilityAttr = MAI->getExportedVisibilityAttr();
2255 break;
2257 VisibilityAttr = MAI->getHiddenVisibilityAttr();
2258 break;
2260 VisibilityAttr = MAI->getProtectedVisibilityAttr();
2261 break;
2262 }
2263 }
2264
2265 // Do not emit the _$TLSML symbol.
2266 if (GV->getThreadLocalMode() == GlobalVariable::LocalDynamicTLSModel &&
2267 GV->hasName() && GV->getName() == "_$TLSML")
2268 return;
2269
2270 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
2271 VisibilityAttr);
2272}
2273
2274void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
2275 // Setup CurrentFnDescSym and its containing csect.
2276 MCSectionXCOFF *FnDescSec =
2277 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
2278 &MF.getFunction(), TM));
2279 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
2280
2281 CurrentFnDescSym = FnDescSec->getQualNameSymbol();
2282
2284}
2285
2286uint16_t PPCAIXAsmPrinter::getNumberOfVRSaved() {
2287 // Calculate the number of VRs be saved.
2288 // Vector registers 20 through 31 are marked as reserved and cannot be used
2289 // in the default ABI.
2290 const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
2291 if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
2292 TM.getAIXExtendedAltivecABI()) {
2293 const MachineRegisterInfo &MRI = MF->getRegInfo();
2294 for (unsigned Reg = PPC::V20; Reg <= PPC::V31; ++Reg)
2295 if (MRI.isPhysRegModified(Reg))
2296 // Number of VRs saved.
2297 return PPC::V31 - Reg + 1;
2298 }
2299 return 0;
2300}
2301
2302void PPCAIXAsmPrinter::emitFunctionBodyEnd() {
2303
2304 if (!TM.getXCOFFTracebackTable())
2305 return;
2306
2307 emitTracebackTable();
2308
2309 // If ShouldEmitEHBlock returns true, then the eh info table
2310 // will be emitted via `AIXException::endFunction`. Otherwise, we
2311 // need to emit a dumy eh info table when VRs are saved. We could not
2312 // consolidate these two places into one because there is no easy way
2313 // to access register information in `AIXException` class.
2315 (getNumberOfVRSaved() > 0)) {
2316 // Emit dummy EH Info Table.
2317 OutStreamer->switchSection(getObjFileLowering().getCompactUnwindSection());
2318 MCSymbol *EHInfoLabel =
2320 OutStreamer->emitLabel(EHInfoLabel);
2321
2322 // Version number.
2323 OutStreamer->emitInt32(0);
2324
2325 const DataLayout &DL = MMI->getModule()->getDataLayout();
2326 const unsigned PointerSize = DL.getPointerSize();
2327 // Add necessary paddings in 64 bit mode.
2328 OutStreamer->emitValueToAlignment(Align(PointerSize));
2329
2330 OutStreamer->emitIntValue(0, PointerSize);
2331 OutStreamer->emitIntValue(0, PointerSize);
2332 OutStreamer->switchSection(MF->getSection());
2333 }
2334}
2335
2336void PPCAIXAsmPrinter::emitTracebackTable() {
2337
2338 // Create a symbol for the end of function.
2339 MCSymbol *FuncEnd = createTempSymbol(MF->getName());
2340 OutStreamer->emitLabel(FuncEnd);
2341
2342 OutStreamer->AddComment("Traceback table begin");
2343 // Begin with a fullword of zero.
2344 OutStreamer->emitIntValueInHexWithPadding(0, 4 /*size*/);
2345
2346 SmallString<128> CommentString;
2347 raw_svector_ostream CommentOS(CommentString);
2348
2349 auto EmitComment = [&]() {
2350 OutStreamer->AddComment(CommentOS.str());
2351 CommentString.clear();
2352 };
2353
2354 auto EmitCommentAndValue = [&](uint64_t Value, int Size) {
2355 EmitComment();
2356 OutStreamer->emitIntValueInHexWithPadding(Value, Size);
2357 };
2358
2359 unsigned int Version = 0;
2360 CommentOS << "Version = " << Version;
2361 EmitCommentAndValue(Version, 1);
2362
2363 // There is a lack of information in the IR to assist with determining the
2364 // source language. AIX exception handling mechanism would only search for
2365 // personality routine and LSDA area when such language supports exception
2366 // handling. So to be conservatively correct and allow runtime to do its job,
2367 // we need to set it to C++ for now.
2368 TracebackTable::LanguageID LanguageIdentifier =
2370
2371 CommentOS << "Language = "
2372 << getNameForTracebackTableLanguageId(LanguageIdentifier);
2373 EmitCommentAndValue(LanguageIdentifier, 1);
2374
2375 // This is only populated for the third and fourth bytes.
2376 uint32_t FirstHalfOfMandatoryField = 0;
2377
2378 // Emit the 3rd byte of the mandatory field.
2379
2380 // We always set traceback offset bit to true.
2381 FirstHalfOfMandatoryField |= TracebackTable::HasTraceBackTableOffsetMask;
2382
2383 const PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
2384 const MachineRegisterInfo &MRI = MF->getRegInfo();
2385
2386 // Check the function uses floating-point processor instructions or not
2387 for (unsigned Reg = PPC::F0; Reg <= PPC::F31; ++Reg) {
2388 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2389 FirstHalfOfMandatoryField |= TracebackTable::IsFloatingPointPresentMask;
2390 break;
2391 }
2392 }
2393
2394#define GENBOOLCOMMENT(Prefix, V, Field) \
2395 CommentOS << (Prefix) << ((V) & (TracebackTable::Field##Mask) ? "+" : "-") \
2396 << #Field
2397
2398#define GENVALUECOMMENT(PrefixAndName, V, Field) \
2399 CommentOS << (PrefixAndName) << " = " \
2400 << static_cast<unsigned>(((V) & (TracebackTable::Field##Mask)) >> \
2401 (TracebackTable::Field##Shift))
2402
2403 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsGlobaLinkage);
2404 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsOutOfLineEpilogOrPrologue);
2405 EmitComment();
2406
2407 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasTraceBackTableOffset);
2408 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsInternalProcedure);
2409 EmitComment();
2410
2411 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasControlledStorage);
2412 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsTOCless);
2413 EmitComment();
2414
2415 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsFloatingPointPresent);
2416 EmitComment();
2417 GENBOOLCOMMENT("", FirstHalfOfMandatoryField,
2418 IsFloatingPointOperationLogOrAbortEnabled);
2419 EmitComment();
2420
2421 OutStreamer->emitIntValueInHexWithPadding(
2422 (FirstHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2423
2424 // Set the 4th byte of the mandatory field.
2425 FirstHalfOfMandatoryField |= TracebackTable::IsFunctionNamePresentMask;
2426
2427 const PPCRegisterInfo *RegInfo =
2428 static_cast<const PPCRegisterInfo *>(Subtarget->getRegisterInfo());
2429 Register FrameReg = RegInfo->getFrameRegister(*MF);
2430 if (FrameReg == (Subtarget->isPPC64() ? PPC::X31 : PPC::R31))
2431 FirstHalfOfMandatoryField |= TracebackTable::IsAllocaUsedMask;
2432
2433 const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
2434 if (!MustSaveCRs.empty())
2435 FirstHalfOfMandatoryField |= TracebackTable::IsCRSavedMask;
2436
2437 if (FI->mustSaveLR())
2438 FirstHalfOfMandatoryField |= TracebackTable::IsLRSavedMask;
2439
2440 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsInterruptHandler);
2441 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsFunctionNamePresent);
2442 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsAllocaUsed);
2443 EmitComment();
2444 GENVALUECOMMENT("OnConditionDirective", FirstHalfOfMandatoryField,
2445 OnConditionDirective);
2446 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsCRSaved);
2447 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsLRSaved);
2448 EmitComment();
2449 OutStreamer->emitIntValueInHexWithPadding((FirstHalfOfMandatoryField & 0xff),
2450 1);
2451
2452 // Set the 5th byte of mandatory field.
2453 uint32_t SecondHalfOfMandatoryField = 0;
2454
2455 SecondHalfOfMandatoryField |= MF->getFrameInfo().getStackSize()
2457 : 0;
2458
2459 uint32_t FPRSaved = 0;
2460 for (unsigned Reg = PPC::F14; Reg <= PPC::F31; ++Reg) {
2461 if (MRI.isPhysRegModified(Reg)) {
2462 FPRSaved = PPC::F31 - Reg + 1;
2463 break;
2464 }
2465 }
2466 SecondHalfOfMandatoryField |= (FPRSaved << TracebackTable::FPRSavedShift) &
2468 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, IsBackChainStored);
2469 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, IsFixup);
2470 GENVALUECOMMENT(", NumOfFPRsSaved", SecondHalfOfMandatoryField, FPRSaved);
2471 EmitComment();
2472 OutStreamer->emitIntValueInHexWithPadding(
2473 (SecondHalfOfMandatoryField & 0xff000000) >> 24, 1);
2474
2475 // Set the 6th byte of mandatory field.
2476
2477 // Check whether has Vector Instruction,We only treat instructions uses vector
2478 // register as vector instructions.
2479 bool HasVectorInst = false;
2480 for (unsigned Reg = PPC::V0; Reg <= PPC::V31; ++Reg)
2481 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2482 // Has VMX instruction.
2483 HasVectorInst = true;
2484 break;
2485 }
2486
2487 if (FI->hasVectorParms() || HasVectorInst)
2488 SecondHalfOfMandatoryField |= TracebackTable::HasVectorInfoMask;
2489
2490 uint16_t NumOfVRSaved = getNumberOfVRSaved();
2491 bool ShouldEmitEHBlock =
2493
2494 if (ShouldEmitEHBlock)
2495 SecondHalfOfMandatoryField |= TracebackTable::HasExtensionTableMask;
2496
2497 uint32_t GPRSaved = 0;
2498
2499 // X13 is reserved under 64-bit environment.
2500 unsigned GPRBegin = Subtarget->isPPC64() ? PPC::X14 : PPC::R13;
2501 unsigned GPREnd = Subtarget->isPPC64() ? PPC::X31 : PPC::R31;
2502
2503 for (unsigned Reg = GPRBegin; Reg <= GPREnd; ++Reg) {
2504 if (MRI.isPhysRegModified(Reg)) {
2505 GPRSaved = GPREnd - Reg + 1;
2506 break;
2507 }
2508 }
2509
2510 SecondHalfOfMandatoryField |= (GPRSaved << TracebackTable::GPRSavedShift) &
2512
2513 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, HasExtensionTable);
2514 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasVectorInfo);
2515 GENVALUECOMMENT(", NumOfGPRsSaved", SecondHalfOfMandatoryField, GPRSaved);
2516 EmitComment();
2517 OutStreamer->emitIntValueInHexWithPadding(
2518 (SecondHalfOfMandatoryField & 0x00ff0000) >> 16, 1);
2519
2520 // Set the 7th byte of mandatory field.
2521 uint32_t NumberOfFixedParms = FI->getFixedParmsNum();
2522 SecondHalfOfMandatoryField |=
2523 (NumberOfFixedParms << TracebackTable::NumberOfFixedParmsShift) &
2525 GENVALUECOMMENT("NumberOfFixedParms", SecondHalfOfMandatoryField,
2526 NumberOfFixedParms);
2527 EmitComment();
2528 OutStreamer->emitIntValueInHexWithPadding(
2529 (SecondHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2530
2531 // Set the 8th byte of mandatory field.
2532
2533 // Always set parameter on stack.
2534 SecondHalfOfMandatoryField |= TracebackTable::HasParmsOnStackMask;
2535
2536 uint32_t NumberOfFPParms = FI->getFloatingPointParmsNum();
2537 SecondHalfOfMandatoryField |=
2540
2541 GENVALUECOMMENT("NumberOfFPParms", SecondHalfOfMandatoryField,
2542 NumberOfFloatingPointParms);
2543 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasParmsOnStack);
2544 EmitComment();
2545 OutStreamer->emitIntValueInHexWithPadding(SecondHalfOfMandatoryField & 0xff,
2546 1);
2547
2548 // Generate the optional fields of traceback table.
2549
2550 // Parameter type.
2551 if (NumberOfFixedParms || NumberOfFPParms) {
2552 uint32_t ParmsTypeValue = FI->getParmsType();
2553
2554 Expected<SmallString<32>> ParmsType =
2555 FI->hasVectorParms()
2557 ParmsTypeValue, NumberOfFixedParms, NumberOfFPParms,
2558 FI->getVectorParmsNum())
2559 : XCOFF::parseParmsType(ParmsTypeValue, NumberOfFixedParms,
2560 NumberOfFPParms);
2561
2562 assert(ParmsType && toString(ParmsType.takeError()).c_str());
2563 if (ParmsType) {
2564 CommentOS << "Parameter type = " << ParmsType.get();
2565 EmitComment();
2566 }
2567 OutStreamer->emitIntValueInHexWithPadding(ParmsTypeValue,
2568 sizeof(ParmsTypeValue));
2569 }
2570 // Traceback table offset.
2571 OutStreamer->AddComment("Function size");
2572 if (FirstHalfOfMandatoryField & TracebackTable::HasTraceBackTableOffsetMask) {
2573 MCSymbol *FuncSectSym = getObjFileLowering().getFunctionEntryPointSymbol(
2574 &(MF->getFunction()), TM);
2575 OutStreamer->emitAbsoluteSymbolDiff(FuncEnd, FuncSectSym, 4);
2576 }
2577
2578 // Since we unset the Int_Handler.
2579 if (FirstHalfOfMandatoryField & TracebackTable::IsInterruptHandlerMask)
2580 report_fatal_error("Hand_Mask not implement yet");
2581
2582 if (FirstHalfOfMandatoryField & TracebackTable::HasControlledStorageMask)
2583 report_fatal_error("Ctl_Info not implement yet");
2584
2585 if (FirstHalfOfMandatoryField & TracebackTable::IsFunctionNamePresentMask) {
2586 StringRef Name = MF->getName().substr(0, INT16_MAX);
2587 int16_t NameLength = Name.size();
2588 CommentOS << "Function name len = "
2589 << static_cast<unsigned int>(NameLength);
2590 EmitCommentAndValue(NameLength, 2);
2591 OutStreamer->AddComment("Function Name");
2592 OutStreamer->emitBytes(Name);
2593 }
2594
2595 if (FirstHalfOfMandatoryField & TracebackTable::IsAllocaUsedMask) {
2596 uint8_t AllocReg = XCOFF::AllocRegNo;
2597 OutStreamer->AddComment("AllocaUsed");
2598 OutStreamer->emitIntValueInHex(AllocReg, sizeof(AllocReg));
2599 }
2600
2601 if (SecondHalfOfMandatoryField & TracebackTable::HasVectorInfoMask) {
2602 uint16_t VRData = 0;
2603 if (NumOfVRSaved) {
2604 // Number of VRs saved.
2605 VRData |= (NumOfVRSaved << TracebackTable::NumberOfVRSavedShift) &
2607 // This bit is supposed to set only when the special register
2608 // VRSAVE is saved on stack.
2609 // However, IBM XL compiler sets the bit when any vector registers
2610 // are saved on the stack. We will follow XL's behavior on AIX
2611 // so that we don't get surprise behavior change for C code.
2613 }
2614
2615 // Set has_varargs.
2616 if (FI->getVarArgsFrameIndex())
2618
2619 // Vector parameters number.
2620 unsigned VectorParmsNum = FI->getVectorParmsNum();
2621 VRData |= (VectorParmsNum << TracebackTable::NumberOfVectorParmsShift) &
2623
2624 if (HasVectorInst)
2626
2627 GENVALUECOMMENT("NumOfVRsSaved", VRData, NumberOfVRSaved);
2628 GENBOOLCOMMENT(", ", VRData, IsVRSavedOnStack);
2629 GENBOOLCOMMENT(", ", VRData, HasVarArgs);
2630 EmitComment();
2631 OutStreamer->emitIntValueInHexWithPadding((VRData & 0xff00) >> 8, 1);
2632
2633 GENVALUECOMMENT("NumOfVectorParams", VRData, NumberOfVectorParms);
2634 GENBOOLCOMMENT(", ", VRData, HasVMXInstruction);
2635 EmitComment();
2636 OutStreamer->emitIntValueInHexWithPadding(VRData & 0x00ff, 1);
2637
2638 uint32_t VecParmTypeValue = FI->getVecExtParmsType();
2639
2640 Expected<SmallString<32>> VecParmsType =
2641 XCOFF::parseVectorParmsType(VecParmTypeValue, VectorParmsNum);
2642 assert(VecParmsType && toString(VecParmsType.takeError()).c_str());
2643 if (VecParmsType) {
2644 CommentOS << "Vector Parameter type = " << VecParmsType.get();
2645 EmitComment();
2646 }
2647 OutStreamer->emitIntValueInHexWithPadding(VecParmTypeValue,
2648 sizeof(VecParmTypeValue));
2649 // Padding 2 bytes.
2650 CommentOS << "Padding";
2651 EmitCommentAndValue(0, 2);
2652 }
2653
2654 uint8_t ExtensionTableFlag = 0;
2655 if (SecondHalfOfMandatoryField & TracebackTable::HasExtensionTableMask) {
2656 if (ShouldEmitEHBlock)
2657 ExtensionTableFlag |= ExtendedTBTableFlag::TB_EH_INFO;
2660 ExtensionTableFlag |= ExtendedTBTableFlag::TB_SSP_CANARY;
2661
2662 CommentOS << "ExtensionTableFlag = "
2663 << getExtendedTBTableFlagString(ExtensionTableFlag);
2664 EmitCommentAndValue(ExtensionTableFlag, sizeof(ExtensionTableFlag));
2665 }
2666
2667 if (ExtensionTableFlag & ExtendedTBTableFlag::TB_EH_INFO) {
2668 auto &Ctx = OutStreamer->getContext();
2669 MCSymbol *EHInfoSym =
2671 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(EHInfoSym, TOCType_EHBlock);
2672 const MCSymbol *TOCBaseSym =
2673 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2674 ->getQualNameSymbol();
2675 const MCExpr *Exp =
2677 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
2678
2679 const DataLayout &DL = getDataLayout();
2680 OutStreamer->emitValueToAlignment(Align(4));
2681 OutStreamer->AddComment("EHInfo Table");
2682 OutStreamer->emitValue(Exp, DL.getPointerSize());
2683 }
2684#undef GENBOOLCOMMENT
2685#undef GENVALUECOMMENT
2686}
2687
2689 return GV->hasAppendingLinkage() &&
2691 // TODO: Linker could still eliminate the GV if we just skip
2692 // handling llvm.used array. Skipping them for now until we or the
2693 // AIX OS team come up with a good solution.
2694 .Case("llvm.used", true)
2695 // It's correct to just skip llvm.compiler.used array here.
2696 .Case("llvm.compiler.used", true)
2697 .Default(false);
2698}
2699
2701 return StringSwitch<bool>(GV->getName())
2702 .Cases("llvm.global_ctors", "llvm.global_dtors", true)
2703 .Default(false);
2704}
2705
2706uint64_t PPCAIXAsmPrinter::getAliasOffset(const Constant *C) {
2707 if (auto *GA = dyn_cast<GlobalAlias>(C))
2708 return getAliasOffset(GA->getAliasee());
2709 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
2710 const MCExpr *LowC = lowerConstant(CE);
2711 const MCBinaryExpr *CBE = dyn_cast<MCBinaryExpr>(LowC);
2712 if (!CBE)
2713 return 0;
2714 if (CBE->getOpcode() != MCBinaryExpr::Add)
2715 report_fatal_error("Only adding an offset is supported now.");
2716 auto *RHS = dyn_cast<MCConstantExpr>(CBE->getRHS());
2717 if (!RHS)
2718 report_fatal_error("Unable to get the offset of alias.");
2719 return RHS->getValue();
2720 }
2721 return 0;
2722}
2723
2724static void tocDataChecks(unsigned PointerSize, const GlobalVariable *GV) {
2725 // TODO: These asserts should be updated as more support for the toc data
2726 // transformation is added (struct support, etc.).
2727 assert(
2728 PointerSize >= GV->getAlign().valueOrOne().value() &&
2729 "GlobalVariables with an alignment requirement stricter than TOC entry "
2730 "size not supported by the toc data transformation.");
2731
2732 Type *GVType = GV->getValueType();
2733 assert(GVType->isSized() && "A GlobalVariable's size must be known to be "
2734 "supported by the toc data transformation.");
2735 if (GV->getDataLayout().getTypeSizeInBits(GVType) >
2736 PointerSize * 8)
2738 "A GlobalVariable with size larger than a TOC entry is not currently "
2739 "supported by the toc data transformation.");
2740 if (GV->hasPrivateLinkage())
2741 report_fatal_error("A GlobalVariable with private linkage is not "
2742 "currently supported by the toc data transformation.");
2743}
2744
2745void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
2746 // Special LLVM global arrays have been handled at the initialization.
2748 return;
2749
2750 // If the Global Variable has the toc-data attribute, it needs to be emitted
2751 // when we emit the .toc section.
2752 if (GV->hasAttribute("toc-data")) {
2753 unsigned PointerSize = GV->getDataLayout().getPointerSize();
2754 tocDataChecks(PointerSize, GV);
2755 TOCDataGlobalVars.push_back(GV);
2756 return;
2757 }
2758
2759 emitGlobalVariableHelper(GV);
2760}
2761
2762void PPCAIXAsmPrinter::emitGlobalVariableHelper(const GlobalVariable *GV) {
2763 assert(!GV->getName().starts_with("llvm.") &&
2764 "Unhandled intrinsic global variable.");
2765
2766 if (GV->hasComdat())
2767 report_fatal_error("COMDAT not yet supported by AIX.");
2768
2769 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
2770
2771 if (GV->isDeclarationForLinker()) {
2772 emitLinkage(GV, GVSym);
2773 return;
2774 }
2775
2776 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
2777 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly() &&
2778 !GVKind.isThreadLocal()) // Checks for both ThreadData and ThreadBSS.
2779 report_fatal_error("Encountered a global variable kind that is "
2780 "not supported yet.");
2781
2782 // Print GV in verbose mode
2783 if (isVerbose()) {
2784 if (GV->hasInitializer()) {
2785 GV->printAsOperand(OutStreamer->getCommentOS(),
2786 /*PrintType=*/false, GV->getParent());
2787 OutStreamer->getCommentOS() << '\n';
2788 }
2789 }
2790
2791 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
2792 getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
2793
2794 // Switch to the containing csect.
2795 OutStreamer->switchSection(Csect);
2796
2797 const DataLayout &DL = GV->getDataLayout();
2798
2799 // Handle common and zero-initialized local symbols.
2800 if (GV->hasCommonLinkage() || GVKind.isBSSLocal() ||
2801 GVKind.isThreadBSSLocal()) {
2802 Align Alignment = GV->getAlign().value_or(DL.getPreferredAlign(GV));
2803 uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
2804 GVSym->setStorageClass(
2806
2807 if (GVKind.isBSSLocal() && Csect->getMappingClass() == XCOFF::XMC_TD) {
2808 OutStreamer->emitZeros(Size);
2809 } else if (GVKind.isBSSLocal() || GVKind.isThreadBSSLocal()) {
2810 assert(Csect->getMappingClass() != XCOFF::XMC_TD &&
2811 "BSS local toc-data already handled and TLS variables "
2812 "incompatible with XMC_TD");
2813 OutStreamer->emitXCOFFLocalCommonSymbol(
2814 OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
2815 GVSym, Alignment);
2816 } else {
2817 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
2818 }
2819 return;
2820 }
2821
2822 MCSymbol *EmittedInitSym = GVSym;
2823
2824 // Emit linkage for the global variable and its aliases.
2825 emitLinkage(GV, EmittedInitSym);
2826 for (const GlobalAlias *GA : GOAliasMap[GV])
2827 emitLinkage(GA, getSymbol(GA));
2828
2829 emitAlignment(getGVAlignment(GV, DL), GV);
2830
2831 // When -fdata-sections is enabled, every GlobalVariable will
2832 // be put into its own csect; therefore, label is not necessary here.
2833 if (!TM.getDataSections() || GV->hasSection()) {
2834 if (Csect->getMappingClass() != XCOFF::XMC_TD)
2835 OutStreamer->emitLabel(EmittedInitSym);
2836 }
2837
2838 // No alias to emit.
2839 if (!GOAliasMap[GV].size()) {
2840 emitGlobalConstant(GV->getDataLayout(), GV->getInitializer());
2841 return;
2842 }
2843
2844 // Aliases with the same offset should be aligned. Record the list of aliases
2845 // associated with the offset.
2846 AliasMapTy AliasList;
2847 for (const GlobalAlias *GA : GOAliasMap[GV])
2848 AliasList[getAliasOffset(GA->getAliasee())].push_back(GA);
2849
2850 // Emit alias label and element value for global variable.
2851 emitGlobalConstant(GV->getDataLayout(), GV->getInitializer(),
2852 &AliasList);
2853}
2854
2855void PPCAIXAsmPrinter::emitFunctionDescriptor() {
2856 const DataLayout &DL = getDataLayout();
2857 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
2858
2859 MCSectionSubPair Current = OutStreamer->getCurrentSection();
2860 // Emit function descriptor.
2861 OutStreamer->switchSection(
2862 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
2863
2864 // Emit aliasing label for function descriptor csect.
2865 for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
2866 OutStreamer->emitLabel(getSymbol(Alias));
2867
2868 // Emit function entry point address.
2869 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
2870 PointerSize);
2871 // Emit TOC base address.
2872 const MCSymbol *TOCBaseSym =
2873 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2874 ->getQualNameSymbol();
2875 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
2876 PointerSize);
2877 // Emit a null environment pointer.
2878 OutStreamer->emitIntValue(0, PointerSize);
2879
2880 OutStreamer->switchSection(Current.first, Current.second);
2881}
2882
2883void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
2884 // For functions without user defined section, it's not necessary to emit the
2885 // label when we have individual function in its own csect.
2886 if (!TM.getFunctionSections() || MF->getFunction().hasSection())
2887 PPCAsmPrinter::emitFunctionEntryLabel();
2888
2889 // Emit aliasing label for function entry point label.
2890 for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
2891 OutStreamer->emitLabel(
2892 getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
2893}
2894
2895void PPCAIXAsmPrinter::emitPGORefs(Module &M) {
2896 if (!OutContext.hasXCOFFSection(
2897 "__llvm_prf_cnts",
2899 return;
2900
2901 // When inside a csect `foo`, a .ref directive referring to a csect `bar`
2902 // translates into a relocation entry from `foo` to` bar`. The referring
2903 // csect, `foo`, is identified by its address. If multiple csects have the
2904 // same address (because one or more of them are zero-length), the referring
2905 // csect cannot be determined. Hence, we don't generate the .ref directives
2906 // if `__llvm_prf_cnts` is an empty section.
2907 bool HasNonZeroLengthPrfCntsSection = false;
2908 const DataLayout &DL = M.getDataLayout();
2909 for (GlobalVariable &GV : M.globals())
2910 if (GV.hasSection() && GV.getSection() == "__llvm_prf_cnts" &&
2911 DL.getTypeAllocSize(GV.getValueType()) > 0) {
2912 HasNonZeroLengthPrfCntsSection = true;
2913 break;
2914 }
2915
2916 if (HasNonZeroLengthPrfCntsSection) {
2917 MCSection *CntsSection = OutContext.getXCOFFSection(
2918 "__llvm_prf_cnts", SectionKind::getData(),
2920 /*MultiSymbolsAllowed*/ true);
2921
2922 OutStreamer->switchSection(CntsSection);
2923 if (OutContext.hasXCOFFSection(
2924 "__llvm_prf_data",
2926 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_data[RW]");
2927 OutStreamer->emitXCOFFRefDirective(S);
2928 }
2929 if (OutContext.hasXCOFFSection(
2930 "__llvm_prf_names",
2932 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_names[RO]");
2933 OutStreamer->emitXCOFFRefDirective(S);
2934 }
2935 if (OutContext.hasXCOFFSection(
2936 "__llvm_prf_vnds",
2938 MCSymbol *S = OutContext.getOrCreateSymbol("__llvm_prf_vnds[RW]");
2939 OutStreamer->emitXCOFFRefDirective(S);
2940 }
2941 }
2942}
2943
2944void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
2945 // If there are no functions and there are no toc-data definitions in this
2946 // module, we will never need to reference the TOC base.
2947 if (M.empty() && TOCDataGlobalVars.empty())
2948 return;
2949
2950 emitPGORefs(M);
2951
2952 // Switch to section to emit TOC base.
2953 OutStreamer->switchSection(getObjFileLowering().getTOCBaseSection());
2954
2955 PPCTargetStreamer *TS =
2956 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2957
2958 for (auto &I : TOC) {
2959 MCSectionXCOFF *TCEntry;
2960 // Setup the csect for the current TC entry. If the variant kind is
2961 // VK_PPC_AIX_TLSGDM the entry represents the region handle, we create a
2962 // new symbol to prefix the name with a dot.
2963 // If TLS model opt is turned on, create a new symbol to prefix the name
2964 // with a dot.
2965 if (I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM ||
2966 (Subtarget->hasAIXShLibTLSModelOpt() &&
2967 I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSLD)) {
2969 StringRef Prefix = ".";
2970 Name += Prefix;
2971 Name += cast<MCSymbolXCOFF>(I.first.first)->getSymbolTableName();
2972 MCSymbol *S = OutContext.getOrCreateSymbol(Name);
2973 TCEntry = cast<MCSectionXCOFF>(
2974 getObjFileLowering().getSectionForTOCEntry(S, TM));
2975 } else {
2976 TCEntry = cast<MCSectionXCOFF>(
2977 getObjFileLowering().getSectionForTOCEntry(I.first.first, TM));
2978 }
2979 OutStreamer->switchSection(TCEntry);
2980
2981 OutStreamer->emitLabel(I.second);
2982 TS->emitTCEntry(*I.first.first, I.first.second);
2983 }
2984
2985 // Traverse the list of global variables twice, emitting all of the
2986 // non-common global variables before the common ones, as emitting a
2987 // .comm directive changes the scope from .toc to the common symbol.
2988 for (const auto *GV : TOCDataGlobalVars) {
2989 if (!GV->hasCommonLinkage())
2990 emitGlobalVariableHelper(GV);
2991 }
2992 for (const auto *GV : TOCDataGlobalVars) {
2993 if (GV->hasCommonLinkage())
2994 emitGlobalVariableHelper(GV);
2995 }
2996}
2997
2998bool PPCAIXAsmPrinter::doInitialization(Module &M) {
2999 const bool Result = PPCAsmPrinter::doInitialization(M);
3000
3001 auto setCsectAlignment = [this](const GlobalObject *GO) {
3002 // Declarations have 0 alignment which is set by default.
3003 if (GO->isDeclarationForLinker())
3004 return;
3005
3006 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
3007 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
3008 getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
3009
3010 Align GOAlign = getGVAlignment(GO, GO->getDataLayout());
3011 Csect->ensureMinAlignment(GOAlign);
3012 };
3013
3014 // For all TLS variables, calculate their corresponding addresses and store
3015 // them into TLSVarsToAddressMapping, which will be used to determine whether
3016 // or not local-exec TLS variables require special assembly printing.
3017 uint64_t TLSVarAddress = 0;
3018 auto DL = M.getDataLayout();
3019 for (const auto &G : M.globals()) {
3020 if (G.isThreadLocal() && !G.isDeclaration()) {
3021 TLSVarAddress = alignTo(TLSVarAddress, getGVAlignment(&G, DL));
3022 TLSVarsToAddressMapping[&G] = TLSVarAddress;
3023 TLSVarAddress += DL.getTypeAllocSize(G.getValueType());
3024 }
3025 }
3026
3027 // We need to know, up front, the alignment of csects for the assembly path,
3028 // because once a .csect directive gets emitted, we could not change the
3029 // alignment value on it.
3030 for (const auto &G : M.globals()) {
3032 continue;
3033
3035 // Generate a format indicator and a unique module id to be a part of
3036 // the sinit and sterm function names.
3037 if (FormatIndicatorAndUniqueModId.empty()) {
3038 std::string UniqueModuleId = getUniqueModuleId(&M);
3039 if (UniqueModuleId != "")
3040 // TODO: Use source file full path to generate the unique module id
3041 // and add a format indicator as a part of function name in case we
3042 // will support more than one format.
3043 FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
3044 else {
3045 // Use threadId, Pid, and current time as the unique module id when we
3046 // cannot generate one based on a module's strong external symbols.
3047 auto CurTime =
3048 std::chrono::duration_cast<std::chrono::nanoseconds>(
3049 std::chrono::steady_clock::now().time_since_epoch())
3050 .count();
3051 FormatIndicatorAndUniqueModId =
3052 "clangPidTidTime_" + llvm::itostr(sys::Process::getProcessId()) +
3053 "_" + llvm::itostr(llvm::get_threadid()) + "_" +
3054 llvm::itostr(CurTime);
3055 }
3056 }
3057
3058 emitSpecialLLVMGlobal(&G);
3059 continue;
3060 }
3061
3062 setCsectAlignment(&G);
3063 std::optional<CodeModel::Model> OptionalCodeModel = G.getCodeModel();
3064 if (OptionalCodeModel)
3065 setOptionalCodeModel(cast<MCSymbolXCOFF>(getSymbol(&G)),
3066 *OptionalCodeModel);
3067 }
3068
3069 for (const auto &F : M)
3070 setCsectAlignment(&F);
3071
3072 // Construct an aliasing list for each GlobalObject.
3073 for (const auto &Alias : M.aliases()) {
3074 const GlobalObject *Aliasee = Alias.getAliaseeObject();
3075 if (!Aliasee)
3077 "alias without a base object is not yet supported on AIX");
3078
3079 if (Aliasee->hasCommonLinkage()) {
3080 report_fatal_error("Aliases to common variables are not allowed on AIX:"
3081 "\n\tAlias attribute for " +
3082 Alias.getGlobalIdentifier() +
3083 " is invalid because " + Aliasee->getName() +
3084 " is common.",
3085 false);
3086 }
3087
3088 const GlobalVariable *GVar =
3089 dyn_cast_or_null<GlobalVariable>(Alias.getAliaseeObject());
3090 if (GVar) {
3091 std::optional<CodeModel::Model> OptionalCodeModel = GVar->getCodeModel();
3092 if (OptionalCodeModel)
3093 setOptionalCodeModel(cast<MCSymbolXCOFF>(getSymbol(&Alias)),
3094 *OptionalCodeModel);
3095 }
3096
3097 GOAliasMap[Aliasee].push_back(&Alias);
3098 }
3099
3100 return Result;
3101}
3102
3103void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
3104 switch (MI->getOpcode()) {
3105 default:
3106 break;
3107 case PPC::TW:
3108 case PPC::TWI:
3109 case PPC::TD:
3110 case PPC::TDI: {
3111 if (MI->getNumOperands() < 5)
3112 break;
3113 const MachineOperand &LangMO = MI->getOperand(3);
3114 const MachineOperand &ReasonMO = MI->getOperand(4);
3115 if (!LangMO.isImm() || !ReasonMO.isImm())
3116 break;
3117 MCSymbol *TempSym = OutContext.createNamedTempSymbol();
3118 OutStreamer->emitLabel(TempSym);
3119 OutStreamer->emitXCOFFExceptDirective(CurrentFnSym, TempSym,
3120 LangMO.getImm(), ReasonMO.getImm(),
3121 Subtarget->isPPC64() ? MI->getMF()->getInstructionCount() * 8 :
3122 MI->getMF()->getInstructionCount() * 4,
3123 MMI->hasDebugInfo());
3124 break;
3125 }
3126 case PPC::GETtlsMOD32AIX:
3127 case PPC::GETtlsMOD64AIX:
3128 case PPC::GETtlsTpointer32AIX:
3129 case PPC::GETtlsADDR64AIX:
3130 case PPC::GETtlsADDR32AIX: {
3131 // A reference to .__tls_get_mod/.__tls_get_addr/.__get_tpointer is unknown
3132 // to the assembler so we need to emit an external symbol reference.
3133 MCSymbol *TlsGetAddr =
3134 createMCSymbolForTlsGetAddr(OutContext, MI->getOpcode());
3135 ExtSymSDNodeSymbols.insert(TlsGetAddr);
3136 break;
3137 }
3138 case PPC::BL8:
3139 case PPC::BL:
3140 case PPC::BL8_NOP:
3141 case PPC::BL_NOP: {
3142 const MachineOperand &MO = MI->getOperand(0);
3143 if (MO.isSymbol()) {
3144 MCSymbolXCOFF *S =
3145 cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
3146 ExtSymSDNodeSymbols.insert(S);
3147 }
3148 } break;
3149 case PPC::BL_TLS:
3150 case PPC::BL8_TLS:
3151 case PPC::BL8_TLS_:
3152 case PPC::BL8_NOP_TLS:
3153 report_fatal_error("TLS call not yet implemented");
3154 case PPC::TAILB:
3155 case PPC::TAILB8:
3156 case PPC::TAILBA:
3157 case PPC::TAILBA8:
3158 case PPC::TAILBCTR:
3159 case PPC::TAILBCTR8:
3160 if (MI->getOperand(0).isSymbol())
3161 report_fatal_error("Tail call for extern symbol not yet supported.");
3162 break;
3163 case PPC::DST:
3164 case PPC::DST64:
3165 case PPC::DSTT:
3166 case PPC::DSTT64:
3167 case PPC::DSTST:
3168 case PPC::DSTST64:
3169 case PPC::DSTSTT:
3170 case PPC::DSTSTT64:
3171 EmitToStreamer(
3172 *OutStreamer,
3173 MCInstBuilder(PPC::ORI).addReg(PPC::R0).addReg(PPC::R0).addImm(0));
3174 return;
3175 }
3176 return PPCAsmPrinter::emitInstruction(MI);
3177}
3178
3179bool PPCAIXAsmPrinter::doFinalization(Module &M) {
3180 // Do streamer related finalization for DWARF.
3181 if (!MAI->usesDwarfFileAndLocDirectives() && MMI->hasDebugInfo())
3182 OutStreamer->doFinalizationAtSectionEnd(
3183 OutStreamer->getContext().getObjectFileInfo()->getTextSection());
3184
3185 for (MCSymbol *Sym : ExtSymSDNodeSymbols)
3186 OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
3187 return PPCAsmPrinter::doFinalization(M);
3188}
3189
3190static unsigned mapToSinitPriority(int P) {
3191 if (P < 0 || P > 65535)
3192 report_fatal_error("invalid init priority");
3193
3194 if (P <= 20)
3195 return P;
3196
3197 if (P < 81)
3198 return 20 + (P - 20) * 16;
3199
3200 if (P <= 1124)
3201 return 1004 + (P - 81);
3202
3203 if (P < 64512)
3204 return 2047 + (P - 1124) * 33878;
3205
3206 return 2147482625u + (P - 64512);
3207}
3208
3209static std::string convertToSinitPriority(int Priority) {
3210 // This helper function converts clang init priority to values used in sinit
3211 // and sterm functions.
3212 //
3213 // The conversion strategies are:
3214 // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm
3215 // reserved priority range [0, 1023] by
3216 // - directly mapping the first 21 and the last 20 elements of the ranges
3217 // - linear interpolating the intermediate values with a step size of 16.
3218 //
3219 // We map the non reserved clang/gnu priority range of [101, 65535] into the
3220 // sinit/sterm priority range [1024, 2147483648] by:
3221 // - directly mapping the first and the last 1024 elements of the ranges
3222 // - linear interpolating the intermediate values with a step size of 33878.
3223 unsigned int P = mapToSinitPriority(Priority);
3224
3225 std::string PrioritySuffix;
3226 llvm::raw_string_ostream os(PrioritySuffix);
3227 os << llvm::format_hex_no_prefix(P, 8);
3228 os.flush();
3229 return PrioritySuffix;
3230}
3231
3232void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
3233 const Constant *List, bool IsCtor) {
3234 SmallVector<Structor, 8> Structors;
3235 preprocessXXStructorList(DL, List, Structors);
3236 if (Structors.empty())
3237 return;
3238
3239 unsigned Index = 0;
3240 for (Structor &S : Structors) {
3241 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func))
3242 S.Func = CE->getOperand(0);
3243
3246 (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
3247 llvm::Twine(convertToSinitPriority(S.Priority)) +
3248 llvm::Twine("_", FormatIndicatorAndUniqueModId) +
3249 llvm::Twine("_", llvm::utostr(Index++)),
3250 cast<Function>(S.Func));
3251 }
3252}
3253
3254void PPCAIXAsmPrinter::emitTTypeReference(const GlobalValue *GV,
3255 unsigned Encoding) {
3256 if (GV) {
3257 TOCEntryType GlobalType = TOCType_GlobalInternal;
3259 if (Linkage == GlobalValue::ExternalLinkage ||
3262 GlobalType = TOCType_GlobalExternal;
3263 MCSymbol *TypeInfoSym = TM.getSymbol(GV);
3264 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(TypeInfoSym, GlobalType);
3265 const MCSymbol *TOCBaseSym =
3266 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
3267 ->getQualNameSymbol();
3268 auto &Ctx = OutStreamer->getContext();
3269 const MCExpr *Exp =
3271 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
3272 OutStreamer->emitValue(Exp, GetSizeOfEncodedValue(Encoding));
3273 } else
3274 OutStreamer->emitIntValue(0, GetSizeOfEncodedValue(Encoding));
3275}
3276
3277// Return a pass that prints the PPC assembly code for a MachineFunction to the
3278// given output stream.
3279static AsmPrinter *
3281 std::unique_ptr<MCStreamer> &&Streamer) {
3282 if (tm.getTargetTriple().isOSAIX())
3283 return new PPCAIXAsmPrinter(tm, std::move(Streamer));
3284
3285 return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
3286}
3287
3288void PPCAIXAsmPrinter::emitModuleCommandLines(Module &M) {
3289 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
3290 if (!NMD || !NMD->getNumOperands())
3291 return;
3292
3293 std::string S;
3294 raw_string_ostream RSOS(S);
3295 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3296 const MDNode *N = NMD->getOperand(i);
3297 assert(N->getNumOperands() == 1 &&
3298 "llvm.commandline metadata entry can have only one operand");
3299 const MDString *MDS = cast<MDString>(N->getOperand(0));
3300 // Add "@(#)" to support retrieving the command line information with the
3301 // AIX "what" command
3302 RSOS << "@(#)opt " << MDS->getString() << "\n";
3303 RSOS.write('\0');
3304 }
3305 OutStreamer->emitXCOFFCInfoSym(".GCC.command.line", RSOS.str());
3306}
3307
3308// Force static initialization.
3318}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_EXTERNAL_VISIBILITY
Definition: Compiler.h:135
#define LLVM_DEBUG(X)
Definition: Debug.h:101
std::string Name
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
IRTranslator LLVM IR MI
#define RegName(no)
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
static std::string getRegisterName(const TargetRegisterInfo *TRI, Register Reg)
Definition: MIParser.cpp:1414
This file implements a map that provides insertion order iteration.
Module.h This file contains the declarations for the Module class.
#define P(N)
static void collectTOCStats(PPCAsmPrinter::TOCEntryType Type)
static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV)
static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV)
LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter()
#define GENBOOLCOMMENT(Prefix, V, Field)
static MCSymbol * getMCSymbolForTOCPseudoMO(const MachineOperand &MO, AsmPrinter &AP)
Map a machine operand for a TOC pseudo-machine instruction to its corresponding MCSymbol.
static void setOptionalCodeModel(MCSymbolXCOFF *XSym, CodeModel::Model CM)
static AsmPrinter * createPPCAsmPrinterPass(TargetMachine &tm, std::unique_ptr< MCStreamer > &&Streamer)
static PPCAsmPrinter::TOCEntryType getTOCEntryTypeForMO(const MachineOperand &MO)
static CodeModel::Model getCodeModel(const PPCSubtarget &S, const TargetMachine &TM, const MachineOperand &MO)
static std::string convertToSinitPriority(int Priority)
static MCSymbol * createMCSymbolForTlsGetAddr(MCContext &Ctx, unsigned MIOpc)
This helper function creates the TlsGetAddr/TlsGetMod MCSymbol for AIX.
#define GENVALUECOMMENT(PrefixAndName, V, Field)
static unsigned mapToSinitPriority(int P)
static void tocDataChecks(unsigned PointerSize, const GlobalVariable *GV)
static cl::opt< bool > EnableSSPCanaryBitInTB("aix-ssp-tb-bit", cl::init(false), cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden)
if(VerifyEach)
const char LLVMTargetMachineRef TM
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
Provides a library for accessing information about this process and other processes on the operating ...
static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, const RISCVSubtarget &Subtarget)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file contains some functions that are useful when dealing with strings.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:469
Value * RHS
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:85
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
Definition: AsmPrinter.h:568
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:706
void emitXRayTable()
Emit a table with all XRay instrumentation points.
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
virtual void SetupMachineFunction(MachineFunction &MF)
This should be called when a new MachineFunction is being processed from runOnMachineFunction.
virtual void emitStartOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the start of their fi...
Definition: AsmPrinter.h:544
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
Definition: AsmPrinter.cpp:450
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
Definition: AsmPrinter.h:396
virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
MCSymbol * GetBlockAddressSymbol(const BlockAddress *BA) const
Return the MCSymbol used to satisfy BlockAddress uses of the specified basic block.
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1084
This is an important base class in LLVM.
Definition: Constant.h:41
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size in bytes, rounded up to a whole number of bytes.
Definition: DataLayout.cpp:750
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:672
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:544
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:80
bool hasComdat() const
Definition: GlobalObject.h:128
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:110
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:248
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:290
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
bool hasDefaultVisibility() const
Definition: GlobalValue.h:249
bool hasPrivateLinkage() const
Definition: GlobalValue.h:527
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
bool hasDLLExportStorageClass() const
Definition: GlobalValue.h:281
bool isDeclarationForLinker() const
Definition: GlobalValue.h:618
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:394
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:67
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ ProtectedVisibility
The GV is protected.
Definition: GlobalValue.h:69
const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition: Globals.cpp:124
bool hasCommonLinkage() const
Definition: GlobalValue.h:532
bool hasAppendingLinkage() const
Definition: GlobalValue.h:525
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:54
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
Type * getValueType() const
Definition: GlobalValue.h:296
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists.
bool hasInitializer() const
Definitions have initializers, declarations don't.
std::optional< CodeModel::Model > getCodeModel() const
Get the custom code model of this global if it has one.
Binary assembler expressions.
Definition: MCExpr.h:492
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:642
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:536
Opcode getOpcode() const
Get the kind of this binary expression.
Definition: MCExpr.h:636
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:621
@ Add
Addition.
Definition: MCExpr.h:495
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:194
Context object for machine code objects.
Definition: MCContext.h:83
MCSectionXCOFF * getXCOFFSection(StringRef Section, SectionKind K, std::optional< XCOFF::CsectProperties > CsectProp=std::nullopt, bool MultiSymbolsAllowed=false, const char *BeginSymName=nullptr, std::optional< XCOFF::DwarfSectionSubtypeFlags > DwarfSubtypeFlags=std::nullopt)
Definition: MCContext.cpp:796
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
MCInstBuilder & addReg(unsigned Reg)
Add a new register operand.
Definition: MCInstBuilder.h:37
MCInstBuilder & addImm(int64_t Val)
Add a new integer immediate operand.
Definition: MCInstBuilder.h:43
MCInstBuilder & addExpr(const MCExpr *Val)
Add a new MCExpr operand.
Definition: MCInstBuilder.h:61
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
void addOperand(const MCOperand Op)
Definition: MCInst.h:210
void setOpcode(unsigned Op)
Definition: MCInst.h:197
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:206
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:36
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:162
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:69
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
XCOFF::StorageMappingClass getMappingClass() const
MCSymbolXCOFF * getQualNameSymbol() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
void setAlignment(Align Value)
Definition: MCSection.h:159
void ensureMinAlignment(Align MinAlignment)
Makes sure that Alignment is at least MinAlignment.
Definition: MCSection.h:162
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:397
StringRef getSymbolTableName() const
Definition: MCSymbolXCOFF.h:68
void setPerSymbolCodeModel(MCSymbolXCOFF::CodeModel Model)
Definition: MCSymbolXCOFF.h:86
void setStorageClass(XCOFF::StorageClass SC)
Definition: MCSymbolXCOFF.h:42
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:58
Metadata node.
Definition: Metadata.h:1067
A single uniqued string.
Definition: Metadata.h:720
StringRef getString() const
Definition: Metadata.cpp:610
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
MCSection * getSection() const
Returns the Section this function belongs to.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Representation of each machine instruction.
Definition: MachineInstr.h:69
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isJTI() const
isJTI - Tests if this is a MO_JumpTableIndex operand.
const BlockAddress * getBlockAddress() const
unsigned getTargetFlags() const
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
iterator end()
Definition: MapVector.h:71
iterator find(const KeyT &Key)
Definition: MapVector.h:167
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1729
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1381
unsigned getNumOperands() const
Definition: Metadata.cpp:1377
uint64_t getTOCSaveOffset() const
getTOCSaveOffset - Return the previous frame offset to save the TOC register – 64-bit SVR4 ABI only.
PPCFunctionInfo - This class is derived from MachineFunction private PowerPC target-specific informat...
MCSymbol * getPICOffsetSymbol(MachineFunction &MF) const
const SmallVectorImpl< Register > & getMustSaveCRs() const
unsigned getFloatingPointParmsNum() const
MCSymbol * getGlobalEPSymbol(MachineFunction &MF) const
MCSymbol * getLocalEPSymbol(MachineFunction &MF) const
unsigned getVectorParmsNum() const
uint32_t getVecExtParmsType() const
MCSymbol * getTOCOffsetSymbol(MachineFunction &MF) const
unsigned getFixedParmsNum() const
static const char * getRegisterName(MCRegister Reg)
static bool hasTLSFlag(unsigned TF)
Definition: PPCInstrInfo.h:315
static const PPCMCExpr * createLo(const MCExpr *Expr, MCContext &Ctx)
Definition: PPCMCExpr.h:49
static const PPCMCExpr * createHa(const MCExpr *Expr, MCContext &Ctx)
Definition: PPCMCExpr.h:57
bool is32BitELFABI() const
Definition: PPCSubtarget.h:219
bool isAIXABI() const
Definition: PPCSubtarget.h:214
const PPCFrameLowering * getFrameLowering() const override
Definition: PPCSubtarget.h:142
bool isPPC64() const
isPPC64 - Return true if we are generating code for 64-bit pointer mode.
bool isUsingPCRelativeCalls() const
CodeModel::Model getCodeModel(const TargetMachine &TM, const GlobalValue *GV) const
Calculates the effective code model for argument GV.
bool isELFv2ABI() const
const PPCRegisterInfo * getRegisterInfo() const override
Definition: PPCSubtarget.h:152
bool isGVIndirectSymbol(const GlobalValue *GV) const
True if the GV will be accessed via an indirect symbol.
Common code between 32-bit and 64-bit PowerPC targets.
bool hasGlibcHWCAPAccess() const
virtual void emitAbiVersion(int AbiVersion)
virtual void emitTCEntry(const MCSymbol &S, MCSymbolRefExpr::VariantKind Kind)
virtual void emitLocalEntry(MCSymbolELF *S, const MCExpr *LocalOffset)
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
MI-level patchpoint operands.
Definition: StackMaps.h:76
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
bool isThreadBSSLocal() const
Definition: SectionKind.h:163
static SectionKind getText()
Definition: SectionKind.h:190
bool isBSSLocal() const
Definition: SectionKind.h:170
static SectionKind getData()
Definition: SectionKind.h:213
bool isThreadLocal() const
Definition: SectionKind.h:157
bool isReadOnly() const
Definition: SectionKind.h:131
bool isGlobalWriteableData() const
Definition: SectionKind.h:165
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:94
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
void recordPatchPoint(const MCSymbol &L, const MachineInstr &MI)
Generate a stackmap record for a patchpoint instruction.
Definition: StackMaps.cpp:548
void recordStackMap(const MCSymbol &L, const MachineInstr &MI)
Generate a stackmap record for a stackmap instruction.
Definition: StackMaps.cpp:538
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:564
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:258
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:90
static bool ShouldSetSSPCanaryBitInTB(const MachineFunction *MF)
static MCSymbol * getEHInfoTableSymbol(const MachineFunction *MF)
static XCOFF::StorageClass getStorageClassForGlobal(const GlobalValue *GV)
static bool ShouldEmitEHBlock(const MachineFunction *MF)
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
const Triple & getTargetTriple() const
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:710
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
LLVM Value Representation.
Definition: Value.h:74
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
Definition: AsmWriter.cpp:5022
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:926
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:5105
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
static Pid getProcessId()
Get the process's identifier.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ SHT_PROGBITS
Definition: ELF.h:1067
@ SHF_ALLOC
Definition: ELF.h:1161
@ SHF_WRITE
Definition: ELF.h:1158
const uint64_t Version
Definition: InstrProf.h:1108
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:148
@ MO_TLSLDM_FLAG
MO_TLSLDM_FLAG - on AIX the ML relocation type is only valid for a reference to a TOC symbol from the...
Definition: PPC.h:146
@ MO_TPREL_PCREL_FLAG
MO_TPREL_PCREL_FLAG = MO_PCREL_FLAG | MO_TPREL_FLAG.
Definition: PPC.h:197
@ MO_GOT_TPREL_PCREL_FLAG
MO_GOT_TPREL_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition: PPC.h:172
@ MO_TLSGDM_FLAG
MO_TLSGDM_FLAG - If this bit is set the symbol reference is relative to the region handle of TLS Gene...
Definition: PPC.h:154
@ MO_TLSLD_FLAG
MO_TLSLD_FLAG - If this bit is set the symbol reference is relative to TLS Local Dynamic model.
Definition: PPC.h:150
@ MO_TPREL_FLAG
MO_TPREL_FLAG - If this bit is set, the symbol reference is relative to the thread pointer and the sy...
Definition: PPC.h:140
@ MO_GOT_TLSLD_PCREL_FLAG
MO_GOT_TLSLD_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition: PPC.h:166
@ MO_TLSGD_FLAG
MO_TLSGD_FLAG - If this bit is set the symbol reference is relative to TLS General Dynamic model for ...
Definition: PPC.h:135
@ MO_GOT_TLSGD_PCREL_FLAG
MO_GOT_TLSGD_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition: PPC.h:160
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:26
const char * stripRegisterPrefix(const char *RegName)
stripRegisterPrefix - This method strips the character prefix from a register name so that only the n...
Predicate InvertPredicate(Predicate Opcode)
Invert the specified predicate. != -> ==, < -> >=.
static bool isVRRegister(unsigned Reg)
static bool isVFRegister(unsigned Reg)
@ CE
Windows NT (Windows on ARM)
Reg
All possible values of the reg field in the ModR/M byte.
void emitInstruction(MCObjectStreamer &, const MCInst &Inst, const MCSubtargetInfo &STI)
SmallString< 32 > getExtendedTBTableFlagString(uint8_t Flag)
Definition: XCOFF.cpp:162
Expected< SmallString< 32 > > parseParmsTypeWithVecInfo(uint32_t Value, unsigned FixedParmsNum, unsigned FloatingParmsNum, unsigned VectorParmsNum)
Definition: XCOFF.cpp:188
Expected< SmallString< 32 > > parseParmsType(uint32_t Value, unsigned FixedParmsNum, unsigned FloatingParmsNum)
Definition: XCOFF.cpp:110
Expected< SmallString< 32 > > parseVectorParmsType(uint32_t Value, unsigned ParmsNum)
Definition: XCOFF.cpp:240
@ XMC_RW
Read Write Data.
Definition: XCOFF.h:117
@ XMC_RO
Read Only Constant.
Definition: XCOFF.h:106
@ XMC_TD
Scalar data item in the TOC.
Definition: XCOFF.h:120
@ XMC_PR
Program Code.
Definition: XCOFF.h:105
StringRef getNameForTracebackTableLanguageId(TracebackTable::LanguageID LangId)
Definition: XCOFF.cpp:87
constexpr uint8_t AllocRegNo
Definition: XCOFF.h:44
@ XTY_SD
Csect definition for initialized storage.
Definition: XCOFF.h:242
@ XTY_ER
External reference.
Definition: XCOFF.h:241
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
unsigned combineHashValue(unsigned a, unsigned b)
Simplistic combination of 32-bit hash values into 32-bit hash values.
Definition: DenseMapInfo.h:39
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
@ Offset
Definition: DWP.cpp:480
Target & getThePPC64LETarget()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1680
bool LowerPPCMachineOperandToMCOperand(const MachineOperand &MO, MCOperand &OutMO, AsmPrinter &AP)
Target & getThePPC32Target()
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
std::pair< MCSection *, uint32_t > MCSectionSubPair
Definition: MCStreamer.h:67
void LowerPPCMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI, AsmPrinter &AP)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition: Format.h:200
Target & getThePPC64Target()
uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
Definition: Threading.cpp:33
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
Target & getThePPC32LETarget()
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
MCSymbolAttr
Definition: MCDirectives.h:18
@ MCSA_Weak
.weak
Definition: MCDirectives.h:45
@ MCSA_Global
.type _foo, @gnu_unique_object
Definition: MCDirectives.h:30
@ MCSA_Extern
.extern (XCOFF)
Definition: MCDirectives.h:32
@ MCSA_LGlobal
.lglobl (XCOFF)
Definition: MCDirectives.h:31
@ MCSA_Invalid
Not a valid directive.
Definition: MCDirectives.h:19
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
std::pair< const MCSymbol *, MCSymbolRefExpr::VariantKind > TOCKey
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:52
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition: Alignment.h:141
static void RegisterAsmPrinter(Target &T, Target::AsmPrinterCtorTy Fn)
RegisterAsmPrinter - Register an AsmPrinter implementation for the given target.
static constexpr uint32_t FPRSavedMask
Definition: XCOFF.h:412
static constexpr uint16_t NumberOfVRSavedMask
Definition: XCOFF.h:442
static constexpr uint8_t NumberOfFloatingPointParmsShift
Definition: XCOFF.h:428
static constexpr uint32_t NumberOfFixedParmsMask
Definition: XCOFF.h:422
static constexpr uint16_t HasVMXInstructionMask
Definition: XCOFF.h:448
static constexpr uint32_t IsLRSavedMask
Definition: XCOFF.h:406
static constexpr uint16_t HasVarArgsMask
Definition: XCOFF.h:444
static constexpr uint32_t IsAllocaUsedMask
Definition: XCOFF.h:403
static constexpr uint16_t IsVRSavedOnStackMask
Definition: XCOFF.h:443
static constexpr uint16_t NumberOfVectorParmsMask
Definition: XCOFF.h:447
static constexpr uint32_t IsFloatingPointPresentMask
Definition: XCOFF.h:396
static constexpr uint32_t FPRSavedShift
Definition: XCOFF.h:413
static constexpr uint32_t NumberOfFloatingPointParmsMask
Definition: XCOFF.h:426
static constexpr uint32_t HasControlledStorageMask
Definition: XCOFF.h:394
static constexpr uint32_t HasExtensionTableMask
Definition: XCOFF.h:416
static constexpr uint32_t HasTraceBackTableOffsetMask
Definition: XCOFF.h:392
static constexpr uint32_t IsCRSavedMask
Definition: XCOFF.h:405
static constexpr uint8_t NumberOfFixedParmsShift
Definition: XCOFF.h:423
static constexpr uint32_t GPRSavedMask
Definition: XCOFF.h:418
static constexpr uint8_t NumberOfVectorParmsShift
Definition: XCOFF.h:449
static constexpr uint32_t HasParmsOnStackMask
Definition: XCOFF.h:427
static constexpr uint32_t IsFunctionNamePresentMask
Definition: XCOFF.h:402
static constexpr uint32_t IsBackChainStoredMask
Definition: XCOFF.h:410
static constexpr uint32_t IsInterruptHandlerMask
Definition: XCOFF.h:401
static constexpr uint32_t HasVectorInfoMask
Definition: XCOFF.h:417
static constexpr uint8_t NumberOfVRSavedShift
Definition: XCOFF.h:445
static constexpr uint32_t GPRSavedShift
Definition: XCOFF.h:419