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 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
21 #include "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSectionMachO.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Support/Mangler.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
55 STATISTIC(EmittedInsts, "Number of machine instrs printed");
58 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
61 std::string Stub, LazyPtr, AnonSymbol;
65 void Init(const GlobalValue *GV, Mangler *Mang) {
66 // Already initialized.
67 if (!Stub.empty()) return;
68 Stub = Mang->getMangledName(GV, "$stub", true);
69 LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
70 AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
73 void Init(const std::string &GV, Mangler *Mang) {
74 // Already initialized.
75 if (!Stub.empty()) return;
76 Stub = Mang->makeNameProper(GV + "$stub",
78 LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
80 AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
85 StringMap<FnStubInfo> FnStubs;
86 StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
87 const PPCSubtarget &Subtarget;
90 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
91 const MCAsmInfo *T, bool V)
92 : AsmPrinter(O, TM, T, V),
93 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
95 virtual const char *getPassName() const {
96 return "PowerPC Assembly Printer";
99 PPCTargetMachine &getTM() {
100 return static_cast<PPCTargetMachine&>(TM);
103 unsigned enumRegToMachineReg(unsigned enumReg) {
105 default: llvm_unreachable("Unhandled register!");
106 case PPC::CR0: return 0;
107 case PPC::CR1: return 1;
108 case PPC::CR2: return 2;
109 case PPC::CR3: return 3;
110 case PPC::CR4: return 4;
111 case PPC::CR5: return 5;
112 case PPC::CR6: return 6;
113 case PPC::CR7: return 7;
118 /// printInstruction - This method is automatically generated by tablegen
119 /// from the instruction set description. This method returns true if the
120 /// machine instruction was sufficiently described to print it, otherwise it
122 void printInstruction(const MachineInstr *MI);
123 static const char *getRegisterName(unsigned RegNo);
126 void printMachineInstruction(const MachineInstr *MI);
127 void printOp(const MachineOperand &MO);
129 /// stripRegisterPrefix - This method strips the character prefix from a
130 /// register name so that only the number is left. Used by for linux asm.
131 const char *stripRegisterPrefix(const char *RegName) {
132 switch (RegName[0]) {
135 case 'v': return RegName + 1;
136 case 'c': if (RegName[1] == 'r') return RegName + 2;
142 /// printRegister - Print register according to target requirements.
144 void printRegister(const MachineOperand &MO, bool R0AsZero) {
145 unsigned RegNo = MO.getReg();
146 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
148 // If we should use 0 for R0.
149 if (R0AsZero && RegNo == PPC::R0) {
154 const char *RegName = getRegisterName(RegNo);
155 // Linux assembler (Others?) does not take register mnemonics.
156 // FIXME - What about special registers used in mfspr/mtspr?
157 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
161 void printOperand(const MachineInstr *MI, unsigned OpNo) {
162 const MachineOperand &MO = MI->getOperand(OpNo);
164 printRegister(MO, false);
165 } else if (MO.isImm()) {
172 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
173 unsigned AsmVariant, const char *ExtraCode);
174 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
175 unsigned AsmVariant, const char *ExtraCode);
178 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
179 char value = MI->getOperand(OpNo).getImm();
180 value = (value << (32-5)) >> (32-5);
183 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
184 unsigned char value = MI->getOperand(OpNo).getImm();
185 assert(value <= 31 && "Invalid u5imm argument!");
186 O << (unsigned int)value;
188 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
189 unsigned char value = MI->getOperand(OpNo).getImm();
190 assert(value <= 63 && "Invalid u6imm argument!");
191 O << (unsigned int)value;
193 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
194 O << (short)MI->getOperand(OpNo).getImm();
196 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
197 O << (unsigned short)MI->getOperand(OpNo).getImm();
199 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
200 if (MI->getOperand(OpNo).isImm()) {
201 O << (short)(MI->getOperand(OpNo).getImm()*4);
204 printOp(MI->getOperand(OpNo));
205 if (TM.getRelocationModel() == Reloc::PIC_)
206 O << "-\"L" << getFunctionNumber() << "$pb\")";
211 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
212 // Branches can take an immediate operand. This is used by the branch
213 // selection pass to print $+8, an eight byte displacement from the PC.
214 if (MI->getOperand(OpNo).isImm()) {
215 O << "$+" << MI->getOperand(OpNo).getImm()*4;
217 printOp(MI->getOperand(OpNo));
220 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
221 const MachineOperand &MO = MI->getOperand(OpNo);
222 if (TM.getRelocationModel() != Reloc::Static) {
223 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
224 GlobalValue *GV = MO.getGlobal();
225 if (GV->isDeclaration() || GV->isWeakForLinker()) {
226 // Dynamically-resolved functions need a stub for the function.
227 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
228 FnInfo.Init(GV, Mang);
233 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
234 FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
235 FnInfo.Init(MO.getSymbolName(), Mang);
241 printOp(MI->getOperand(OpNo));
243 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
244 O << (int)MI->getOperand(OpNo).getImm()*4;
246 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
247 O << "\"L" << getFunctionNumber() << "$pb\"\n";
248 O << "\"L" << getFunctionNumber() << "$pb\":";
250 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
251 if (MI->getOperand(OpNo).isImm()) {
252 printS16ImmOperand(MI, OpNo);
254 if (Subtarget.isDarwin()) O << "ha16(";
255 printOp(MI->getOperand(OpNo));
256 if (TM.getRelocationModel() == Reloc::PIC_)
257 O << "-\"L" << getFunctionNumber() << "$pb\"";
258 if (Subtarget.isDarwin())
264 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
265 if (MI->getOperand(OpNo).isImm()) {
266 printS16ImmOperand(MI, OpNo);
268 if (Subtarget.isDarwin()) O << "lo16(";
269 printOp(MI->getOperand(OpNo));
270 if (TM.getRelocationModel() == Reloc::PIC_)
271 O << "-\"L" << getFunctionNumber() << "$pb\"";
272 if (Subtarget.isDarwin())
278 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
279 unsigned CCReg = MI->getOperand(OpNo).getReg();
280 unsigned RegNo = enumRegToMachineReg(CCReg);
281 O << (0x80 >> RegNo);
283 // The new addressing mode printers.
284 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
285 printSymbolLo(MI, OpNo);
287 if (MI->getOperand(OpNo+1).isReg() &&
288 MI->getOperand(OpNo+1).getReg() == PPC::R0)
291 printOperand(MI, OpNo+1);
294 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
295 if (MI->getOperand(OpNo).isImm())
296 printS16X4ImmOperand(MI, OpNo);
298 printSymbolLo(MI, OpNo);
300 if (MI->getOperand(OpNo+1).isReg() &&
301 MI->getOperand(OpNo+1).getReg() == PPC::R0)
304 printOperand(MI, OpNo+1);
308 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
309 // When used as the base register, r0 reads constant zero rather than
310 // the value contained in the register. For this reason, the darwin
311 // assembler requires that we print r0 as 0 (no r) when used as the base.
312 const MachineOperand &MO = MI->getOperand(OpNo);
313 printRegister(MO, true);
315 printOperand(MI, OpNo+1);
318 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
319 const MachineOperand &MO = MI->getOperand(OpNo);
321 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
323 GlobalValue *GV = MO.getGlobal();
325 std::string Name = Mang->getMangledName(GV);
327 // Map symbol -> label of TOC entry.
328 if (TOC.count(Name) == 0) {
330 Label += MAI->getPrivateGlobalPrefix();
332 Label += utostr(LabelID++);
337 O << TOC[Name] << "@toc";
340 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
341 const char *Modifier);
343 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
346 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
347 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
349 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
350 const MCAsmInfo *T, bool V)
351 : PPCAsmPrinter(O, TM, T, V){}
353 virtual const char *getPassName() const {
354 return "Linux PPC Assembly Printer";
357 bool runOnMachineFunction(MachineFunction &F);
358 bool doFinalization(Module &M);
360 void getAnalysisUsage(AnalysisUsage &AU) const {
361 AU.setPreservesAll();
362 AU.addRequired<MachineModuleInfo>();
363 AU.addRequired<DwarfWriter>();
364 PPCAsmPrinter::getAnalysisUsage(AU);
367 void PrintGlobalVariable(const GlobalVariable *GVar);
370 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
372 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
373 formatted_raw_ostream &OS;
375 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
376 const MCAsmInfo *T, bool V)
377 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
379 virtual const char *getPassName() const {
380 return "Darwin PPC Assembly Printer";
383 bool runOnMachineFunction(MachineFunction &F);
384 bool doFinalization(Module &M);
385 void EmitStartOfAsmFile(Module &M);
387 void getAnalysisUsage(AnalysisUsage &AU) const {
388 AU.setPreservesAll();
389 AU.addRequired<MachineModuleInfo>();
390 AU.addRequired<DwarfWriter>();
391 PPCAsmPrinter::getAnalysisUsage(AU);
394 void PrintGlobalVariable(const GlobalVariable *GVar);
396 } // end of anonymous namespace
398 // Include the auto-generated portion of the assembly writer
399 #include "PPCGenAsmWriter.inc"
401 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
402 switch (MO.getType()) {
403 case MachineOperand::MO_Immediate:
404 llvm_unreachable("printOp() does not handle immediate values");
406 case MachineOperand::MO_MachineBasicBlock:
407 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
409 case MachineOperand::MO_JumpTableIndex:
410 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
411 << '_' << MO.getIndex();
412 // FIXME: PIC relocation model
414 case MachineOperand::MO_ConstantPoolIndex:
415 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
416 << '_' << MO.getIndex();
418 case MachineOperand::MO_ExternalSymbol: {
419 // Computing the address of an external symbol, not calling it.
420 std::string Name(MAI->getGlobalPrefix());
421 Name += MO.getSymbolName();
423 if (TM.getRelocationModel() != Reloc::Static) {
424 GVStubs[Name] = Name+"$non_lazy_ptr";
425 Name += "$non_lazy_ptr";
430 case MachineOperand::MO_GlobalAddress: {
431 // Computing the address of a global symbol, not calling it.
432 GlobalValue *GV = MO.getGlobal();
435 // External or weakly linked global variables need non-lazily-resolved stubs
436 if (TM.getRelocationModel() != Reloc::Static &&
437 (GV->isDeclaration() || GV->isWeakForLinker())) {
438 if (!GV->hasHiddenVisibility()) {
439 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
440 GVStubs[Mang->getMangledName(GV)] = Name;
441 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
442 GV->hasAvailableExternallyLinkage()) {
443 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
444 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
446 Name = Mang->getMangledName(GV);
449 Name = Mang->getMangledName(GV);
453 printOffset(MO.getOffset());
458 O << "<unknown operand type: " << MO.getType() << ">";
463 /// PrintAsmOperand - Print out an operand for an inline asm expression.
465 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
467 const char *ExtraCode) {
468 // Does this asm operand have a single letter operand modifier?
469 if (ExtraCode && ExtraCode[0]) {
470 if (ExtraCode[1] != 0) return true; // Unknown modifier.
472 switch (ExtraCode[0]) {
473 default: return true; // Unknown modifier.
474 case 'c': // Don't print "$" before a global var name or constant.
475 // PPC never has a prefix.
476 printOperand(MI, OpNo);
478 case 'L': // Write second word of DImode reference.
479 // Verify that this operand has two consecutive registers.
480 if (!MI->getOperand(OpNo).isReg() ||
481 OpNo+1 == MI->getNumOperands() ||
482 !MI->getOperand(OpNo+1).isReg())
484 ++OpNo; // Return the high-part.
487 // Write 'i' if an integer constant, otherwise nothing. Used to print
489 if (MI->getOperand(OpNo).isImm())
495 printOperand(MI, OpNo);
499 // At the moment, all inline asm memory operands are a single register.
500 // In any case, the output of this routine should always be just one
501 // assembler operand.
503 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
505 const char *ExtraCode) {
506 if (ExtraCode && ExtraCode[0])
507 return true; // Unknown modifier.
508 assert (MI->getOperand(OpNo).isReg());
510 printOperand(MI, OpNo);
515 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
516 const char *Modifier) {
517 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
518 unsigned Code = MI->getOperand(OpNo).getImm();
519 if (!strcmp(Modifier, "cc")) {
520 switch ((PPC::Predicate)Code) {
521 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
522 case PPC::PRED_LT: O << "lt"; return;
523 case PPC::PRED_LE: O << "le"; return;
524 case PPC::PRED_EQ: O << "eq"; return;
525 case PPC::PRED_GE: O << "ge"; return;
526 case PPC::PRED_GT: O << "gt"; return;
527 case PPC::PRED_NE: O << "ne"; return;
528 case PPC::PRED_UN: O << "un"; return;
529 case PPC::PRED_NU: O << "nu"; return;
533 assert(!strcmp(Modifier, "reg") &&
534 "Need to specify 'cc' or 'reg' as predicate op modifier!");
535 // Don't print the register for 'always'.
536 if (Code == PPC::PRED_ALWAYS) return;
537 printOperand(MI, OpNo+1);
542 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
543 /// the current output stream.
545 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
548 processDebugLoc(MI->getDebugLoc());
550 // Check for slwi/srwi mnemonics.
551 if (MI->getOpcode() == PPC::RLWINM) {
552 bool FoundMnemonic = false;
553 unsigned char SH = MI->getOperand(2).getImm();
554 unsigned char MB = MI->getOperand(3).getImm();
555 unsigned char ME = MI->getOperand(4).getImm();
556 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
557 O << "\tslwi "; FoundMnemonic = true;
559 if (SH <= 31 && MB == (32-SH) && ME == 31) {
560 O << "\tsrwi "; FoundMnemonic = true;
567 O << ", " << (unsigned int)SH << '\n';
570 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
571 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
579 } else if (MI->getOpcode() == PPC::RLDICR) {
580 unsigned char SH = MI->getOperand(2).getImm();
581 unsigned char ME = MI->getOperand(3).getImm();
582 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
588 O << ", " << (unsigned int)SH << '\n';
593 printInstruction(MI);
595 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
600 /// runOnMachineFunction - This uses the printMachineInstruction()
601 /// method to print assembly for each instruction.
603 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
606 SetupMachineFunction(MF);
609 // Print out constants referenced by the function
610 EmitConstantPool(MF.getConstantPool());
612 // Print out labels for the function.
613 const Function *F = MF.getFunction();
614 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
616 switch (F->getLinkage()) {
617 default: llvm_unreachable("Unknown linkage type!");
618 case Function::PrivateLinkage:
619 case Function::InternalLinkage: // Symbols default to internal.
621 case Function::ExternalLinkage:
622 O << "\t.global\t" << CurrentFnName << '\n'
623 << "\t.type\t" << CurrentFnName << ", @function\n";
625 case Function::LinkerPrivateLinkage:
626 case Function::WeakAnyLinkage:
627 case Function::WeakODRLinkage:
628 case Function::LinkOnceAnyLinkage:
629 case Function::LinkOnceODRLinkage:
630 O << "\t.global\t" << CurrentFnName << '\n';
631 O << "\t.weak\t" << CurrentFnName << '\n';
635 printVisibility(CurrentFnName, F->getVisibility());
637 EmitAlignment(MF.getAlignment(), F);
639 if (Subtarget.isPPC64()) {
640 // Emit an official procedure descriptor.
641 // FIXME 64-bit SVR4: Use MCSection here?
642 O << "\t.section\t\".opd\",\"aw\"\n";
644 O << CurrentFnName << ":\n";
645 O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
646 O << "\t.previous\n";
647 O << ".L." << CurrentFnName << ":\n";
649 O << CurrentFnName << ":\n";
652 // Emit pre-function debug information.
653 DW->BeginFunction(&MF);
655 // Print out code for the function.
656 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
658 // Print a label for the basic block.
659 if (I != MF.begin()) {
660 EmitBasicBlockStart(I);
663 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
665 // Print the assembly for the instruction.
666 printMachineInstruction(II);
670 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
672 // Print out jump tables referenced by the function.
673 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
675 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
677 // Emit post-function debug information.
678 DW->EndFunction(&MF);
680 // We didn't modify anything.
684 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
685 const TargetData *TD = TM.getTargetData();
687 if (!GVar->hasInitializer())
688 return; // External global require no code
690 // Check to see if this is a special global used by LLVM, if so, emit it.
691 if (EmitSpecialLLVMGlobal(GVar))
694 std::string name = Mang->getMangledName(GVar);
696 printVisibility(name, GVar->getVisibility());
698 Constant *C = GVar->getInitializer();
699 const Type *Type = C->getType();
700 unsigned Size = TD->getTypeAllocSize(Type);
701 unsigned Align = TD->getPreferredAlignmentLog(GVar);
703 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
706 if (C->isNullValue() && /* FIXME: Verify correct */
707 !GVar->hasSection() &&
708 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
709 GVar->isWeakForLinker())) {
710 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
712 if (GVar->hasExternalLinkage()) {
713 O << "\t.global " << name << '\n';
714 O << "\t.type " << name << ", @object\n";
716 O << "\t.zero " << Size << '\n';
717 } else if (GVar->hasLocalLinkage()) {
718 O << MAI->getLCOMMDirective() << name << ',' << Size;
720 O << ".comm " << name << ',' << Size;
723 O << "\t\t" << MAI->getCommentString() << " '";
724 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
731 switch (GVar->getLinkage()) {
732 case GlobalValue::LinkOnceAnyLinkage:
733 case GlobalValue::LinkOnceODRLinkage:
734 case GlobalValue::WeakAnyLinkage:
735 case GlobalValue::WeakODRLinkage:
736 case GlobalValue::CommonLinkage:
737 case GlobalValue::LinkerPrivateLinkage:
738 O << "\t.global " << name << '\n'
739 << "\t.type " << name << ", @object\n"
740 << "\t.weak " << name << '\n';
742 case GlobalValue::AppendingLinkage:
743 // FIXME: appending linkage variables should go into a section of
744 // their name or something. For now, just emit them as external.
745 case GlobalValue::ExternalLinkage:
746 // If external or appending, declare as a global symbol
747 O << "\t.global " << name << '\n'
748 << "\t.type " << name << ", @object\n";
750 case GlobalValue::InternalLinkage:
751 case GlobalValue::PrivateLinkage:
754 llvm_unreachable("Unknown linkage type!");
757 EmitAlignment(Align, GVar);
760 O << "\t\t\t\t" << MAI->getCommentString() << " '";
761 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
766 EmitGlobalConstant(C);
770 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
771 const TargetData *TD = TM.getTargetData();
773 bool isPPC64 = TD->getPointerSizeInBits() == 64;
775 if (isPPC64 && !TOC.empty()) {
776 // FIXME 64-bit SVR4: Use MCSection here?
777 O << "\t.section\t\".toc\",\"aw\"\n";
779 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
781 O << I->second << ":\n";
782 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
786 return AsmPrinter::doFinalization(M);
789 /// runOnMachineFunction - This uses the printMachineInstruction()
790 /// method to print assembly for each instruction.
792 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
795 SetupMachineFunction(MF);
798 // Print out constants referenced by the function
799 EmitConstantPool(MF.getConstantPool());
801 // Print out labels for the function.
802 const Function *F = MF.getFunction();
803 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
805 switch (F->getLinkage()) {
806 default: llvm_unreachable("Unknown linkage type!");
807 case Function::PrivateLinkage:
808 case Function::InternalLinkage: // Symbols default to internal.
810 case Function::ExternalLinkage:
811 O << "\t.globl\t" << CurrentFnName << '\n';
813 case Function::WeakAnyLinkage:
814 case Function::WeakODRLinkage:
815 case Function::LinkOnceAnyLinkage:
816 case Function::LinkOnceODRLinkage:
817 case Function::LinkerPrivateLinkage:
818 O << "\t.globl\t" << CurrentFnName << '\n';
819 O << "\t.weak_definition\t" << CurrentFnName << '\n';
823 printVisibility(CurrentFnName, F->getVisibility());
825 EmitAlignment(MF.getAlignment(), F);
826 O << CurrentFnName << ":\n";
828 // Emit pre-function debug information.
829 DW->BeginFunction(&MF);
831 // If the function is empty, then we need to emit *something*. Otherwise, the
832 // function's label might be associated with something that it wasn't meant to
833 // be associated with. We emit a noop in this situation.
834 MachineFunction::iterator I = MF.begin();
836 if (++I == MF.end() && MF.front().empty())
839 // Print out code for the function.
840 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
842 // Print a label for the basic block.
843 if (I != MF.begin()) {
844 EmitBasicBlockStart(I);
847 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
849 // Print the assembly for the instruction.
850 printMachineInstruction(II);
854 // Print out jump tables referenced by the function.
855 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
857 // Emit post-function debug information.
858 DW->EndFunction(&MF);
860 // We didn't modify anything.
865 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
866 static const char *const CPUDirectives[] = {
878 unsigned Directive = Subtarget.getDarwinDirective();
879 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
880 Directive = PPC::DIR_970;
881 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
882 Directive = PPC::DIR_7400;
883 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
884 Directive = PPC::DIR_64;
885 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
886 O << "\t.machine " << CPUDirectives[Directive] << '\n';
888 // Prime text sections so they are adjacent. This reduces the likelihood a
889 // large data or debug section causes a branch to exceed 16M limit.
890 TargetLoweringObjectFileMachO &TLOFMacho =
891 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
892 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
893 if (TM.getRelocationModel() == Reloc::PIC_) {
894 OutStreamer.SwitchSection(
895 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
896 MCSectionMachO::S_SYMBOL_STUBS |
897 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
898 32, SectionKind::getText()));
899 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
900 OutStreamer.SwitchSection(
901 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
902 MCSectionMachO::S_SYMBOL_STUBS |
903 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
904 16, SectionKind::getText()));
906 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
909 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
910 const TargetData *TD = TM.getTargetData();
912 if (!GVar->hasInitializer())
913 return; // External global require no code
915 // Check to see if this is a special global used by LLVM, if so, emit it.
916 if (EmitSpecialLLVMGlobal(GVar)) {
917 if (TM.getRelocationModel() == Reloc::Static) {
918 if (GVar->getName() == "llvm.global_ctors")
919 O << ".reference .constructors_used\n";
920 else if (GVar->getName() == "llvm.global_dtors")
921 O << ".reference .destructors_used\n";
926 std::string name = Mang->getMangledName(GVar);
927 printVisibility(name, GVar->getVisibility());
929 Constant *C = GVar->getInitializer();
930 const Type *Type = C->getType();
931 unsigned Size = TD->getTypeAllocSize(Type);
932 unsigned Align = TD->getPreferredAlignmentLog(GVar);
934 const MCSection *TheSection =
935 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
936 OutStreamer.SwitchSection(TheSection);
938 /// FIXME: Drive this off the section!
939 if (C->isNullValue() && /* FIXME: Verify correct */
940 !GVar->hasSection() &&
941 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
942 GVar->isWeakForLinker()) &&
943 // Don't put things that should go in the cstring section into "comm".
944 !TheSection->getKind().isMergeableCString()) {
945 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
947 if (GVar->hasExternalLinkage()) {
948 O << "\t.globl " << name << '\n';
949 O << "\t.zerofill __DATA, __common, " << name << ", "
950 << Size << ", " << Align;
951 } else if (GVar->hasLocalLinkage()) {
952 O << MAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
953 } else if (!GVar->hasCommonLinkage()) {
954 O << "\t.globl " << name << '\n'
955 << MAI->getWeakDefDirective() << name << '\n';
956 EmitAlignment(Align, GVar);
959 O << "\t\t\t\t" << MAI->getCommentString() << " ";
960 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
963 EmitGlobalConstant(C);
966 O << ".comm " << name << ',' << Size;
967 // Darwin 9 and above support aligned common data.
968 if (Subtarget.isDarwin9())
972 O << "\t\t" << MAI->getCommentString() << " '";
973 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
980 switch (GVar->getLinkage()) {
981 case GlobalValue::LinkOnceAnyLinkage:
982 case GlobalValue::LinkOnceODRLinkage:
983 case GlobalValue::WeakAnyLinkage:
984 case GlobalValue::WeakODRLinkage:
985 case GlobalValue::CommonLinkage:
986 case GlobalValue::LinkerPrivateLinkage:
987 O << "\t.globl " << name << '\n'
988 << "\t.weak_definition " << name << '\n';
990 case GlobalValue::AppendingLinkage:
991 // FIXME: appending linkage variables should go into a section of
992 // their name or something. For now, just emit them as external.
993 case GlobalValue::ExternalLinkage:
994 // If external or appending, declare as a global symbol
995 O << "\t.globl " << name << '\n';
997 case GlobalValue::InternalLinkage:
998 case GlobalValue::PrivateLinkage:
1001 llvm_unreachable("Unknown linkage type!");
1004 EmitAlignment(Align, GVar);
1007 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1008 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1013 EmitGlobalConstant(C);
1017 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1018 const TargetData *TD = TM.getTargetData();
1020 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1022 // Darwin/PPC always uses mach-o.
1023 TargetLoweringObjectFileMachO &TLOFMacho =
1024 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1027 const MCSection *LSPSection = 0;
1028 if (!FnStubs.empty()) // .lazy_symbol_pointer
1029 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1032 // Output stubs for dynamically-linked functions
1033 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1034 const MCSection *StubSection =
1035 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1036 MCSectionMachO::S_SYMBOL_STUBS |
1037 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1038 32, SectionKind::getText());
1039 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1041 OutStreamer.SwitchSection(StubSection);
1043 const FnStubInfo &Info = I->second;
1044 O << Info.Stub << ":\n";
1045 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1047 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1048 O << Info.AnonSymbol << ":\n";
1049 O << "\tmflr r11\n";
1050 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1053 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1054 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1055 O << "\tmtctr r12\n";
1058 OutStreamer.SwitchSection(LSPSection);
1059 O << Info.LazyPtr << ":\n";
1060 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1061 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1063 } else if (!FnStubs.empty()) {
1064 const MCSection *StubSection =
1065 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1066 MCSectionMachO::S_SYMBOL_STUBS |
1067 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1068 16, SectionKind::getText());
1070 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1072 OutStreamer.SwitchSection(StubSection);
1074 const FnStubInfo &Info = I->second;
1075 O << Info.Stub << ":\n";
1076 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1077 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1078 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1079 O << Info.LazyPtr << ")(r11)\n";
1080 O << "\tmtctr r12\n";
1082 OutStreamer.SwitchSection(LSPSection);
1083 O << Info.LazyPtr << ":\n";
1084 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1085 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1091 if (MAI->doesSupportExceptionHandling() && MMI) {
1092 // Add the (possibly multiple) personalities to the set of global values.
1093 // Only referenced functions get into the Personalities list.
1094 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1095 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1096 E = Personalities.end(); I != E; ++I) {
1098 GVStubs[Mang->getMangledName(*I)] =
1099 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1103 // Output macho stubs for external and common global variables.
1104 if (!GVStubs.empty()) {
1105 // Switch with ".non_lazy_symbol_pointer" directive.
1106 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1107 EmitAlignment(isPPC64 ? 3 : 2);
1109 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1110 E = GVStubs.end(); I != E; ++I) {
1111 O << I->second << ":\n";
1112 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1113 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1117 if (!HiddenGVStubs.empty()) {
1118 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1119 EmitAlignment(isPPC64 ? 3 : 2);
1120 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1121 E = HiddenGVStubs.end(); I != E; ++I) {
1122 O << I->second << ":\n";
1123 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1127 // Funny Darwin hack: This flag tells the linker that no global symbols
1128 // contain code that falls through to other global symbols (e.g. the obvious
1129 // implementation of multiple entry points). If this doesn't occur, the
1130 // linker can safely perform dead code stripping. Since LLVM never generates
1131 // code that does this, it is always safe to set.
1132 O << "\t.subsections_via_symbols\n";
1134 return AsmPrinter::doFinalization(M);
1139 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1140 /// for a MachineFunction to the given output stream, in a format that the
1141 /// Darwin assembler can deal with.
1143 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1145 const MCAsmInfo *tai,
1147 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1149 if (Subtarget->isDarwin())
1150 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1151 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1154 // Force static initialization.
1155 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1156 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1157 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);