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/MCSectionMachO.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegistry.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/FormattedStream.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSet.h"
53 STATISTIC(EmittedInsts, "Number of machine instrs printed");
56 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
59 std::string Stub, LazyPtr, AnonSymbol;
63 void Init(const GlobalValue *GV, Mangler *Mang) {
64 // Already initialized.
65 if (!Stub.empty()) return;
66 Stub = Mang->getMangledName(GV, "$stub", true);
67 LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
68 AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
71 void Init(const std::string &GV, Mangler *Mang) {
72 // Already initialized.
73 if (!Stub.empty()) return;
74 Stub = Mang->makeNameProper(GV + "$stub",
76 LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
78 AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
83 StringMap<FnStubInfo> FnStubs;
84 StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
85 const PPCSubtarget &Subtarget;
88 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
89 const TargetAsmInfo *T, bool V)
90 : AsmPrinter(O, TM, T, V),
91 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
93 virtual const char *getPassName() const {
94 return "PowerPC Assembly Printer";
97 PPCTargetMachine &getTM() {
98 return static_cast<PPCTargetMachine&>(TM);
101 unsigned enumRegToMachineReg(unsigned enumReg) {
103 default: llvm_unreachable("Unhandled register!");
104 case PPC::CR0: return 0;
105 case PPC::CR1: return 1;
106 case PPC::CR2: return 2;
107 case PPC::CR3: return 3;
108 case PPC::CR4: return 4;
109 case PPC::CR5: return 5;
110 case PPC::CR6: return 6;
111 case PPC::CR7: return 7;
116 /// printInstruction - This method is automatically generated by tablegen
117 /// from the instruction set description. This method returns true if the
118 /// machine instruction was sufficiently described to print it, otherwise it
120 void printInstruction(const MachineInstr *MI);
122 void printMachineInstruction(const MachineInstr *MI);
123 void printOp(const MachineOperand &MO);
125 /// stripRegisterPrefix - This method strips the character prefix from a
126 /// register name so that only the number is left. Used by for linux asm.
127 const char *stripRegisterPrefix(const char *RegName) {
128 switch (RegName[0]) {
131 case 'v': return RegName + 1;
132 case 'c': if (RegName[1] == 'r') return RegName + 2;
138 /// printRegister - Print register according to target requirements.
140 void printRegister(const MachineOperand &MO, bool R0AsZero) {
141 unsigned RegNo = MO.getReg();
142 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
144 // If we should use 0 for R0.
145 if (R0AsZero && RegNo == PPC::R0) {
150 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
151 // Linux assembler (Others?) does not take register mnemonics.
152 // FIXME - What about special registers used in mfspr/mtspr?
153 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
157 void printOperand(const MachineInstr *MI, unsigned OpNo) {
158 const MachineOperand &MO = MI->getOperand(OpNo);
160 printRegister(MO, false);
161 } else if (MO.isImm()) {
168 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
169 unsigned AsmVariant, const char *ExtraCode);
170 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
171 unsigned AsmVariant, const char *ExtraCode);
174 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
175 char value = MI->getOperand(OpNo).getImm();
176 value = (value << (32-5)) >> (32-5);
179 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
180 unsigned char value = MI->getOperand(OpNo).getImm();
181 assert(value <= 31 && "Invalid u5imm argument!");
182 O << (unsigned int)value;
184 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
185 unsigned char value = MI->getOperand(OpNo).getImm();
186 assert(value <= 63 && "Invalid u6imm argument!");
187 O << (unsigned int)value;
189 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
190 O << (short)MI->getOperand(OpNo).getImm();
192 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
193 O << (unsigned short)MI->getOperand(OpNo).getImm();
195 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
196 if (MI->getOperand(OpNo).isImm()) {
197 O << (short)(MI->getOperand(OpNo).getImm()*4);
200 printOp(MI->getOperand(OpNo));
201 if (TM.getRelocationModel() == Reloc::PIC_)
202 O << "-\"L" << getFunctionNumber() << "$pb\")";
207 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
208 // Branches can take an immediate operand. This is used by the branch
209 // selection pass to print $+8, an eight byte displacement from the PC.
210 if (MI->getOperand(OpNo).isImm()) {
211 O << "$+" << MI->getOperand(OpNo).getImm()*4;
213 printOp(MI->getOperand(OpNo));
216 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
217 const MachineOperand &MO = MI->getOperand(OpNo);
218 if (TM.getRelocationModel() != Reloc::Static) {
219 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
220 GlobalValue *GV = MO.getGlobal();
221 if (GV->isDeclaration() || GV->isWeakForLinker()) {
222 // Dynamically-resolved functions need a stub for the function.
223 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
224 FnInfo.Init(GV, Mang);
229 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
230 FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
231 FnInfo.Init(MO.getSymbolName(), Mang);
237 printOp(MI->getOperand(OpNo));
239 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
240 O << (int)MI->getOperand(OpNo).getImm()*4;
242 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
243 O << "\"L" << getFunctionNumber() << "$pb\"\n";
244 O << "\"L" << getFunctionNumber() << "$pb\":";
246 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
247 if (MI->getOperand(OpNo).isImm()) {
248 printS16ImmOperand(MI, OpNo);
250 if (Subtarget.isDarwin()) O << "ha16(";
251 printOp(MI->getOperand(OpNo));
252 if (TM.getRelocationModel() == Reloc::PIC_)
253 O << "-\"L" << getFunctionNumber() << "$pb\"";
254 if (Subtarget.isDarwin())
260 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
261 if (MI->getOperand(OpNo).isImm()) {
262 printS16ImmOperand(MI, OpNo);
264 if (Subtarget.isDarwin()) O << "lo16(";
265 printOp(MI->getOperand(OpNo));
266 if (TM.getRelocationModel() == Reloc::PIC_)
267 O << "-\"L" << getFunctionNumber() << "$pb\"";
268 if (Subtarget.isDarwin())
274 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
275 unsigned CCReg = MI->getOperand(OpNo).getReg();
276 unsigned RegNo = enumRegToMachineReg(CCReg);
277 O << (0x80 >> RegNo);
279 // The new addressing mode printers.
280 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
281 printSymbolLo(MI, OpNo);
283 if (MI->getOperand(OpNo+1).isReg() &&
284 MI->getOperand(OpNo+1).getReg() == PPC::R0)
287 printOperand(MI, OpNo+1);
290 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
291 if (MI->getOperand(OpNo).isImm())
292 printS16X4ImmOperand(MI, OpNo);
294 printSymbolLo(MI, OpNo);
296 if (MI->getOperand(OpNo+1).isReg() &&
297 MI->getOperand(OpNo+1).getReg() == PPC::R0)
300 printOperand(MI, OpNo+1);
304 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
305 // When used as the base register, r0 reads constant zero rather than
306 // the value contained in the register. For this reason, the darwin
307 // assembler requires that we print r0 as 0 (no r) when used as the base.
308 const MachineOperand &MO = MI->getOperand(OpNo);
309 printRegister(MO, true);
311 printOperand(MI, OpNo+1);
314 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
315 const MachineOperand &MO = MI->getOperand(OpNo);
317 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
319 GlobalValue *GV = MO.getGlobal();
321 std::string Name = Mang->getMangledName(GV);
323 // Map symbol -> label of TOC entry.
324 if (TOC.count(Name) == 0) {
326 Label += TAI->getPrivateGlobalPrefix();
328 Label += utostr(LabelID++);
333 O << TOC[Name] << "@toc";
336 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
337 const char *Modifier);
339 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
341 virtual void EmitExternalGlobal(const GlobalVariable *GV);
344 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
345 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
347 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
348 const TargetAsmInfo *T, bool V)
349 : PPCAsmPrinter(O, TM, T, V){}
351 virtual const char *getPassName() const {
352 return "Linux PPC Assembly Printer";
355 bool runOnMachineFunction(MachineFunction &F);
356 bool doFinalization(Module &M);
358 void getAnalysisUsage(AnalysisUsage &AU) const {
359 AU.setPreservesAll();
360 AU.addRequired<MachineModuleInfo>();
361 AU.addRequired<DwarfWriter>();
362 PPCAsmPrinter::getAnalysisUsage(AU);
365 void PrintGlobalVariable(const GlobalVariable *GVar);
368 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
370 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
371 formatted_raw_ostream &OS;
373 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
374 const TargetAsmInfo *T, bool V)
375 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
377 virtual const char *getPassName() const {
378 return "Darwin PPC Assembly Printer";
381 bool runOnMachineFunction(MachineFunction &F);
382 bool doInitialization(Module &M);
383 bool doFinalization(Module &M);
385 void getAnalysisUsage(AnalysisUsage &AU) const {
386 AU.setPreservesAll();
387 AU.addRequired<MachineModuleInfo>();
388 AU.addRequired<DwarfWriter>();
389 PPCAsmPrinter::getAnalysisUsage(AU);
392 void PrintGlobalVariable(const GlobalVariable *GVar);
394 } // end of anonymous namespace
396 // Include the auto-generated portion of the assembly writer
397 #include "PPCGenAsmWriter.inc"
399 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
400 switch (MO.getType()) {
401 case MachineOperand::MO_Immediate:
402 llvm_unreachable("printOp() does not handle immediate values");
404 case MachineOperand::MO_MachineBasicBlock:
405 printBasicBlockLabel(MO.getMBB());
407 case MachineOperand::MO_JumpTableIndex:
408 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
409 << '_' << MO.getIndex();
410 // FIXME: PIC relocation model
412 case MachineOperand::MO_ConstantPoolIndex:
413 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
414 << '_' << MO.getIndex();
416 case MachineOperand::MO_ExternalSymbol: {
417 // Computing the address of an external symbol, not calling it.
418 std::string Name(TAI->getGlobalPrefix());
419 Name += MO.getSymbolName();
421 if (TM.getRelocationModel() != Reloc::Static) {
422 GVStubs[Name] = Name+"$non_lazy_ptr";
423 Name += "$non_lazy_ptr";
428 case MachineOperand::MO_GlobalAddress: {
429 // Computing the address of a global symbol, not calling it.
430 GlobalValue *GV = MO.getGlobal();
433 // External or weakly linked global variables need non-lazily-resolved stubs
434 if (TM.getRelocationModel() != Reloc::Static &&
435 (GV->isDeclaration() || GV->isWeakForLinker())) {
436 if (!GV->hasHiddenVisibility()) {
437 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
438 GVStubs[Mang->getMangledName(GV)] = Name;
439 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
440 GV->hasAvailableExternallyLinkage()) {
441 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
442 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
444 Name = Mang->getMangledName(GV);
447 Name = Mang->getMangledName(GV);
451 printOffset(MO.getOffset());
456 O << "<unknown operand type: " << MO.getType() << ">";
461 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
463 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
466 if (TM.getRelocationModel() != Reloc::Static) {
467 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
469 Name = Mang->getMangledName(GV);
474 /// PrintAsmOperand - Print out an operand for an inline asm expression.
476 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
478 const char *ExtraCode) {
479 // Does this asm operand have a single letter operand modifier?
480 if (ExtraCode && ExtraCode[0]) {
481 if (ExtraCode[1] != 0) return true; // Unknown modifier.
483 switch (ExtraCode[0]) {
484 default: return true; // Unknown modifier.
485 case 'c': // Don't print "$" before a global var name or constant.
486 // PPC never has a prefix.
487 printOperand(MI, OpNo);
489 case 'L': // Write second word of DImode reference.
490 // Verify that this operand has two consecutive registers.
491 if (!MI->getOperand(OpNo).isReg() ||
492 OpNo+1 == MI->getNumOperands() ||
493 !MI->getOperand(OpNo+1).isReg())
495 ++OpNo; // Return the high-part.
498 // Write 'i' if an integer constant, otherwise nothing. Used to print
500 if (MI->getOperand(OpNo).isImm())
506 printOperand(MI, OpNo);
510 // At the moment, all inline asm memory operands are a single register.
511 // In any case, the output of this routine should always be just one
512 // assembler operand.
514 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
516 const char *ExtraCode) {
517 if (ExtraCode && ExtraCode[0])
518 return true; // Unknown modifier.
519 assert (MI->getOperand(OpNo).isReg());
520 printOperand(MI, OpNo);
524 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
525 const char *Modifier) {
526 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
527 unsigned Code = MI->getOperand(OpNo).getImm();
528 if (!strcmp(Modifier, "cc")) {
529 switch ((PPC::Predicate)Code) {
530 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
531 case PPC::PRED_LT: O << "lt"; return;
532 case PPC::PRED_LE: O << "le"; return;
533 case PPC::PRED_EQ: O << "eq"; return;
534 case PPC::PRED_GE: O << "ge"; return;
535 case PPC::PRED_GT: O << "gt"; return;
536 case PPC::PRED_NE: O << "ne"; return;
537 case PPC::PRED_UN: O << "un"; return;
538 case PPC::PRED_NU: O << "nu"; return;
542 assert(!strcmp(Modifier, "reg") &&
543 "Need to specify 'cc' or 'reg' as predicate op modifier!");
544 // Don't print the register for 'always'.
545 if (Code == PPC::PRED_ALWAYS) return;
546 printOperand(MI, OpNo+1);
551 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
552 /// the current output stream.
554 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
557 // Check for slwi/srwi mnemonics.
558 if (MI->getOpcode() == PPC::RLWINM) {
559 bool FoundMnemonic = false;
560 unsigned char SH = MI->getOperand(2).getImm();
561 unsigned char MB = MI->getOperand(3).getImm();
562 unsigned char ME = MI->getOperand(4).getImm();
563 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
564 O << "\tslwi "; FoundMnemonic = true;
566 if (SH <= 31 && MB == (32-SH) && ME == 31) {
567 O << "\tsrwi "; FoundMnemonic = true;
574 O << ", " << (unsigned int)SH << '\n';
577 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
578 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
586 } else if (MI->getOpcode() == PPC::RLDICR) {
587 unsigned char SH = MI->getOperand(2).getImm();
588 unsigned char ME = MI->getOperand(3).getImm();
589 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
595 O << ", " << (unsigned int)SH << '\n';
600 printInstruction(MI);
603 /// runOnMachineFunction - This uses the printMachineInstruction()
604 /// method to print assembly for each instruction.
606 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
609 SetupMachineFunction(MF);
612 // Print out constants referenced by the function
613 EmitConstantPool(MF.getConstantPool());
615 // Print out labels for the function.
616 const Function *F = MF.getFunction();
617 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
619 switch (F->getLinkage()) {
620 default: llvm_unreachable("Unknown linkage type!");
621 case Function::PrivateLinkage:
622 case Function::LinkerPrivateLinkage:
623 case Function::InternalLinkage: // Symbols default to internal.
625 case Function::ExternalLinkage:
626 O << "\t.global\t" << CurrentFnName << '\n'
627 << "\t.type\t" << CurrentFnName << ", @function\n";
629 case Function::WeakAnyLinkage:
630 case Function::WeakODRLinkage:
631 case Function::LinkOnceAnyLinkage:
632 case Function::LinkOnceODRLinkage:
633 O << "\t.global\t" << CurrentFnName << '\n';
634 O << "\t.weak\t" << CurrentFnName << '\n';
638 printVisibility(CurrentFnName, F->getVisibility());
640 EmitAlignment(MF.getAlignment(), F);
642 if (Subtarget.isPPC64()) {
643 // Emit an official procedure descriptor.
644 // FIXME 64-bit SVR4: Use MCSection here?
645 O << "\t.section\t\".opd\",\"aw\"\n";
647 O << CurrentFnName << ":\n";
648 O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
649 O << "\t.previous\n";
650 O << ".L." << CurrentFnName << ":\n";
652 O << CurrentFnName << ":\n";
655 // Emit pre-function debug information.
656 DW->BeginFunction(&MF);
658 // Print out code for the function.
659 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
661 // Print a label for the basic block.
662 if (I != MF.begin()) {
663 printBasicBlockLabel(I, true, true);
666 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
668 // Print the assembly for the instruction.
669 printMachineInstruction(II);
673 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
675 // Print out jump tables referenced by the function.
676 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
678 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
680 // Emit post-function debug information.
681 DW->EndFunction(&MF);
683 // We didn't modify anything.
687 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
688 const TargetData *TD = TM.getTargetData();
690 if (!GVar->hasInitializer())
691 return; // External global require no code
693 // Check to see if this is a special global used by LLVM, if so, emit it.
694 if (EmitSpecialLLVMGlobal(GVar))
697 std::string name = Mang->getMangledName(GVar);
699 printVisibility(name, GVar->getVisibility());
701 Constant *C = GVar->getInitializer();
702 const Type *Type = C->getType();
703 unsigned Size = TD->getTypeAllocSize(Type);
704 unsigned Align = TD->getPreferredAlignmentLog(GVar);
706 SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang, TM));
708 if (C->isNullValue() && /* FIXME: Verify correct */
709 !GVar->hasSection() &&
710 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
711 GVar->isWeakForLinker())) {
712 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
714 if (GVar->hasExternalLinkage()) {
715 O << "\t.global " << name << '\n';
716 O << "\t.type " << name << ", @object\n";
718 O << "\t.zero " << Size << '\n';
719 } else if (GVar->hasLocalLinkage()) {
720 O << TAI->getLCOMMDirective() << name << ',' << Size;
722 O << ".comm " << name << ',' << Size;
725 O << "\t\t" << TAI->getCommentString() << " '";
726 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
733 switch (GVar->getLinkage()) {
734 case GlobalValue::LinkOnceAnyLinkage:
735 case GlobalValue::LinkOnceODRLinkage:
736 case GlobalValue::WeakAnyLinkage:
737 case GlobalValue::WeakODRLinkage:
738 case GlobalValue::CommonLinkage:
739 O << "\t.global " << name << '\n'
740 << "\t.type " << name << ", @object\n"
741 << "\t.weak " << name << '\n';
743 case GlobalValue::AppendingLinkage:
744 // FIXME: appending linkage variables should go into a section of
745 // their name or something. For now, just emit them as external.
746 case GlobalValue::ExternalLinkage:
747 // If external or appending, declare as a global symbol
748 O << "\t.global " << name << '\n'
749 << "\t.type " << name << ", @object\n";
751 case GlobalValue::InternalLinkage:
752 case GlobalValue::PrivateLinkage:
753 case GlobalValue::LinkerPrivateLinkage:
756 llvm_unreachable("Unknown linkage type!");
759 EmitAlignment(Align, GVar);
762 O << "\t\t\t\t" << TAI->getCommentString() << " '";
763 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
768 EmitGlobalConstant(C);
772 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
773 const TargetData *TD = TM.getTargetData();
775 bool isPPC64 = TD->getPointerSizeInBits() == 64;
777 if (isPPC64 && !TOC.empty()) {
778 // FIXME 64-bit SVR4: Use MCSection here?
779 O << "\t.section\t\".toc\",\"aw\"\n";
781 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
783 O << I->second << ":\n";
784 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
788 return AsmPrinter::doFinalization(M);
791 /// runOnMachineFunction - This uses the printMachineInstruction()
792 /// method to print assembly for each instruction.
794 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
797 SetupMachineFunction(MF);
800 // Print out constants referenced by the function
801 EmitConstantPool(MF.getConstantPool());
803 // Print out labels for the function.
804 const Function *F = MF.getFunction();
805 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
807 switch (F->getLinkage()) {
808 default: llvm_unreachable("Unknown linkage type!");
809 case Function::PrivateLinkage:
810 case Function::LinkerPrivateLinkage:
811 case Function::InternalLinkage: // Symbols default to internal.
813 case Function::ExternalLinkage:
814 O << "\t.globl\t" << CurrentFnName << '\n';
816 case Function::WeakAnyLinkage:
817 case Function::WeakODRLinkage:
818 case Function::LinkOnceAnyLinkage:
819 case Function::LinkOnceODRLinkage:
820 O << "\t.globl\t" << CurrentFnName << '\n';
821 O << "\t.weak_definition\t" << CurrentFnName << '\n';
825 printVisibility(CurrentFnName, F->getVisibility());
827 EmitAlignment(MF.getAlignment(), F);
828 O << CurrentFnName << ":\n";
830 // Emit pre-function debug information.
831 DW->BeginFunction(&MF);
833 // If the function is empty, then we need to emit *something*. Otherwise, the
834 // function's label might be associated with something that it wasn't meant to
835 // be associated with. We emit a noop in this situation.
836 MachineFunction::iterator I = MF.begin();
838 if (++I == MF.end() && MF.front().empty())
841 // Print out code for the function.
842 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
844 // Print a label for the basic block.
845 if (I != MF.begin()) {
846 printBasicBlockLabel(I, true, true, VerboseAsm);
849 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
851 // Print the assembly for the instruction.
852 printMachineInstruction(II);
856 // Print out jump tables referenced by the function.
857 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
859 // Emit post-function debug information.
860 DW->EndFunction(&MF);
862 // We didn't modify anything.
867 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
868 static const char *const CPUDirectives[] = {
880 unsigned Directive = Subtarget.getDarwinDirective();
881 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
882 Directive = PPC::DIR_970;
883 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
884 Directive = PPC::DIR_7400;
885 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
886 Directive = PPC::DIR_64;
887 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
888 O << "\t.machine " << CPUDirectives[Directive] << '\n';
890 bool Result = AsmPrinter::doInitialization(M);
893 // Prime text sections so they are adjacent. This reduces the likelihood a
894 // large data or debug section causes a branch to exceed 16M limit.
895 TargetLoweringObjectFileMachO &TLOFMacho =
896 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
897 SwitchToSection(TLOFMacho.getTextCoalSection());
898 if (TM.getRelocationModel() == Reloc::PIC_) {
899 SwitchToSection(TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
900 MCSectionMachO::S_SYMBOL_STUBS |
901 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
902 32, SectionKind::getText()));
903 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
904 SwitchToSection(TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
905 MCSectionMachO::S_SYMBOL_STUBS |
906 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
907 16, SectionKind::getText()));
909 SwitchToSection(getObjFileLowering().getTextSection());
914 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
915 const TargetData *TD = TM.getTargetData();
917 if (!GVar->hasInitializer())
918 return; // External global require no code
920 // Check to see if this is a special global used by LLVM, if so, emit it.
921 if (EmitSpecialLLVMGlobal(GVar)) {
922 if (TM.getRelocationModel() == Reloc::Static) {
923 if (GVar->getName() == "llvm.global_ctors")
924 O << ".reference .constructors_used\n";
925 else if (GVar->getName() == "llvm.global_dtors")
926 O << ".reference .destructors_used\n";
931 std::string name = Mang->getMangledName(GVar);
932 printVisibility(name, GVar->getVisibility());
934 Constant *C = GVar->getInitializer();
935 const Type *Type = C->getType();
936 unsigned Size = TD->getTypeAllocSize(Type);
937 unsigned Align = TD->getPreferredAlignmentLog(GVar);
939 const MCSection *TheSection =
940 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
941 SwitchToSection(TheSection);
943 /// FIXME: Drive this off the section!
944 if (C->isNullValue() && /* FIXME: Verify correct */
945 !GVar->hasSection() &&
946 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
947 GVar->isWeakForLinker()) &&
948 // Don't put things that should go in the cstring section into "comm".
949 !TheSection->getKind().isMergeableCString()) {
950 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
952 if (GVar->hasExternalLinkage()) {
953 O << "\t.globl " << name << '\n';
954 O << "\t.zerofill __DATA, __common, " << name << ", "
955 << Size << ", " << Align;
956 } else if (GVar->hasLocalLinkage()) {
957 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
958 } else if (!GVar->hasCommonLinkage()) {
959 O << "\t.globl " << name << '\n'
960 << TAI->getWeakDefDirective() << name << '\n';
961 EmitAlignment(Align, GVar);
964 O << "\t\t\t\t" << TAI->getCommentString() << " ";
965 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
968 EmitGlobalConstant(C);
971 O << ".comm " << name << ',' << Size;
972 // Darwin 9 and above support aligned common data.
973 if (Subtarget.isDarwin9())
977 O << "\t\t" << TAI->getCommentString() << " '";
978 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
985 switch (GVar->getLinkage()) {
986 case GlobalValue::LinkOnceAnyLinkage:
987 case GlobalValue::LinkOnceODRLinkage:
988 case GlobalValue::WeakAnyLinkage:
989 case GlobalValue::WeakODRLinkage:
990 case GlobalValue::CommonLinkage:
991 O << "\t.globl " << name << '\n'
992 << "\t.weak_definition " << name << '\n';
994 case GlobalValue::AppendingLinkage:
995 // FIXME: appending linkage variables should go into a section of
996 // their name or something. For now, just emit them as external.
997 case GlobalValue::ExternalLinkage:
998 // If external or appending, declare as a global symbol
999 O << "\t.globl " << name << '\n';
1001 case GlobalValue::InternalLinkage:
1002 case GlobalValue::PrivateLinkage:
1003 case GlobalValue::LinkerPrivateLinkage:
1006 llvm_unreachable("Unknown linkage type!");
1009 EmitAlignment(Align, GVar);
1012 O << "\t\t\t\t" << TAI->getCommentString() << " '";
1013 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1018 EmitGlobalConstant(C);
1022 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1023 const TargetData *TD = TM.getTargetData();
1025 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1027 // Darwin/PPC always uses mach-o.
1028 TargetLoweringObjectFileMachO &TLOFMacho =
1029 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1032 const MCSection *LSPSection = 0;
1033 if (!FnStubs.empty()) // .lazy_symbol_pointer
1034 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1037 // Output stubs for dynamically-linked functions
1038 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1039 const MCSection *StubSection =
1040 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1041 MCSectionMachO::S_SYMBOL_STUBS |
1042 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1043 32, SectionKind::getText());
1044 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1046 SwitchToSection(StubSection);
1048 const FnStubInfo &Info = I->second;
1049 O << Info.Stub << ":\n";
1050 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1052 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1053 O << Info.AnonSymbol << ":\n";
1054 O << "\tmflr r11\n";
1055 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1058 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1059 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1060 O << "\tmtctr r12\n";
1063 SwitchToSection(LSPSection);
1064 O << Info.LazyPtr << ":\n";
1065 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1066 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1068 } else if (!FnStubs.empty()) {
1069 const MCSection *StubSection =
1070 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1071 MCSectionMachO::S_SYMBOL_STUBS |
1072 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1073 16, SectionKind::getText());
1075 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1077 SwitchToSection(StubSection);
1079 const FnStubInfo &Info = I->second;
1080 O << Info.Stub << ":\n";
1081 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1082 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1083 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1084 O << Info.LazyPtr << ")(r11)\n";
1085 O << "\tmtctr r12\n";
1087 SwitchToSection(LSPSection);
1088 O << Info.LazyPtr << ":\n";
1089 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1090 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1096 if (TAI->doesSupportExceptionHandling() && MMI) {
1097 // Add the (possibly multiple) personalities to the set of global values.
1098 // Only referenced functions get into the Personalities list.
1099 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1100 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1101 E = Personalities.end(); I != E; ++I) {
1103 GVStubs[Mang->getMangledName(*I)] =
1104 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1108 // Output macho stubs for external and common global variables.
1109 if (!GVStubs.empty()) {
1110 // Switch with ".non_lazy_symbol_pointer" directive.
1111 SwitchToSection(TLOFMacho.getNonLazySymbolPointerSection());
1112 EmitAlignment(isPPC64 ? 3 : 2);
1114 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1115 E = GVStubs.end(); I != E; ++I) {
1116 O << I->second << ":\n";
1117 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1118 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1122 if (!HiddenGVStubs.empty()) {
1123 SwitchToSection(getObjFileLowering().getDataSection());
1124 EmitAlignment(isPPC64 ? 3 : 2);
1125 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1126 E = HiddenGVStubs.end(); I != E; ++I) {
1127 O << I->second << ":\n";
1128 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1132 // Funny Darwin hack: This flag tells the linker that no global symbols
1133 // contain code that falls through to other global symbols (e.g. the obvious
1134 // implementation of multiple entry points). If this doesn't occur, the
1135 // linker can safely perform dead code stripping. Since LLVM never generates
1136 // code that does this, it is always safe to set.
1137 O << "\t.subsections_via_symbols\n";
1139 return AsmPrinter::doFinalization(M);
1144 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1145 /// for a MachineFunction to the given output stream, in a format that the
1146 /// Darwin assembler can deal with.
1148 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1150 const TargetAsmInfo *tai,
1152 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1154 if (Subtarget->isDarwin())
1155 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1156 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1159 // Force static initialization.
1160 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1161 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1162 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);