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/FormattedStream.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSet.h"
52 #include "llvm/ADT/SmallString.h"
55 STATISTIC(EmittedInsts, "Number of machine instrs printed");
58 class 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(StringRef GVName, Mangler *Mang) {
74 assert(!GVName.empty());
75 if (!Stub.empty()) return; // Already initialized.
76 // Get the names for the external symbol name.
77 SmallString<128> TmpStr;
78 Mang->getNameWithPrefix(TmpStr, GVName + "$stub", Mangler::Private);
82 Mang->getNameWithPrefix(TmpStr, GVName + "$lazy_ptr", Mangler::Private);
83 LazyPtr = TmpStr.str();
86 Mang->getNameWithPrefix(TmpStr, GVName + "$stub$tmp", Mangler::Private);
87 AnonSymbol = TmpStr.str();
91 StringMap<FnStubInfo> FnStubs;
92 StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
93 const PPCSubtarget &Subtarget;
96 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
97 const MCAsmInfo *T, bool V)
98 : AsmPrinter(O, TM, T, V),
99 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
101 virtual const char *getPassName() const {
102 return "PowerPC Assembly Printer";
105 PPCTargetMachine &getTM() {
106 return static_cast<PPCTargetMachine&>(TM);
109 unsigned enumRegToMachineReg(unsigned enumReg) {
111 default: llvm_unreachable("Unhandled register!");
112 case PPC::CR0: return 0;
113 case PPC::CR1: return 1;
114 case PPC::CR2: return 2;
115 case PPC::CR3: return 3;
116 case PPC::CR4: return 4;
117 case PPC::CR5: return 5;
118 case PPC::CR6: return 6;
119 case PPC::CR7: return 7;
124 /// printInstruction - This method is automatically generated by tablegen
125 /// from the instruction set description. This method returns true if the
126 /// machine instruction was sufficiently described to print it, otherwise it
128 void printInstruction(const MachineInstr *MI);
129 static const char *getRegisterName(unsigned RegNo);
132 void printMachineInstruction(const MachineInstr *MI);
133 void printOp(const MachineOperand &MO);
135 /// stripRegisterPrefix - This method strips the character prefix from a
136 /// register name so that only the number is left. Used by for linux asm.
137 const char *stripRegisterPrefix(const char *RegName) {
138 switch (RegName[0]) {
141 case 'v': return RegName + 1;
142 case 'c': if (RegName[1] == 'r') return RegName + 2;
148 /// printRegister - Print register according to target requirements.
150 void printRegister(const MachineOperand &MO, bool R0AsZero) {
151 unsigned RegNo = MO.getReg();
152 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
154 // If we should use 0 for R0.
155 if (R0AsZero && RegNo == PPC::R0) {
160 const char *RegName = getRegisterName(RegNo);
161 // Linux assembler (Others?) does not take register mnemonics.
162 // FIXME - What about special registers used in mfspr/mtspr?
163 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
167 void printOperand(const MachineInstr *MI, unsigned OpNo) {
168 const MachineOperand &MO = MI->getOperand(OpNo);
170 printRegister(MO, false);
171 } else if (MO.isImm()) {
178 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
179 unsigned AsmVariant, const char *ExtraCode);
180 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
181 unsigned AsmVariant, const char *ExtraCode);
184 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
185 char value = MI->getOperand(OpNo).getImm();
186 value = (value << (32-5)) >> (32-5);
189 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
190 unsigned char value = MI->getOperand(OpNo).getImm();
191 assert(value <= 31 && "Invalid u5imm argument!");
192 O << (unsigned int)value;
194 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
195 unsigned char value = MI->getOperand(OpNo).getImm();
196 assert(value <= 63 && "Invalid u6imm argument!");
197 O << (unsigned int)value;
199 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
200 O << (short)MI->getOperand(OpNo).getImm();
202 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
203 O << (unsigned short)MI->getOperand(OpNo).getImm();
205 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
206 if (MI->getOperand(OpNo).isImm()) {
207 O << (short)(MI->getOperand(OpNo).getImm()*4);
210 printOp(MI->getOperand(OpNo));
211 if (TM.getRelocationModel() == Reloc::PIC_)
212 O << "-\"L" << getFunctionNumber() << "$pb\")";
217 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
218 // Branches can take an immediate operand. This is used by the branch
219 // selection pass to print $+8, an eight byte displacement from the PC.
220 if (MI->getOperand(OpNo).isImm()) {
221 O << "$+" << MI->getOperand(OpNo).getImm()*4;
223 printOp(MI->getOperand(OpNo));
226 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
227 const MachineOperand &MO = MI->getOperand(OpNo);
228 if (TM.getRelocationModel() != Reloc::Static) {
229 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
230 GlobalValue *GV = MO.getGlobal();
231 if (GV->isDeclaration() || GV->isWeakForLinker()) {
232 // Dynamically-resolved functions need a stub for the function.
233 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
234 FnInfo.Init(GV, Mang);
239 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
240 SmallString<128> MangledName;
241 Mang->getNameWithPrefix(MangledName, MO.getSymbolName());
242 FnStubInfo &FnInfo = FnStubs[MangledName.str()];
243 FnInfo.Init(MO.getSymbolName(), Mang);
249 printOp(MI->getOperand(OpNo));
251 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
252 O << (int)MI->getOperand(OpNo).getImm()*4;
254 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
255 O << "\"L" << getFunctionNumber() << "$pb\"\n";
256 O << "\"L" << getFunctionNumber() << "$pb\":";
258 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
259 if (MI->getOperand(OpNo).isImm()) {
260 printS16ImmOperand(MI, OpNo);
262 if (Subtarget.isDarwin()) O << "ha16(";
263 printOp(MI->getOperand(OpNo));
264 if (TM.getRelocationModel() == Reloc::PIC_)
265 O << "-\"L" << getFunctionNumber() << "$pb\"";
266 if (Subtarget.isDarwin())
272 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
273 if (MI->getOperand(OpNo).isImm()) {
274 printS16ImmOperand(MI, OpNo);
276 if (Subtarget.isDarwin()) O << "lo16(";
277 printOp(MI->getOperand(OpNo));
278 if (TM.getRelocationModel() == Reloc::PIC_)
279 O << "-\"L" << getFunctionNumber() << "$pb\"";
280 if (Subtarget.isDarwin())
286 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
287 unsigned CCReg = MI->getOperand(OpNo).getReg();
288 unsigned RegNo = enumRegToMachineReg(CCReg);
289 O << (0x80 >> RegNo);
291 // The new addressing mode printers.
292 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
293 printSymbolLo(MI, OpNo);
295 if (MI->getOperand(OpNo+1).isReg() &&
296 MI->getOperand(OpNo+1).getReg() == PPC::R0)
299 printOperand(MI, OpNo+1);
302 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
303 if (MI->getOperand(OpNo).isImm())
304 printS16X4ImmOperand(MI, OpNo);
306 printSymbolLo(MI, OpNo);
308 if (MI->getOperand(OpNo+1).isReg() &&
309 MI->getOperand(OpNo+1).getReg() == PPC::R0)
312 printOperand(MI, OpNo+1);
316 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
317 // When used as the base register, r0 reads constant zero rather than
318 // the value contained in the register. For this reason, the darwin
319 // assembler requires that we print r0 as 0 (no r) when used as the base.
320 const MachineOperand &MO = MI->getOperand(OpNo);
321 printRegister(MO, true);
323 printOperand(MI, OpNo+1);
326 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
327 const MachineOperand &MO = MI->getOperand(OpNo);
329 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
331 GlobalValue *GV = MO.getGlobal();
333 std::string Name = Mang->getMangledName(GV);
335 // Map symbol -> label of TOC entry.
336 if (TOC.count(Name) == 0) {
338 Label += MAI->getPrivateGlobalPrefix();
340 Label += utostr(LabelID++);
345 O << TOC[Name] << "@toc";
348 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
349 const char *Modifier);
351 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
354 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
355 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
357 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
358 const MCAsmInfo *T, bool V)
359 : PPCAsmPrinter(O, TM, T, V){}
361 virtual const char *getPassName() const {
362 return "Linux PPC Assembly Printer";
365 bool runOnMachineFunction(MachineFunction &F);
366 bool doFinalization(Module &M);
368 void getAnalysisUsage(AnalysisUsage &AU) const {
369 AU.setPreservesAll();
370 AU.addRequired<MachineModuleInfo>();
371 AU.addRequired<DwarfWriter>();
372 PPCAsmPrinter::getAnalysisUsage(AU);
375 void PrintGlobalVariable(const GlobalVariable *GVar);
378 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
380 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
381 formatted_raw_ostream &OS;
383 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
384 const MCAsmInfo *T, bool V)
385 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
387 virtual const char *getPassName() const {
388 return "Darwin PPC Assembly Printer";
391 bool runOnMachineFunction(MachineFunction &F);
392 bool doFinalization(Module &M);
393 void EmitStartOfAsmFile(Module &M);
395 void getAnalysisUsage(AnalysisUsage &AU) const {
396 AU.setPreservesAll();
397 AU.addRequired<MachineModuleInfo>();
398 AU.addRequired<DwarfWriter>();
399 PPCAsmPrinter::getAnalysisUsage(AU);
402 void PrintGlobalVariable(const GlobalVariable *GVar);
404 } // end of anonymous namespace
406 // Include the auto-generated portion of the assembly writer
407 #include "PPCGenAsmWriter.inc"
409 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
410 switch (MO.getType()) {
411 case MachineOperand::MO_Immediate:
412 llvm_unreachable("printOp() does not handle immediate values");
414 case MachineOperand::MO_MachineBasicBlock:
415 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
417 case MachineOperand::MO_JumpTableIndex:
418 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
419 << '_' << MO.getIndex();
420 // FIXME: PIC relocation model
422 case MachineOperand::MO_ConstantPoolIndex:
423 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
424 << '_' << MO.getIndex();
426 case MachineOperand::MO_BlockAddress:
427 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
429 case MachineOperand::MO_ExternalSymbol: {
430 // Computing the address of an external symbol, not calling it.
431 std::string Name(MAI->getGlobalPrefix());
432 Name += MO.getSymbolName();
434 if (TM.getRelocationModel() != Reloc::Static) {
435 GVStubs[Name] = Name+"$non_lazy_ptr";
436 Name += "$non_lazy_ptr";
441 case MachineOperand::MO_GlobalAddress: {
442 // Computing the address of a global symbol, not calling it.
443 GlobalValue *GV = MO.getGlobal();
446 // External or weakly linked global variables need non-lazily-resolved stubs
447 if (TM.getRelocationModel() != Reloc::Static &&
448 (GV->isDeclaration() || GV->isWeakForLinker())) {
449 if (!GV->hasHiddenVisibility()) {
450 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
451 GVStubs[Mang->getMangledName(GV)] = Name;
452 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
453 GV->hasAvailableExternallyLinkage()) {
454 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
455 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
457 Name = Mang->getMangledName(GV);
460 Name = Mang->getMangledName(GV);
464 printOffset(MO.getOffset());
469 O << "<unknown operand type: " << MO.getType() << ">";
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());
521 printOperand(MI, OpNo);
526 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
527 const char *Modifier) {
528 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
529 unsigned Code = MI->getOperand(OpNo).getImm();
530 if (!strcmp(Modifier, "cc")) {
531 switch ((PPC::Predicate)Code) {
532 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
533 case PPC::PRED_LT: O << "lt"; return;
534 case PPC::PRED_LE: O << "le"; return;
535 case PPC::PRED_EQ: O << "eq"; return;
536 case PPC::PRED_GE: O << "ge"; return;
537 case PPC::PRED_GT: O << "gt"; return;
538 case PPC::PRED_NE: O << "ne"; return;
539 case PPC::PRED_UN: O << "un"; return;
540 case PPC::PRED_NU: O << "nu"; return;
544 assert(!strcmp(Modifier, "reg") &&
545 "Need to specify 'cc' or 'reg' as predicate op modifier!");
546 // Don't print the register for 'always'.
547 if (Code == PPC::PRED_ALWAYS) return;
548 printOperand(MI, OpNo+1);
553 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
554 /// the current output stream.
556 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
559 processDebugLoc(MI, true);
561 // Check for slwi/srwi mnemonics.
562 bool useSubstituteMnemonic = false;
563 if (MI->getOpcode() == PPC::RLWINM) {
564 unsigned char SH = MI->getOperand(2).getImm();
565 unsigned char MB = MI->getOperand(3).getImm();
566 unsigned char ME = MI->getOperand(4).getImm();
567 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
568 O << "\tslwi "; useSubstituteMnemonic = true;
570 if (SH <= 31 && MB == (32-SH) && ME == 31) {
571 O << "\tsrwi "; useSubstituteMnemonic = true;
574 if (useSubstituteMnemonic) {
578 O << ", " << (unsigned int)SH;
580 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
581 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
582 useSubstituteMnemonic = true;
588 } else if (MI->getOpcode() == PPC::RLDICR) {
589 unsigned char SH = MI->getOperand(2).getImm();
590 unsigned char ME = MI->getOperand(3).getImm();
591 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
593 useSubstituteMnemonic = true;
598 O << ", " << (unsigned int)SH;
602 if (!useSubstituteMnemonic)
603 printInstruction(MI);
609 processDebugLoc(MI, false);
612 /// runOnMachineFunction - This uses the printMachineInstruction()
613 /// method to print assembly for each instruction.
615 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
618 SetupMachineFunction(MF);
621 // Print out constants referenced by the function
622 EmitConstantPool(MF.getConstantPool());
624 // Print out labels for the function.
625 const Function *F = MF.getFunction();
626 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
628 switch (F->getLinkage()) {
629 default: llvm_unreachable("Unknown linkage type!");
630 case Function::PrivateLinkage:
631 case Function::InternalLinkage: // Symbols default to internal.
633 case Function::ExternalLinkage:
634 O << "\t.global\t" << CurrentFnName << '\n'
635 << "\t.type\t" << CurrentFnName << ", @function\n";
637 case Function::LinkerPrivateLinkage:
638 case Function::WeakAnyLinkage:
639 case Function::WeakODRLinkage:
640 case Function::LinkOnceAnyLinkage:
641 case Function::LinkOnceODRLinkage:
642 O << "\t.global\t" << CurrentFnName << '\n';
643 O << "\t.weak\t" << CurrentFnName << '\n';
647 printVisibility(CurrentFnName, F->getVisibility());
649 EmitAlignment(MF.getAlignment(), F);
651 if (Subtarget.isPPC64()) {
652 // Emit an official procedure descriptor.
653 // FIXME 64-bit SVR4: Use MCSection here?
654 O << "\t.section\t\".opd\",\"aw\"\n";
656 O << CurrentFnName << ":\n";
657 O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
658 O << "\t.previous\n";
659 O << ".L." << CurrentFnName << ":\n";
661 O << CurrentFnName << ":\n";
664 // Emit pre-function debug information.
665 DW->BeginFunction(&MF);
667 // Print out code for the function.
668 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
670 // Print a label for the basic block.
671 if (I != MF.begin()) {
672 EmitBasicBlockStart(I);
674 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
676 // Print the assembly for the instruction.
677 printMachineInstruction(II);
681 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
683 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
685 // Emit post-function debug information.
686 DW->EndFunction(&MF);
688 // Print out jump tables referenced by the function.
689 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
691 // We didn't modify anything.
695 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
696 const TargetData *TD = TM.getTargetData();
698 if (!GVar->hasInitializer())
699 return; // External global require no code
701 // Check to see if this is a special global used by LLVM, if so, emit it.
702 if (EmitSpecialLLVMGlobal(GVar))
705 std::string name = Mang->getMangledName(GVar);
707 printVisibility(name, GVar->getVisibility());
709 Constant *C = GVar->getInitializer();
710 const Type *Type = C->getType();
711 unsigned Size = TD->getTypeAllocSize(Type);
712 unsigned Align = TD->getPreferredAlignmentLog(GVar);
714 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
717 if (C->isNullValue() && /* FIXME: Verify correct */
718 !GVar->hasSection() &&
719 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
720 GVar->isWeakForLinker())) {
721 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
723 if (GVar->hasExternalLinkage()) {
724 O << "\t.global " << name << '\n';
725 O << "\t.type " << name << ", @object\n";
727 O << "\t.zero " << Size << '\n';
728 } else if (GVar->hasLocalLinkage()) {
729 O << MAI->getLCOMMDirective() << name << ',' << Size;
731 O << ".comm " << name << ',' << Size;
734 O << "\t\t" << MAI->getCommentString() << " '";
735 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
742 switch (GVar->getLinkage()) {
743 case GlobalValue::LinkOnceAnyLinkage:
744 case GlobalValue::LinkOnceODRLinkage:
745 case GlobalValue::WeakAnyLinkage:
746 case GlobalValue::WeakODRLinkage:
747 case GlobalValue::CommonLinkage:
748 case GlobalValue::LinkerPrivateLinkage:
749 O << "\t.global " << name << '\n'
750 << "\t.type " << name << ", @object\n"
751 << "\t.weak " << name << '\n';
753 case GlobalValue::AppendingLinkage:
754 // FIXME: appending linkage variables should go into a section of
755 // their name or something. For now, just emit them as external.
756 case GlobalValue::ExternalLinkage:
757 // If external or appending, declare as a global symbol
758 O << "\t.global " << name << '\n'
759 << "\t.type " << name << ", @object\n";
761 case GlobalValue::InternalLinkage:
762 case GlobalValue::PrivateLinkage:
765 llvm_unreachable("Unknown linkage type!");
768 EmitAlignment(Align, GVar);
771 O << "\t\t\t\t" << MAI->getCommentString() << " '";
772 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
777 EmitGlobalConstant(C);
781 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
782 const TargetData *TD = TM.getTargetData();
784 bool isPPC64 = TD->getPointerSizeInBits() == 64;
786 if (isPPC64 && !TOC.empty()) {
787 // FIXME 64-bit SVR4: Use MCSection here?
788 O << "\t.section\t\".toc\",\"aw\"\n";
790 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
792 O << I->second << ":\n";
793 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
797 return AsmPrinter::doFinalization(M);
800 /// runOnMachineFunction - This uses the printMachineInstruction()
801 /// method to print assembly for each instruction.
803 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
806 SetupMachineFunction(MF);
809 // Print out constants referenced by the function
810 EmitConstantPool(MF.getConstantPool());
812 // Print out labels for the function.
813 const Function *F = MF.getFunction();
814 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
816 switch (F->getLinkage()) {
817 default: llvm_unreachable("Unknown linkage type!");
818 case Function::PrivateLinkage:
819 case Function::InternalLinkage: // Symbols default to internal.
821 case Function::ExternalLinkage:
822 O << "\t.globl\t" << CurrentFnName << '\n';
824 case Function::WeakAnyLinkage:
825 case Function::WeakODRLinkage:
826 case Function::LinkOnceAnyLinkage:
827 case Function::LinkOnceODRLinkage:
828 case Function::LinkerPrivateLinkage:
829 O << "\t.globl\t" << CurrentFnName << '\n';
830 O << "\t.weak_definition\t" << CurrentFnName << '\n';
834 printVisibility(CurrentFnName, F->getVisibility());
836 EmitAlignment(MF.getAlignment(), F);
837 O << CurrentFnName << ":\n";
839 // Emit pre-function debug information.
840 DW->BeginFunction(&MF);
842 // If the function is empty, then we need to emit *something*. Otherwise, the
843 // function's label might be associated with something that it wasn't meant to
844 // be associated with. We emit a noop in this situation.
845 MachineFunction::iterator I = MF.begin();
847 if (++I == MF.end() && MF.front().empty())
850 // Print out code for the function.
851 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
853 // Print a label for the basic block.
854 if (I != MF.begin()) {
855 EmitBasicBlockStart(I);
857 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
859 // Print the assembly for the instruction.
860 printMachineInstruction(II);
864 // Emit post-function debug information.
865 DW->EndFunction(&MF);
867 // Print out jump tables referenced by the function.
868 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
870 // We didn't modify anything.
875 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
876 static const char *const CPUDirectives[] = {
888 unsigned Directive = Subtarget.getDarwinDirective();
889 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
890 Directive = PPC::DIR_970;
891 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
892 Directive = PPC::DIR_7400;
893 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
894 Directive = PPC::DIR_64;
895 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
896 O << "\t.machine " << CPUDirectives[Directive] << '\n';
898 // Prime text sections so they are adjacent. This reduces the likelihood a
899 // large data or debug section causes a branch to exceed 16M limit.
900 TargetLoweringObjectFileMachO &TLOFMacho =
901 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
902 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
903 if (TM.getRelocationModel() == Reloc::PIC_) {
904 OutStreamer.SwitchSection(
905 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
906 MCSectionMachO::S_SYMBOL_STUBS |
907 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
908 32, SectionKind::getText()));
909 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
910 OutStreamer.SwitchSection(
911 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
912 MCSectionMachO::S_SYMBOL_STUBS |
913 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
914 16, SectionKind::getText()));
916 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
919 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
920 const TargetData *TD = TM.getTargetData();
922 if (!GVar->hasInitializer())
923 return; // External global require no code
925 // Check to see if this is a special global used by LLVM, if so, emit it.
926 if (EmitSpecialLLVMGlobal(GVar)) {
927 if (TM.getRelocationModel() == Reloc::Static) {
928 if (GVar->getName() == "llvm.global_ctors")
929 O << ".reference .constructors_used\n";
930 else if (GVar->getName() == "llvm.global_dtors")
931 O << ".reference .destructors_used\n";
936 std::string name = Mang->getMangledName(GVar);
937 printVisibility(name, GVar->getVisibility());
939 Constant *C = GVar->getInitializer();
940 const Type *Type = C->getType();
941 unsigned Size = TD->getTypeAllocSize(Type);
942 unsigned Align = TD->getPreferredAlignmentLog(GVar);
944 const MCSection *TheSection =
945 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
946 OutStreamer.SwitchSection(TheSection);
948 /// FIXME: Drive this off the section!
949 if (C->isNullValue() && /* FIXME: Verify correct */
950 !GVar->hasSection() &&
951 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
952 GVar->isWeakForLinker()) &&
953 // Don't put things that should go in the cstring section into "comm".
954 !TheSection->getKind().isMergeableCString()) {
955 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
957 if (GVar->hasExternalLinkage()) {
958 O << "\t.globl " << name << '\n';
959 O << "\t.zerofill __DATA, __common, " << name << ", "
960 << Size << ", " << Align;
961 } else if (GVar->hasLocalLinkage()) {
962 O << MAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
963 } else if (!GVar->hasCommonLinkage()) {
964 O << "\t.globl " << name << '\n'
965 << MAI->getWeakDefDirective() << name << '\n';
966 EmitAlignment(Align, GVar);
969 O << "\t\t\t\t" << MAI->getCommentString() << " ";
970 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
973 EmitGlobalConstant(C);
976 O << ".comm " << name << ',' << Size;
977 // Darwin 9 and above support aligned common data.
978 if (Subtarget.isDarwin9())
982 O << "\t\t" << MAI->getCommentString() << " '";
983 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
990 switch (GVar->getLinkage()) {
991 case GlobalValue::LinkOnceAnyLinkage:
992 case GlobalValue::LinkOnceODRLinkage:
993 case GlobalValue::WeakAnyLinkage:
994 case GlobalValue::WeakODRLinkage:
995 case GlobalValue::CommonLinkage:
996 case GlobalValue::LinkerPrivateLinkage:
997 O << "\t.globl " << name << '\n'
998 << "\t.weak_definition " << name << '\n';
1000 case GlobalValue::AppendingLinkage:
1001 // FIXME: appending linkage variables should go into a section of
1002 // their name or something. For now, just emit them as external.
1003 case GlobalValue::ExternalLinkage:
1004 // If external or appending, declare as a global symbol
1005 O << "\t.globl " << name << '\n';
1007 case GlobalValue::InternalLinkage:
1008 case GlobalValue::PrivateLinkage:
1011 llvm_unreachable("Unknown linkage type!");
1014 EmitAlignment(Align, GVar);
1017 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1018 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1023 EmitGlobalConstant(C);
1027 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1028 const TargetData *TD = TM.getTargetData();
1030 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1032 // Darwin/PPC always uses mach-o.
1033 TargetLoweringObjectFileMachO &TLOFMacho =
1034 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1037 const MCSection *LSPSection = 0;
1038 if (!FnStubs.empty()) // .lazy_symbol_pointer
1039 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1042 // Output stubs for dynamically-linked functions
1043 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1044 const MCSection *StubSection =
1045 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1046 MCSectionMachO::S_SYMBOL_STUBS |
1047 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1048 32, SectionKind::getText());
1049 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1051 OutStreamer.SwitchSection(StubSection);
1053 const FnStubInfo &Info = I->second;
1054 O << Info.Stub << ":\n";
1055 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1057 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1058 O << Info.AnonSymbol << ":\n";
1059 O << "\tmflr r11\n";
1060 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1063 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1064 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1065 O << "\tmtctr r12\n";
1068 OutStreamer.SwitchSection(LSPSection);
1069 O << Info.LazyPtr << ":\n";
1070 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1071 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1073 } else if (!FnStubs.empty()) {
1074 const MCSection *StubSection =
1075 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1076 MCSectionMachO::S_SYMBOL_STUBS |
1077 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1078 16, SectionKind::getText());
1080 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1082 OutStreamer.SwitchSection(StubSection);
1084 const FnStubInfo &Info = I->second;
1085 O << Info.Stub << ":\n";
1086 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1087 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1088 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1089 O << Info.LazyPtr << ")(r11)\n";
1090 O << "\tmtctr r12\n";
1092 OutStreamer.SwitchSection(LSPSection);
1093 O << Info.LazyPtr << ":\n";
1094 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1095 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1101 if (MAI->doesSupportExceptionHandling() && MMI) {
1102 // Add the (possibly multiple) personalities to the set of global values.
1103 // Only referenced functions get into the Personalities list.
1104 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1105 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1106 E = Personalities.end(); I != E; ++I) {
1108 GVStubs[Mang->getMangledName(*I)] =
1109 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1113 // Output macho stubs for external and common global variables.
1114 if (!GVStubs.empty()) {
1115 // Switch with ".non_lazy_symbol_pointer" directive.
1116 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1117 EmitAlignment(isPPC64 ? 3 : 2);
1119 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1120 E = GVStubs.end(); I != E; ++I) {
1121 O << I->second << ":\n";
1122 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1123 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1127 if (!HiddenGVStubs.empty()) {
1128 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1129 EmitAlignment(isPPC64 ? 3 : 2);
1130 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1131 E = HiddenGVStubs.end(); I != E; ++I) {
1132 O << I->second << ":\n";
1133 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1137 // Funny Darwin hack: This flag tells the linker that no global symbols
1138 // contain code that falls through to other global symbols (e.g. the obvious
1139 // implementation of multiple entry points). If this doesn't occur, the
1140 // linker can safely perform dead code stripping. Since LLVM never generates
1141 // code that does this, it is always safe to set.
1142 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1144 return AsmPrinter::doFinalization(M);
1149 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1150 /// for a MachineFunction to the given output stream, in a format that the
1151 /// Darwin assembler can deal with.
1153 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1155 const MCAsmInfo *tai,
1157 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1159 if (Subtarget->isDarwin())
1160 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1161 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1164 // Force static initialization.
1165 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1166 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1167 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);