1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
20 #include "InstPrinter/PPCInstPrinter.h"
21 #include "MCTargetDesc/PPCMCExpr.h"
22 #include "MCTargetDesc/PPCPredicates.h"
23 #include "PPCMachineFunctionInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "PPCTargetStreamer.h"
27 #include "llvm/ADT/MapVector.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/CodeGen/AsmPrinter.h"
31 #include "llvm/CodeGen/MachineConstantPool.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/StackMaps.h"
38 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DebugInfo.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Mangler.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCInst.h"
48 #include "llvm/MC/MCInstBuilder.h"
49 #include "llvm/MC/MCSectionELF.h"
50 #include "llvm/MC/MCSectionMachO.h"
51 #include "llvm/MC/MCStreamer.h"
52 #include "llvm/MC/MCSymbolELF.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ELF.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/TargetRegistry.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 #include "llvm/Target/TargetOptions.h"
62 #include "llvm/Target/TargetRegisterInfo.h"
65 #define DEBUG_TYPE "asmprinter"
68 class PPCAsmPrinter : public AsmPrinter {
70 MapVector<MCSymbol*, MCSymbol*> TOC;
71 const PPCSubtarget *Subtarget;
74 explicit PPCAsmPrinter(TargetMachine &TM,
75 std::unique_ptr<MCStreamer> Streamer)
76 : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
78 const char *getPassName() const override {
79 return "PowerPC Assembly Printer";
82 MCSymbol *lookUpOrCreateTOCEntry(MCSymbol *Sym);
84 void EmitInstruction(const MachineInstr *MI) override;
86 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
88 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
89 unsigned AsmVariant, const char *ExtraCode,
90 raw_ostream &O) override;
91 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
92 unsigned AsmVariant, const char *ExtraCode,
93 raw_ostream &O) override;
95 void EmitEndOfAsmFile(Module &M) override;
97 void LowerSTACKMAP(MCStreamer &OutStreamer, StackMaps &SM,
98 const MachineInstr &MI);
99 void LowerPATCHPOINT(MCStreamer &OutStreamer, StackMaps &SM,
100 const MachineInstr &MI);
101 void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
102 bool runOnMachineFunction(MachineFunction &MF) override {
103 Subtarget = &MF.getSubtarget<PPCSubtarget>();
104 return AsmPrinter::runOnMachineFunction(MF);
108 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
109 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
111 explicit PPCLinuxAsmPrinter(TargetMachine &TM,
112 std::unique_ptr<MCStreamer> Streamer)
113 : PPCAsmPrinter(TM, std::move(Streamer)) {}
115 const char *getPassName() const override {
116 return "Linux PPC Assembly Printer";
119 bool doFinalization(Module &M) override;
120 void EmitStartOfAsmFile(Module &M) override;
122 void EmitFunctionEntryLabel() override;
124 void EmitFunctionBodyStart() override;
125 void EmitFunctionBodyEnd() override;
128 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
130 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
132 explicit PPCDarwinAsmPrinter(TargetMachine &TM,
133 std::unique_ptr<MCStreamer> Streamer)
134 : PPCAsmPrinter(TM, std::move(Streamer)) {}
136 const char *getPassName() const override {
137 return "Darwin PPC Assembly Printer";
140 bool doFinalization(Module &M) override;
141 void EmitStartOfAsmFile(Module &M) override;
143 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
145 } // end of anonymous namespace
147 /// stripRegisterPrefix - This method strips the character prefix from a
148 /// register name so that only the number is left. Used by for linux asm.
149 static const char *stripRegisterPrefix(const char *RegName) {
150 switch (RegName[0]) {
155 if (RegName[1] == 's')
158 case 'c': if (RegName[1] == 'r') return RegName + 2;
164 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
166 const DataLayout &DL = getDataLayout();
167 const MachineOperand &MO = MI->getOperand(OpNo);
169 switch (MO.getType()) {
170 case MachineOperand::MO_Register: {
171 const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
172 // Linux assembler (Others?) does not take register mnemonics.
173 // FIXME - What about special registers used in mfspr/mtspr?
174 if (!Subtarget->isDarwin())
175 RegName = stripRegisterPrefix(RegName);
179 case MachineOperand::MO_Immediate:
183 case MachineOperand::MO_MachineBasicBlock:
184 MO.getMBB()->getSymbol()->print(O, MAI);
186 case MachineOperand::MO_ConstantPoolIndex:
187 O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
190 case MachineOperand::MO_BlockAddress:
191 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
193 case MachineOperand::MO_GlobalAddress: {
194 // Computing the address of a global symbol, not calling it.
195 const GlobalValue *GV = MO.getGlobal();
196 MCSymbol *SymToPrint;
198 // External or weakly linked global variables need non-lazily-resolved stubs
199 if (TM.getRelocationModel() != Reloc::Static &&
200 !GV->isStrongDefinitionForLinker()) {
201 if (!GV->hasHiddenVisibility()) {
202 SymToPrint = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
203 MachineModuleInfoImpl::StubValueTy &StubSym =
204 MMI->getObjFileInfo<MachineModuleInfoMachO>()
205 .getGVStubEntry(SymToPrint);
206 if (!StubSym.getPointer())
207 StubSym = MachineModuleInfoImpl::
208 StubValueTy(getSymbol(GV), !GV->hasInternalLinkage());
209 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
210 GV->hasAvailableExternallyLinkage()) {
211 SymToPrint = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
213 MachineModuleInfoImpl::StubValueTy &StubSym =
214 MMI->getObjFileInfo<MachineModuleInfoMachO>().
215 getHiddenGVStubEntry(SymToPrint);
216 if (!StubSym.getPointer())
217 StubSym = MachineModuleInfoImpl::
218 StubValueTy(getSymbol(GV), !GV->hasInternalLinkage());
220 SymToPrint = getSymbol(GV);
223 SymToPrint = getSymbol(GV);
226 SymToPrint->print(O, MAI);
228 printOffset(MO.getOffset(), O);
233 O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
238 /// PrintAsmOperand - Print out an operand for an inline asm expression.
240 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
242 const char *ExtraCode, raw_ostream &O) {
243 // Does this asm operand have a single letter operand modifier?
244 if (ExtraCode && ExtraCode[0]) {
245 if (ExtraCode[1] != 0) return true; // Unknown modifier.
247 switch (ExtraCode[0]) {
249 // See if this is a generic print operand
250 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
251 case 'c': // Don't print "$" before a global var name or constant.
252 break; // PPC never has a prefix.
253 case 'L': // Write second word of DImode reference.
254 // Verify that this operand has two consecutive registers.
255 if (!MI->getOperand(OpNo).isReg() ||
256 OpNo+1 == MI->getNumOperands() ||
257 !MI->getOperand(OpNo+1).isReg())
259 ++OpNo; // Return the high-part.
262 // Write 'i' if an integer constant, otherwise nothing. Used to print
264 if (MI->getOperand(OpNo).isImm())
270 printOperand(MI, OpNo, O);
274 // At the moment, all inline asm memory operands are a single register.
275 // In any case, the output of this routine should always be just one
276 // assembler operand.
278 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
280 const char *ExtraCode,
282 if (ExtraCode && ExtraCode[0]) {
283 if (ExtraCode[1] != 0) return true; // Unknown modifier.
285 switch (ExtraCode[0]) {
286 default: return true; // Unknown modifier.
287 case 'y': // A memory reference for an X-form instruction
289 const char *RegName = "r0";
290 if (!Subtarget->isDarwin())
291 RegName = stripRegisterPrefix(RegName);
292 O << RegName << ", ";
293 printOperand(MI, OpNo, O);
296 case 'U': // Print 'u' for update form.
297 case 'X': // Print 'x' for indexed form.
299 // FIXME: Currently for PowerPC memory operands are always loaded
300 // into a register, so we never get an update or indexed form.
301 // This is bad even for offset forms, since even if we know we
302 // have a value in -16(r1), we will generate a load into r<n>
303 // and then load from 0(r<n>). Until that issue is fixed,
304 // tolerate 'U' and 'X' but don't output anything.
305 assert(MI->getOperand(OpNo).isReg());
311 assert(MI->getOperand(OpNo).isReg());
313 printOperand(MI, OpNo, O);
319 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
320 /// exists for it. If not, create one. Then return a symbol that references
322 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(MCSymbol *Sym) {
323 MCSymbol *&TOCEntry = TOC[Sym];
325 TOCEntry = createTempSymbol("C");
329 void PPCAsmPrinter::EmitEndOfAsmFile(Module &M) {
330 SM.serializeToStackMapSection();
333 void PPCAsmPrinter::LowerSTACKMAP(MCStreamer &OutStreamer, StackMaps &SM,
334 const MachineInstr &MI) {
335 unsigned NumNOPBytes = MI.getOperand(1).getImm();
337 SM.recordStackMap(MI);
338 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
340 // Scan ahead to trim the shadow.
341 const MachineBasicBlock &MBB = *MI.getParent();
342 MachineBasicBlock::const_iterator MII(MI);
344 while (NumNOPBytes > 0) {
345 if (MII == MBB.end() || MII->isCall() ||
346 MII->getOpcode() == PPC::DBG_VALUE ||
347 MII->getOpcode() == TargetOpcode::PATCHPOINT ||
348 MII->getOpcode() == TargetOpcode::STACKMAP)
355 for (unsigned i = 0; i < NumNOPBytes; i += 4)
356 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::NOP));
359 // Lower a patchpoint of the form:
360 // [<def>], <id>, <numBytes>, <target>, <numArgs>
361 void PPCAsmPrinter::LowerPATCHPOINT(MCStreamer &OutStreamer, StackMaps &SM,
362 const MachineInstr &MI) {
363 SM.recordPatchPoint(MI);
364 PatchPointOpers Opers(&MI);
366 unsigned EncodedBytes = 0;
367 const MachineOperand &CalleeMO =
368 Opers.getMetaOper(PatchPointOpers::TargetPos);
370 if (CalleeMO.isImm()) {
371 int64_t CallTarget = Opers.getMetaOper(PatchPointOpers::TargetPos).getImm();
373 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
374 "High 16 bits of call target should be zero.");
375 unsigned ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
377 // Materialize the jump address:
378 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::LI8)
380 .addImm((CallTarget >> 32) & 0xFFFF));
382 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::RLDIC)
385 .addImm(32).addImm(16));
387 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::ORIS8)
390 .addImm((CallTarget >> 16) & 0xFFFF));
392 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::ORI8)
395 .addImm(CallTarget & 0xFFFF));
397 // Save the current TOC pointer before the remote call.
398 int TOCSaveOffset = Subtarget->isELFv2ABI() ? 24 : 40;
399 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::STD)
401 .addImm(TOCSaveOffset)
406 // If we're on ELFv1, then we need to load the actual function pointer
407 // from the function descriptor.
408 if (!Subtarget->isELFv2ABI()) {
409 // Load the new TOC pointer and the function address, but not r11
410 // (needing this is rare, and loading it here would prevent passing it
411 // via a 'nest' parameter.
412 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::LD)
415 .addReg(ScratchReg));
417 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::LD)
420 .addReg(ScratchReg));
424 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::MTCTR8)
425 .addReg(ScratchReg));
427 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::BCTRL8));
430 // Restore the TOC pointer after the call.
431 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::LD)
433 .addImm(TOCSaveOffset)
437 } else if (CalleeMO.isGlobal()) {
438 const GlobalValue *GValue = CalleeMO.getGlobal();
439 MCSymbol *MOSymbol = getSymbol(GValue);
440 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
442 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::BL8_NOP)
447 // Each instruction is 4 bytes.
451 unsigned NumBytes = Opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
452 assert(NumBytes >= EncodedBytes &&
453 "Patchpoint can't request size less than the length of a call.");
454 assert((NumBytes - EncodedBytes) % 4 == 0 &&
455 "Invalid number of NOP bytes requested!");
456 for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
457 EmitToStreamer(OutStreamer, MCInstBuilder(PPC::NOP));
460 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
461 /// call to __tls_get_addr to the current output stream.
462 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
463 MCSymbolRefExpr::VariantKind VK) {
464 StringRef Name = "__tls_get_addr";
465 MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name);
466 MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
468 assert(MI->getOperand(0).isReg() &&
469 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
470 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
471 "GETtls[ld]ADDR[32] must define GPR3");
472 assert(MI->getOperand(1).isReg() &&
473 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
474 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
475 "GETtls[ld]ADDR[32] must read GPR3");
477 if (!Subtarget->isPPC64() && !Subtarget->isDarwin() &&
478 TM.getRelocationModel() == Reloc::PIC_)
479 Kind = MCSymbolRefExpr::VK_PLT;
480 const MCSymbolRefExpr *TlsRef =
481 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
482 const MachineOperand &MO = MI->getOperand(2);
483 const GlobalValue *GValue = MO.getGlobal();
484 MCSymbol *MOSymbol = getSymbol(GValue);
485 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
486 EmitToStreamer(*OutStreamer,
487 MCInstBuilder(Subtarget->isPPC64() ?
488 PPC::BL8_NOP_TLS : PPC::BL_TLS)
493 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
494 /// the current output stream.
496 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
498 bool isPPC64 = Subtarget->isPPC64();
499 bool isDarwin = TM.getTargetTriple().isOSDarwin();
500 const Module *M = MF->getFunction()->getParent();
501 PICLevel::Level PL = M->getPICLevel();
503 // Lower multi-instruction pseudo operations.
504 switch (MI->getOpcode()) {
506 case TargetOpcode::DBG_VALUE:
507 llvm_unreachable("Should be handled target independently");
508 case TargetOpcode::STACKMAP:
509 return LowerSTACKMAP(*OutStreamer, SM, *MI);
510 case TargetOpcode::PATCHPOINT:
511 return LowerPATCHPOINT(*OutStreamer, SM, *MI);
513 case PPC::MoveGOTtoLR: {
514 // Transform %LR = MoveGOTtoLR
515 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
516 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
517 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
519 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
520 MCSymbol *GOTSymbol =
521 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
522 const MCExpr *OffsExpr =
523 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
524 MCSymbolRefExpr::VK_PPC_LOCAL,
526 MCConstantExpr::create(4, OutContext),
530 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
533 case PPC::MovePCtoLR:
534 case PPC::MovePCtoLR8: {
535 // Transform %LR = MovePCtoLR
536 // Into this, where the label is the PIC base:
539 MCSymbol *PICBase = MF->getPICBaseSymbol();
542 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
543 // FIXME: We would like an efficient form for this, so we don't have to do
544 // a lot of extra uniquing.
545 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
548 OutStreamer->EmitLabel(PICBase);
551 case PPC::UpdateGBR: {
552 // Transform %Rd = UpdateGBR(%Rt, %Ri)
553 // Into: lwz %Rt, .L0$poff - .L0$pb(%Ri)
555 // Get the offset from the GOT Base Register to the GOT
556 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
557 MCSymbol *PICOffset =
558 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol();
559 TmpInst.setOpcode(PPC::LWZ);
561 MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
563 MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
564 MCSymbolRefExpr::VK_None,
566 const MCOperand TR = TmpInst.getOperand(1);
567 const MCOperand PICR = TmpInst.getOperand(0);
569 // Step 1: lwz %Rt, .L$poff - .L$pb(%Ri)
570 TmpInst.getOperand(1) =
571 MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
572 TmpInst.getOperand(0) = TR;
573 TmpInst.getOperand(2) = PICR;
574 EmitToStreamer(*OutStreamer, TmpInst);
576 TmpInst.setOpcode(PPC::ADD4);
577 TmpInst.getOperand(0) = PICR;
578 TmpInst.getOperand(1) = TR;
579 TmpInst.getOperand(2) = PICR;
580 EmitToStreamer(*OutStreamer, TmpInst);
584 // Transform %R3 = LWZtoc <ga:@min1>, %R2
585 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
587 // Change the opcode to LWZ, and the global address operand to be a
588 // reference to the GOT entry we will synthesize later.
589 TmpInst.setOpcode(PPC::LWZ);
590 const MachineOperand &MO = MI->getOperand(1);
592 // Map symbol -> label of TOC entry
593 assert(MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress());
594 MCSymbol *MOSymbol = nullptr;
596 MOSymbol = getSymbol(MO.getGlobal());
598 MOSymbol = GetCPISymbol(MO.getIndex());
600 MOSymbol = GetJTISymbol(MO.getIndex());
601 else if (MO.isBlockAddress())
602 MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
604 if (PL == PICLevel::Small) {
606 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
608 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
610 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
613 MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None,
616 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
618 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
619 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
621 EmitToStreamer(*OutStreamer, TmpInst);
628 // Transform %X3 = LDtoc <ga:@min1>, %X2
629 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
631 // Change the opcode to LD, and the global address operand to be a
632 // reference to the TOC entry we will synthesize later.
633 TmpInst.setOpcode(PPC::LD);
634 const MachineOperand &MO = MI->getOperand(1);
636 // Map symbol -> label of TOC entry
637 assert(MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress());
638 MCSymbol *MOSymbol = nullptr;
640 MOSymbol = getSymbol(MO.getGlobal());
642 MOSymbol = GetCPISymbol(MO.getIndex());
644 MOSymbol = GetJTISymbol(MO.getIndex());
645 else if (MO.isBlockAddress())
646 MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
648 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
651 MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_PPC_TOC,
653 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
654 EmitToStreamer(*OutStreamer, TmpInst);
658 case PPC::ADDIStocHA: {
659 // Transform %Xd = ADDIStocHA %X2, <ga:@sym>
660 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
662 // Change the opcode to ADDIS8. If the global address is external, has
663 // common linkage, is a non-local function address, or is a jump table
664 // address, then generate a TOC entry and reference that. Otherwise
665 // reference the symbol directly.
666 TmpInst.setOpcode(PPC::ADDIS8);
667 const MachineOperand &MO = MI->getOperand(2);
668 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
669 MO.isBlockAddress()) &&
670 "Invalid operand for ADDIStocHA!");
671 MCSymbol *MOSymbol = nullptr;
672 bool IsExternal = false;
673 bool IsNonLocalFunction = false;
674 bool IsCommon = false;
675 bool IsAvailExt = false;
678 const GlobalValue *GV = MO.getGlobal();
679 MOSymbol = getSymbol(GV);
680 IsExternal = GV->isDeclaration();
681 IsCommon = GV->hasCommonLinkage();
682 IsNonLocalFunction = GV->getType()->getElementType()->isFunctionTy() &&
683 !GV->isStrongDefinitionForLinker();
684 IsAvailExt = GV->hasAvailableExternallyLinkage();
685 } else if (MO.isCPI())
686 MOSymbol = GetCPISymbol(MO.getIndex());
688 MOSymbol = GetJTISymbol(MO.getIndex());
689 else if (MO.isBlockAddress())
690 MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
692 if (IsExternal || IsNonLocalFunction || IsCommon || IsAvailExt ||
693 MO.isJTI() || MO.isBlockAddress() ||
694 TM.getCodeModel() == CodeModel::Large)
695 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
698 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_HA,
700 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
701 EmitToStreamer(*OutStreamer, TmpInst);
705 // Transform %Xd = LDtocL <ga:@sym>, %Xs
706 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
708 // Change the opcode to LD. If the global address is external, has
709 // common linkage, or is a jump table address, then reference the
710 // associated TOC entry. Otherwise reference the symbol directly.
711 TmpInst.setOpcode(PPC::LD);
712 const MachineOperand &MO = MI->getOperand(1);
713 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
714 MO.isBlockAddress()) &&
715 "Invalid operand for LDtocL!");
716 MCSymbol *MOSymbol = nullptr;
719 MOSymbol = lookUpOrCreateTOCEntry(GetJTISymbol(MO.getIndex()));
720 else if (MO.isBlockAddress()) {
721 MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
722 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
724 else if (MO.isCPI()) {
725 MOSymbol = GetCPISymbol(MO.getIndex());
726 if (TM.getCodeModel() == CodeModel::Large)
727 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
729 else if (MO.isGlobal()) {
730 const GlobalValue *GValue = MO.getGlobal();
731 MOSymbol = getSymbol(GValue);
732 if (GValue->getType()->getElementType()->isFunctionTy() ||
733 GValue->isDeclaration() || GValue->hasCommonLinkage() ||
734 GValue->hasAvailableExternallyLinkage() ||
735 TM.getCodeModel() == CodeModel::Large)
736 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
740 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
742 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
743 EmitToStreamer(*OutStreamer, TmpInst);
746 case PPC::ADDItocL: {
747 // Transform %Xd = ADDItocL %Xs, <ga:@sym>
748 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
750 // Change the opcode to ADDI8. If the global address is external, then
751 // generate a TOC entry and reference that. Otherwise reference the
753 TmpInst.setOpcode(PPC::ADDI8);
754 const MachineOperand &MO = MI->getOperand(2);
755 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL");
756 MCSymbol *MOSymbol = nullptr;
757 bool IsExternal = false;
758 bool IsNonLocalFunction = false;
761 const GlobalValue *GV = MO.getGlobal();
762 MOSymbol = getSymbol(GV);
763 IsExternal = GV->isDeclaration();
764 IsNonLocalFunction = GV->getType()->getElementType()->isFunctionTy() &&
765 !GV->isStrongDefinitionForLinker();
766 } else if (MO.isCPI())
767 MOSymbol = GetCPISymbol(MO.getIndex());
769 if (IsNonLocalFunction || IsExternal ||
770 TM.getCodeModel() == CodeModel::Large)
771 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
774 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
776 TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
777 EmitToStreamer(*OutStreamer, TmpInst);
780 case PPC::ADDISgotTprelHA: {
781 // Transform: %Xd = ADDISgotTprelHA %X2, <ga:@sym>
782 // Into: %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
783 assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
784 const MachineOperand &MO = MI->getOperand(2);
785 const GlobalValue *GValue = MO.getGlobal();
786 MCSymbol *MOSymbol = getSymbol(GValue);
787 const MCExpr *SymGotTprel =
788 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
790 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
791 .addReg(MI->getOperand(0).getReg())
792 .addReg(MI->getOperand(1).getReg())
793 .addExpr(SymGotTprel));
796 case PPC::LDgotTprelL:
797 case PPC::LDgotTprelL32: {
798 // Transform %Xd = LDgotTprelL <ga:@sym>, %Xs
799 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
801 // Change the opcode to LD.
802 TmpInst.setOpcode(isPPC64 ? PPC::LD : PPC::LWZ);
803 const MachineOperand &MO = MI->getOperand(1);
804 const GlobalValue *GValue = MO.getGlobal();
805 MCSymbol *MOSymbol = getSymbol(GValue);
807 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO,
809 TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
810 EmitToStreamer(*OutStreamer, TmpInst);
814 case PPC::PPC32PICGOT: {
815 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
816 MCSymbol *GOTRef = OutContext.createTempSymbol();
817 MCSymbol *NextInstr = OutContext.createTempSymbol();
819 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
820 // FIXME: We would like an efficient form for this, so we don't have to do
821 // a lot of extra uniquing.
822 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
823 const MCExpr *OffsExpr =
824 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
825 MCSymbolRefExpr::create(GOTRef, OutContext),
827 OutStreamer->EmitLabel(GOTRef);
828 OutStreamer->EmitValue(OffsExpr, 4);
829 OutStreamer->EmitLabel(NextInstr);
830 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
831 .addReg(MI->getOperand(0).getReg()));
832 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
833 .addReg(MI->getOperand(1).getReg())
835 .addReg(MI->getOperand(0).getReg()));
836 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
837 .addReg(MI->getOperand(0).getReg())
838 .addReg(MI->getOperand(1).getReg())
839 .addReg(MI->getOperand(0).getReg()));
842 case PPC::PPC32GOT: {
843 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
844 const MCExpr *SymGotTlsL =
845 MCSymbolRefExpr::create(GOTSymbol, MCSymbolRefExpr::VK_PPC_LO,
847 const MCExpr *SymGotTlsHA =
848 MCSymbolRefExpr::create(GOTSymbol, MCSymbolRefExpr::VK_PPC_HA,
850 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
851 .addReg(MI->getOperand(0).getReg())
852 .addExpr(SymGotTlsL));
853 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
854 .addReg(MI->getOperand(0).getReg())
855 .addReg(MI->getOperand(0).getReg())
856 .addExpr(SymGotTlsHA));
859 case PPC::ADDIStlsgdHA: {
860 // Transform: %Xd = ADDIStlsgdHA %X2, <ga:@sym>
861 // Into: %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
862 assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
863 const MachineOperand &MO = MI->getOperand(2);
864 const GlobalValue *GValue = MO.getGlobal();
865 MCSymbol *MOSymbol = getSymbol(GValue);
866 const MCExpr *SymGotTlsGD =
867 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
869 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
870 .addReg(MI->getOperand(0).getReg())
871 .addReg(MI->getOperand(1).getReg())
872 .addExpr(SymGotTlsGD));
875 case PPC::ADDItlsgdL:
876 // Transform: %Xd = ADDItlsgdL %Xs, <ga:@sym>
877 // Into: %Xd = ADDI8 %Xs, sym@got@tlsgd@l
878 case PPC::ADDItlsgdL32: {
879 // Transform: %Rd = ADDItlsgdL32 %Rs, <ga:@sym>
880 // Into: %Rd = ADDI %Rs, sym@got@tlsgd
881 const MachineOperand &MO = MI->getOperand(2);
882 const GlobalValue *GValue = MO.getGlobal();
883 MCSymbol *MOSymbol = getSymbol(GValue);
884 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
885 MOSymbol, Subtarget->isPPC64() ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
886 : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
888 EmitToStreamer(*OutStreamer,
889 MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
890 .addReg(MI->getOperand(0).getReg())
891 .addReg(MI->getOperand(1).getReg())
892 .addExpr(SymGotTlsGD));
895 case PPC::GETtlsADDR:
896 // Transform: %X3 = GETtlsADDR %X3, <ga:@sym>
897 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
898 case PPC::GETtlsADDR32: {
899 // Transform: %R3 = GETtlsADDR32 %R3, <ga:@sym>
900 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
901 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
904 case PPC::ADDIStlsldHA: {
905 // Transform: %Xd = ADDIStlsldHA %X2, <ga:@sym>
906 // Into: %Xd = ADDIS8 %X2, sym@got@tlsld@ha
907 assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
908 const MachineOperand &MO = MI->getOperand(2);
909 const GlobalValue *GValue = MO.getGlobal();
910 MCSymbol *MOSymbol = getSymbol(GValue);
911 const MCExpr *SymGotTlsLD =
912 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
914 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
915 .addReg(MI->getOperand(0).getReg())
916 .addReg(MI->getOperand(1).getReg())
917 .addExpr(SymGotTlsLD));
920 case PPC::ADDItlsldL:
921 // Transform: %Xd = ADDItlsldL %Xs, <ga:@sym>
922 // Into: %Xd = ADDI8 %Xs, sym@got@tlsld@l
923 case PPC::ADDItlsldL32: {
924 // Transform: %Rd = ADDItlsldL32 %Rs, <ga:@sym>
925 // Into: %Rd = ADDI %Rs, sym@got@tlsld
926 const MachineOperand &MO = MI->getOperand(2);
927 const GlobalValue *GValue = MO.getGlobal();
928 MCSymbol *MOSymbol = getSymbol(GValue);
929 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
930 MOSymbol, Subtarget->isPPC64() ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
931 : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
933 EmitToStreamer(*OutStreamer,
934 MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
935 .addReg(MI->getOperand(0).getReg())
936 .addReg(MI->getOperand(1).getReg())
937 .addExpr(SymGotTlsLD));
940 case PPC::GETtlsldADDR:
941 // Transform: %X3 = GETtlsldADDR %X3, <ga:@sym>
942 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
943 case PPC::GETtlsldADDR32: {
944 // Transform: %R3 = GETtlsldADDR32 %R3, <ga:@sym>
945 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
946 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
949 case PPC::ADDISdtprelHA:
950 // Transform: %Xd = ADDISdtprelHA %X3, <ga:@sym>
951 // Into: %Xd = ADDIS8 %X3, sym@dtprel@ha
952 case PPC::ADDISdtprelHA32: {
953 // Transform: %Rd = ADDISdtprelHA32 %R3, <ga:@sym>
954 // Into: %Rd = ADDIS %R3, sym@dtprel@ha
955 const MachineOperand &MO = MI->getOperand(2);
956 const GlobalValue *GValue = MO.getGlobal();
957 MCSymbol *MOSymbol = getSymbol(GValue);
958 const MCExpr *SymDtprel =
959 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
963 MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDIS8 : PPC::ADDIS)
964 .addReg(MI->getOperand(0).getReg())
965 .addReg(Subtarget->isPPC64() ? PPC::X3 : PPC::R3)
966 .addExpr(SymDtprel));
969 case PPC::ADDIdtprelL:
970 // Transform: %Xd = ADDIdtprelL %Xs, <ga:@sym>
971 // Into: %Xd = ADDI8 %Xs, sym@dtprel@l
972 case PPC::ADDIdtprelL32: {
973 // Transform: %Rd = ADDIdtprelL32 %Rs, <ga:@sym>
974 // Into: %Rd = ADDI %Rs, sym@dtprel@l
975 const MachineOperand &MO = MI->getOperand(2);
976 const GlobalValue *GValue = MO.getGlobal();
977 MCSymbol *MOSymbol = getSymbol(GValue);
978 const MCExpr *SymDtprel =
979 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
981 EmitToStreamer(*OutStreamer,
982 MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
983 .addReg(MI->getOperand(0).getReg())
984 .addReg(MI->getOperand(1).getReg())
985 .addExpr(SymDtprel));
990 if (!Subtarget->hasMFOCRF()) {
991 // Transform: %R3 = MFOCRF %CR7
992 // Into: %R3 = MFCR ;; cr7
994 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
995 OutStreamer->AddComment(PPCInstPrinter::
996 getRegisterName(MI->getOperand(1).getReg()));
997 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
998 .addReg(MI->getOperand(0).getReg()));
1004 if (!Subtarget->hasMFOCRF()) {
1005 // Transform: %CR7 = MTOCRF %R3
1006 // Into: MTCRF mask, %R3 ;; cr7
1007 unsigned NewOpcode =
1008 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1009 unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1010 ->getEncodingValue(MI->getOperand(0).getReg());
1011 OutStreamer->AddComment(PPCInstPrinter::
1012 getRegisterName(MI->getOperand(0).getReg()));
1013 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1015 .addReg(MI->getOperand(1).getReg()));
1023 // Verify alignment is legal, so we don't create relocations
1024 // that can't be supported.
1025 // FIXME: This test is currently disabled for Darwin. The test
1026 // suite shows a handful of test cases that fail this check for
1027 // Darwin. Those need to be investigated before this sanity test
1028 // can be enabled for those subtargets.
1029 if (!Subtarget->isDarwin()) {
1030 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1031 const MachineOperand &MO = MI->getOperand(OpNum);
1032 if (MO.isGlobal() && MO.getGlobal()->getAlignment() < 4)
1033 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1035 // Now process the instruction normally.
1040 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
1041 EmitToStreamer(*OutStreamer, TmpInst);
1044 void PPCLinuxAsmPrinter::EmitStartOfAsmFile(Module &M) {
1045 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1046 PPCTargetStreamer *TS =
1047 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1050 TS->emitAbiVersion(2);
1053 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1054 TM.getRelocationModel() != Reloc::PIC_)
1055 return AsmPrinter::EmitStartOfAsmFile(M);
1057 if (M.getPICLevel() == PICLevel::Small)
1058 return AsmPrinter::EmitStartOfAsmFile(M);
1060 OutStreamer->SwitchSection(OutContext.getELFSection(
1061 ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1063 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1064 MCSymbol *CurrentPos = OutContext.createTempSymbol();
1066 OutStreamer->EmitLabel(CurrentPos);
1068 // The GOT pointer points to the middle of the GOT, in order to reference the
1069 // entire 64kB range. 0x8000 is the midpoint.
1070 const MCExpr *tocExpr =
1071 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1072 MCConstantExpr::create(0x8000, OutContext),
1075 OutStreamer->EmitAssignment(TOCSym, tocExpr);
1077 OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1080 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
1081 // linux/ppc32 - Normal entry label.
1082 if (!Subtarget->isPPC64() &&
1083 (TM.getRelocationModel() != Reloc::PIC_ ||
1084 MF->getFunction()->getParent()->getPICLevel() == PICLevel::Small))
1085 return AsmPrinter::EmitFunctionEntryLabel();
1087 if (!Subtarget->isPPC64()) {
1088 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1089 if (PPCFI->usesPICBase()) {
1090 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol();
1091 MCSymbol *PICBase = MF->getPICBaseSymbol();
1092 OutStreamer->EmitLabel(RelocSymbol);
1094 const MCExpr *OffsExpr =
1095 MCBinaryExpr::createSub(
1096 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1098 MCSymbolRefExpr::create(PICBase, OutContext),
1100 OutStreamer->EmitValue(OffsExpr, 4);
1101 OutStreamer->EmitLabel(CurrentFnSym);
1104 return AsmPrinter::EmitFunctionEntryLabel();
1107 // ELFv2 ABI - Normal entry label.
1108 if (Subtarget->isELFv2ABI())
1109 return AsmPrinter::EmitFunctionEntryLabel();
1111 // Emit an official procedure descriptor.
1112 MCSectionSubPair Current = OutStreamer->getCurrentSection();
1113 MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1114 ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1115 OutStreamer->SwitchSection(Section);
1116 OutStreamer->EmitLabel(CurrentFnSym);
1117 OutStreamer->EmitValueToAlignment(8);
1118 MCSymbol *Symbol1 = CurrentFnSymForSize;
1119 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1121 OutStreamer->EmitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1123 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1124 // Generates a R_PPC64_TOC relocation for TOC base insertion.
1125 OutStreamer->EmitValue(
1126 MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1128 // Emit a null environment pointer.
1129 OutStreamer->EmitIntValue(0, 8 /* size */);
1130 OutStreamer->SwitchSection(Current.first, Current.second);
1134 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
1135 const DataLayout &DL = getDataLayout();
1137 bool isPPC64 = DL.getPointerSizeInBits() == 64;
1139 PPCTargetStreamer &TS =
1140 static_cast<PPCTargetStreamer &>(*OutStreamer->getTargetStreamer());
1143 MCSectionELF *Section;
1146 Section = OutStreamer->getContext().getELFSection(
1147 ".toc", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1149 Section = OutStreamer->getContext().getELFSection(
1150 ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1151 OutStreamer->SwitchSection(Section);
1153 for (MapVector<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
1154 E = TOC.end(); I != E; ++I) {
1155 OutStreamer->EmitLabel(I->second);
1156 MCSymbol *S = I->first;
1160 OutStreamer->EmitSymbolValue(S, 4);
1164 return AsmPrinter::doFinalization(M);
1167 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1168 void PPCLinuxAsmPrinter::EmitFunctionBodyStart() {
1169 // In the ELFv2 ABI, in functions that use the TOC register, we need to
1170 // provide two entry points. The ABI guarantees that when calling the
1171 // local entry point, r2 is set up by the caller to contain the TOC base
1172 // for this function, and when calling the global entry point, r12 is set
1173 // up by the caller to hold the address of the global entry point. We
1174 // thus emit a prefix sequence along the following lines:
1177 // # global entry point
1178 // addis r2,r12,(.TOC.-func)@ha
1179 // addi r2,r2,(.TOC.-func)@l
1180 // .localentry func, .-func
1181 // # local entry point, followed by function body
1183 // This ensures we have r2 set up correctly while executing the function
1184 // body, no matter which entry point is called.
1185 if (Subtarget->isELFv2ABI()
1186 // Only do all that if the function uses r2 in the first place.
1187 && !MF->getRegInfo().use_empty(PPC::X2)) {
1189 MCSymbol *GlobalEntryLabel = OutContext.createTempSymbol();
1190 OutStreamer->EmitLabel(GlobalEntryLabel);
1191 const MCSymbolRefExpr *GlobalEntryLabelExp =
1192 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1194 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1195 const MCExpr *TOCDeltaExpr =
1196 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1197 GlobalEntryLabelExp, OutContext);
1199 const MCExpr *TOCDeltaHi =
1200 PPCMCExpr::createHa(TOCDeltaExpr, false, OutContext);
1201 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1204 .addExpr(TOCDeltaHi));
1206 const MCExpr *TOCDeltaLo =
1207 PPCMCExpr::createLo(TOCDeltaExpr, false, OutContext);
1208 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1211 .addExpr(TOCDeltaLo));
1213 MCSymbol *LocalEntryLabel = OutContext.createTempSymbol();
1214 OutStreamer->EmitLabel(LocalEntryLabel);
1215 const MCSymbolRefExpr *LocalEntryLabelExp =
1216 MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1217 const MCExpr *LocalOffsetExp =
1218 MCBinaryExpr::createSub(LocalEntryLabelExp,
1219 GlobalEntryLabelExp, OutContext);
1221 PPCTargetStreamer *TS =
1222 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1225 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1229 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1232 void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
1233 // Only the 64-bit target requires a traceback table. For now,
1234 // we only emit the word of zeroes that GDB requires to find
1235 // the end of the function, and zeroes for the eight-byte
1236 // mandatory fields.
1237 // FIXME: We should fill in the eight-byte mandatory fields as described in
1238 // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1239 // currently make use of these fields).
1240 if (Subtarget->isPPC64()) {
1241 OutStreamer->EmitIntValue(0, 4/*size*/);
1242 OutStreamer->EmitIntValue(0, 8/*size*/);
1246 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
1247 static const char *const CPUDirectives[] = {
1271 // Get the numerically largest directive.
1272 // FIXME: How should we merge darwin directives?
1273 unsigned Directive = PPC::DIR_NONE;
1274 for (const Function &F : M) {
1275 const PPCSubtarget &STI = TM.getSubtarget<PPCSubtarget>(F);
1276 unsigned FDir = STI.getDarwinDirective();
1277 Directive = Directive > FDir ? FDir : STI.getDarwinDirective();
1278 if (STI.hasMFOCRF() && Directive < PPC::DIR_970)
1279 Directive = PPC::DIR_970;
1280 if (STI.hasAltivec() && Directive < PPC::DIR_7400)
1281 Directive = PPC::DIR_7400;
1282 if (STI.isPPC64() && Directive < PPC::DIR_64)
1283 Directive = PPC::DIR_64;
1286 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
1288 assert(Directive < array_lengthof(CPUDirectives) &&
1289 "CPUDirectives[] might not be up-to-date!");
1290 PPCTargetStreamer &TStreamer =
1291 *static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1292 TStreamer.emitMachine(CPUDirectives[Directive]);
1294 // Prime text sections so they are adjacent. This reduces the likelihood a
1295 // large data or debug section causes a branch to exceed 16M limit.
1296 const TargetLoweringObjectFileMachO &TLOFMacho =
1297 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1298 OutStreamer->SwitchSection(TLOFMacho.getTextCoalSection());
1299 if (TM.getRelocationModel() == Reloc::PIC_) {
1300 OutStreamer->SwitchSection(
1301 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
1302 MachO::S_SYMBOL_STUBS |
1303 MachO::S_ATTR_PURE_INSTRUCTIONS,
1304 32, SectionKind::getText()));
1305 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
1306 OutStreamer->SwitchSection(
1307 OutContext.getMachOSection("__TEXT","__symbol_stub1",
1308 MachO::S_SYMBOL_STUBS |
1309 MachO::S_ATTR_PURE_INSTRUCTIONS,
1310 16, SectionKind::getText()));
1312 OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1315 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
1316 // Remove $stub suffix, add $lazy_ptr.
1317 StringRef NoStub = Sym->getName().substr(0, Sym->getName().size()-5);
1318 return Ctx.getOrCreateSymbol(NoStub + "$lazy_ptr");
1321 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
1322 // Add $tmp suffix to $stub, yielding $stub$tmp.
1323 return Ctx.getOrCreateSymbol(Sym->getName() + "$tmp");
1326 void PPCDarwinAsmPrinter::
1327 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
1328 bool isPPC64 = getDataLayout().getPointerSizeInBits() == 64;
1330 // Construct a local MCSubtargetInfo and shadow EmitToStreamer here.
1331 // This is because the MachineFunction won't exist (but have not yet been
1332 // freed) and since we're at the global level we can use the default
1333 // constructed subtarget.
1334 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
1335 TM.getTargetTriple().str(), TM.getTargetCPU(),
1336 TM.getTargetFeatureString()));
1337 auto EmitToStreamer = [&STI] (MCStreamer &S, const MCInst &Inst) {
1338 S.EmitInstruction(Inst, *STI);
1341 const TargetLoweringObjectFileMachO &TLOFMacho =
1342 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1344 // .lazy_symbol_pointer
1345 MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
1347 // Output stubs for dynamically-linked functions
1348 if (TM.getRelocationModel() == Reloc::PIC_) {
1349 MCSection *StubSection = OutContext.getMachOSection(
1350 "__TEXT", "__picsymbolstub1",
1351 MachO::S_SYMBOL_STUBS | MachO::S_ATTR_PURE_INSTRUCTIONS, 32,
1352 SectionKind::getText());
1353 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1354 OutStreamer->SwitchSection(StubSection);
1357 MCSymbol *Stub = Stubs[i].first;
1358 MCSymbol *RawSym = Stubs[i].second.getPointer();
1359 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
1360 MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
1362 OutStreamer->EmitLabel(Stub);
1363 OutStreamer->EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
1365 const MCExpr *Anon = MCSymbolRefExpr::create(AnonSymbol, OutContext);
1366 const MCExpr *LazyPtrExpr = MCSymbolRefExpr::create(LazyPtr, OutContext);
1368 MCBinaryExpr::createSub(LazyPtrExpr, Anon, OutContext);
1371 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR).addReg(PPC::R0));
1372 // bcl 20, 31, AnonSymbol
1373 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCLalways).addExpr(Anon));
1374 OutStreamer->EmitLabel(AnonSymbol);
1376 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR).addReg(PPC::R11));
1377 // addis r11, r11, ha16(LazyPtr - AnonSymbol)
1378 const MCExpr *SubHa16 = PPCMCExpr::createHa(Sub, true, OutContext);
1379 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1384 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR).addReg(PPC::R0));
1386 // ldu r12, lo16(LazyPtr - AnonSymbol)(r11)
1387 // lwzu r12, lo16(LazyPtr - AnonSymbol)(r11)
1388 const MCExpr *SubLo16 = PPCMCExpr::createLo(Sub, true, OutContext);
1389 EmitToStreamer(*OutStreamer, MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
1391 .addExpr(SubLo16).addExpr(SubLo16)
1394 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
1396 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTR));
1398 OutStreamer->SwitchSection(LSPSection);
1399 OutStreamer->EmitLabel(LazyPtr);
1400 OutStreamer->EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
1402 MCSymbol *DyldStubBindingHelper =
1403 OutContext.getOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
1405 // .quad dyld_stub_binding_helper
1406 OutStreamer->EmitSymbolValue(DyldStubBindingHelper, 8);
1408 // .long dyld_stub_binding_helper
1409 OutStreamer->EmitSymbolValue(DyldStubBindingHelper, 4);
1412 OutStreamer->AddBlankLine();
1416 MCSection *StubSection = OutContext.getMachOSection(
1417 "__TEXT", "__symbol_stub1",
1418 MachO::S_SYMBOL_STUBS | MachO::S_ATTR_PURE_INSTRUCTIONS, 16,
1419 SectionKind::getText());
1420 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1421 MCSymbol *Stub = Stubs[i].first;
1422 MCSymbol *RawSym = Stubs[i].second.getPointer();
1423 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
1424 const MCExpr *LazyPtrExpr = MCSymbolRefExpr::create(LazyPtr, OutContext);
1426 OutStreamer->SwitchSection(StubSection);
1428 OutStreamer->EmitLabel(Stub);
1429 OutStreamer->EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
1431 // lis r11, ha16(LazyPtr)
1432 const MCExpr *LazyPtrHa16 =
1433 PPCMCExpr::createHa(LazyPtrExpr, true, OutContext);
1434 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LIS)
1436 .addExpr(LazyPtrHa16));
1438 // ldu r12, lo16(LazyPtr)(r11)
1439 // lwzu r12, lo16(LazyPtr)(r11)
1440 const MCExpr *LazyPtrLo16 =
1441 PPCMCExpr::createLo(LazyPtrExpr, true, OutContext);
1442 EmitToStreamer(*OutStreamer, MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
1444 .addExpr(LazyPtrLo16).addExpr(LazyPtrLo16)
1448 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
1450 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTR));
1452 OutStreamer->SwitchSection(LSPSection);
1453 OutStreamer->EmitLabel(LazyPtr);
1454 OutStreamer->EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
1456 MCSymbol *DyldStubBindingHelper =
1457 OutContext.getOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
1459 // .quad dyld_stub_binding_helper
1460 OutStreamer->EmitSymbolValue(DyldStubBindingHelper, 8);
1462 // .long dyld_stub_binding_helper
1463 OutStreamer->EmitSymbolValue(DyldStubBindingHelper, 4);
1467 OutStreamer->AddBlankLine();
1471 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1472 bool isPPC64 = getDataLayout().getPointerSizeInBits() == 64;
1474 // Darwin/PPC always uses mach-o.
1475 const TargetLoweringObjectFileMachO &TLOFMacho =
1476 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1477 MachineModuleInfoMachO &MMIMacho =
1478 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1480 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
1482 EmitFunctionStubs(Stubs);
1484 if (MAI->doesSupportExceptionHandling() && MMI) {
1485 // Add the (possibly multiple) personalities to the set of global values.
1486 // Only referenced functions get into the Personalities list.
1487 const std::vector<const Function*> &Personalities = MMI->getPersonalities();
1488 for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
1489 E = Personalities.end(); I != E; ++I) {
1491 MCSymbol *NLPSym = getSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
1492 MachineModuleInfoImpl::StubValueTy &StubSym =
1493 MMIMacho.getGVStubEntry(NLPSym);
1494 StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(*I), true);
1499 // Output stubs for dynamically-linked functions.
1500 Stubs = MMIMacho.GetGVStubList();
1502 // Output macho stubs for external and common global variables.
1503 if (!Stubs.empty()) {
1504 // Switch with ".non_lazy_symbol_pointer" directive.
1505 OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1506 EmitAlignment(isPPC64 ? 3 : 2);
1508 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1510 OutStreamer->EmitLabel(Stubs[i].first);
1511 // .indirect_symbol _foo
1512 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1513 OutStreamer->EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
1516 // External to current translation unit.
1517 OutStreamer->EmitIntValue(0, isPPC64 ? 8 : 4/*size*/);
1519 // Internal to current translation unit.
1521 // When we place the LSDA into the TEXT section, the type info pointers
1522 // need to be indirect and pc-rel. We accomplish this by using NLPs.
1523 // However, sometimes the types are local to the file. So we need to
1524 // fill in the value for the NLP in those cases.
1525 OutStreamer->EmitValue(MCSymbolRefExpr::create(MCSym.getPointer(),
1527 isPPC64 ? 8 : 4/*size*/);
1531 OutStreamer->AddBlankLine();
1534 Stubs = MMIMacho.GetHiddenGVStubList();
1535 if (!Stubs.empty()) {
1536 OutStreamer->SwitchSection(getObjFileLowering().getDataSection());
1537 EmitAlignment(isPPC64 ? 3 : 2);
1539 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1541 OutStreamer->EmitLabel(Stubs[i].first);
1543 OutStreamer->EmitValue(MCSymbolRefExpr::
1544 create(Stubs[i].second.getPointer(),
1546 isPPC64 ? 8 : 4/*size*/);
1550 OutStreamer->AddBlankLine();
1553 // Funny Darwin hack: This flag tells the linker that no global symbols
1554 // contain code that falls through to other global symbols (e.g. the obvious
1555 // implementation of multiple entry points). If this doesn't occur, the
1556 // linker can safely perform dead code stripping. Since LLVM never generates
1557 // code that does this, it is always safe to set.
1558 OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1560 return AsmPrinter::doFinalization(M);
1563 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1564 /// for a MachineFunction to the given output stream, in a format that the
1565 /// Darwin assembler can deal with.
1568 createPPCAsmPrinterPass(TargetMachine &tm,
1569 std::unique_ptr<MCStreamer> &&Streamer) {
1570 if (tm.getTargetTriple().isMacOSX())
1571 return new PPCDarwinAsmPrinter(tm, std::move(Streamer));
1572 return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
1575 // Force static initialization.
1576 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1577 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1578 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1579 TargetRegistry::RegisterAsmPrinter(ThePPC64LETarget, createPPCAsmPrinterPass);