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/MDNode.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.h"
30 #include "llvm/CodeGen/DwarfWriter.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Target/TargetAsmInfo.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/ADT/StringSet.h"
51 STATISTIC(EmittedInsts, "Number of machine instrs printed");
54 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
57 StringMap<std::string> GVStubs, HiddenGVStubs;
58 const PPCSubtarget &Subtarget;
60 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
61 const TargetAsmInfo *T, bool V)
62 : AsmPrinter(O, TM, T, V),
63 Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
65 virtual const char *getPassName() const {
66 return "PowerPC Assembly Printer";
69 PPCTargetMachine &getTM() {
70 return static_cast<PPCTargetMachine&>(TM);
73 unsigned enumRegToMachineReg(unsigned enumReg) {
75 default: llvm_unreachable("Unhandled register!");
76 case PPC::CR0: return 0;
77 case PPC::CR1: return 1;
78 case PPC::CR2: return 2;
79 case PPC::CR3: return 3;
80 case PPC::CR4: return 4;
81 case PPC::CR5: return 5;
82 case PPC::CR6: return 6;
83 case PPC::CR7: return 7;
88 /// printInstruction - This method is automatically generated by tablegen
89 /// from the instruction set description. This method returns true if the
90 /// machine instruction was sufficiently described to print it, otherwise it
92 bool printInstruction(const MachineInstr *MI);
94 void printMachineInstruction(const MachineInstr *MI);
95 void printOp(const MachineOperand &MO);
97 /// stripRegisterPrefix - This method strips the character prefix from a
98 /// register name so that only the number is left. Used by for linux asm.
99 const char *stripRegisterPrefix(const char *RegName) {
100 switch (RegName[0]) {
103 case 'v': return RegName + 1;
104 case 'c': if (RegName[1] == 'r') return RegName + 2;
110 /// printRegister - Print register according to target requirements.
112 void printRegister(const MachineOperand &MO, bool R0AsZero) {
113 unsigned RegNo = MO.getReg();
114 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
116 // If we should use 0 for R0.
117 if (R0AsZero && RegNo == PPC::R0) {
122 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
123 // Linux assembler (Others?) does not take register mnemonics.
124 // FIXME - What about special registers used in mfspr/mtspr?
125 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
129 void printOperand(const MachineInstr *MI, unsigned OpNo) {
130 const MachineOperand &MO = MI->getOperand(OpNo);
132 printRegister(MO, false);
133 } else if (MO.isImm()) {
140 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
141 unsigned AsmVariant, const char *ExtraCode);
142 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
143 unsigned AsmVariant, const char *ExtraCode);
146 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
147 char value = MI->getOperand(OpNo).getImm();
148 value = (value << (32-5)) >> (32-5);
151 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
152 unsigned char value = MI->getOperand(OpNo).getImm();
153 assert(value <= 31 && "Invalid u5imm argument!");
154 O << (unsigned int)value;
156 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
157 unsigned char value = MI->getOperand(OpNo).getImm();
158 assert(value <= 63 && "Invalid u6imm argument!");
159 O << (unsigned int)value;
161 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
162 O << (short)MI->getOperand(OpNo).getImm();
164 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
165 O << (unsigned short)MI->getOperand(OpNo).getImm();
167 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
168 if (MI->getOperand(OpNo).isImm()) {
169 O << (short)(MI->getOperand(OpNo).getImm()*4);
172 printOp(MI->getOperand(OpNo));
173 if (TM.getRelocationModel() == Reloc::PIC_)
174 O << "-\"L" << getFunctionNumber() << "$pb\")";
179 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
180 // Branches can take an immediate operand. This is used by the branch
181 // selection pass to print $+8, an eight byte displacement from the PC.
182 if (MI->getOperand(OpNo).isImm()) {
183 O << "$+" << MI->getOperand(OpNo).getImm()*4;
185 printOp(MI->getOperand(OpNo));
188 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
189 const MachineOperand &MO = MI->getOperand(OpNo);
190 if (TM.getRelocationModel() != Reloc::Static) {
191 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
192 GlobalValue *GV = MO.getGlobal();
193 if (GV->isDeclaration() || GV->isWeakForLinker()) {
194 // Dynamically-resolved functions need a stub for the function.
195 std::string Name = Mang->getMangledName(GV);
196 FnStubs.insert(Name);
197 printSuffixedName(Name, "$stub");
201 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
202 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
203 FnStubs.insert(Name);
204 printSuffixedName(Name, "$stub");
209 printOp(MI->getOperand(OpNo));
211 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
212 O << (int)MI->getOperand(OpNo).getImm()*4;
214 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
215 O << "\"L" << getFunctionNumber() << "$pb\"\n";
216 O << "\"L" << getFunctionNumber() << "$pb\":";
218 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
219 if (MI->getOperand(OpNo).isImm()) {
220 printS16ImmOperand(MI, OpNo);
222 if (Subtarget.isDarwin()) O << "ha16(";
223 printOp(MI->getOperand(OpNo));
224 if (TM.getRelocationModel() == Reloc::PIC_)
225 O << "-\"L" << getFunctionNumber() << "$pb\"";
226 if (Subtarget.isDarwin())
232 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
233 if (MI->getOperand(OpNo).isImm()) {
234 printS16ImmOperand(MI, OpNo);
236 if (Subtarget.isDarwin()) O << "lo16(";
237 printOp(MI->getOperand(OpNo));
238 if (TM.getRelocationModel() == Reloc::PIC_)
239 O << "-\"L" << getFunctionNumber() << "$pb\"";
240 if (Subtarget.isDarwin())
246 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
247 unsigned CCReg = MI->getOperand(OpNo).getReg();
248 unsigned RegNo = enumRegToMachineReg(CCReg);
249 O << (0x80 >> RegNo);
251 // The new addressing mode printers.
252 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
253 printSymbolLo(MI, OpNo);
255 if (MI->getOperand(OpNo+1).isReg() &&
256 MI->getOperand(OpNo+1).getReg() == PPC::R0)
259 printOperand(MI, OpNo+1);
262 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
263 if (MI->getOperand(OpNo).isImm())
264 printS16X4ImmOperand(MI, OpNo);
266 printSymbolLo(MI, OpNo);
268 if (MI->getOperand(OpNo+1).isReg() &&
269 MI->getOperand(OpNo+1).getReg() == PPC::R0)
272 printOperand(MI, OpNo+1);
276 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
277 // When used as the base register, r0 reads constant zero rather than
278 // the value contained in the register. For this reason, the darwin
279 // assembler requires that we print r0 as 0 (no r) when used as the base.
280 const MachineOperand &MO = MI->getOperand(OpNo);
281 printRegister(MO, true);
283 printOperand(MI, OpNo+1);
286 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
287 const char *Modifier);
289 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
290 virtual bool doFinalization(Module &M) = 0;
292 virtual void EmitExternalGlobal(const GlobalVariable *GV);
295 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
296 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
298 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, PPCTargetMachine &TM,
299 const TargetAsmInfo *T, bool V)
300 : PPCAsmPrinter(O, TM, T, V){}
302 virtual const char *getPassName() const {
303 return "Linux PPC Assembly Printer";
306 bool runOnMachineFunction(MachineFunction &F);
307 bool doFinalization(Module &M);
309 void getAnalysisUsage(AnalysisUsage &AU) const {
310 AU.setPreservesAll();
311 AU.addRequired<MachineModuleInfo>();
312 AU.addRequired<DwarfWriter>();
313 PPCAsmPrinter::getAnalysisUsage(AU);
316 void printModuleLevelGV(const GlobalVariable* GVar);
319 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
321 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
322 formatted_raw_ostream &OS;
324 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, PPCTargetMachine &TM,
325 const TargetAsmInfo *T, bool V)
326 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
328 virtual const char *getPassName() const {
329 return "Darwin PPC Assembly Printer";
332 bool runOnMachineFunction(MachineFunction &F);
333 bool doInitialization(Module &M);
334 bool doFinalization(Module &M);
336 void getAnalysisUsage(AnalysisUsage &AU) const {
337 AU.setPreservesAll();
338 AU.addRequired<MachineModuleInfo>();
339 AU.addRequired<DwarfWriter>();
340 PPCAsmPrinter::getAnalysisUsage(AU);
343 void printModuleLevelGV(const GlobalVariable* GVar);
345 } // end of anonymous namespace
347 // Include the auto-generated portion of the assembly writer
348 #include "PPCGenAsmWriter.inc"
350 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
351 switch (MO.getType()) {
352 case MachineOperand::MO_Immediate:
353 llvm_unreachable("printOp() does not handle immediate values");
355 case MachineOperand::MO_MachineBasicBlock:
356 printBasicBlockLabel(MO.getMBB());
358 case MachineOperand::MO_JumpTableIndex:
359 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
360 << '_' << MO.getIndex();
361 // FIXME: PIC relocation model
363 case MachineOperand::MO_ConstantPoolIndex:
364 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
365 << '_' << MO.getIndex();
367 case MachineOperand::MO_ExternalSymbol: {
368 // Computing the address of an external symbol, not calling it.
369 std::string Name(TAI->getGlobalPrefix());
370 Name += MO.getSymbolName();
372 if (TM.getRelocationModel() != Reloc::Static) {
373 GVStubs[Name] = Name+"$non_lazy_ptr";
374 Name += "$non_lazy_ptr";
379 case MachineOperand::MO_GlobalAddress: {
380 // Computing the address of a global symbol, not calling it.
381 GlobalValue *GV = MO.getGlobal();
384 // External or weakly linked global variables need non-lazily-resolved stubs
385 if (TM.getRelocationModel() != Reloc::Static &&
386 (GV->isDeclaration() || GV->isWeakForLinker())) {
387 if (!GV->hasHiddenVisibility()) {
388 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
389 GVStubs[Mang->getMangledName(GV)] = Name;
390 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
391 GV->hasAvailableExternallyLinkage()) {
392 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
393 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
395 Name = Mang->getMangledName(GV);
398 Name = Mang->getMangledName(GV);
402 printOffset(MO.getOffset());
407 O << "<unknown operand type: " << MO.getType() << ">";
412 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
414 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
417 if (TM.getRelocationModel() != Reloc::Static) {
418 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
420 Name = Mang->getMangledName(GV);
425 /// PrintAsmOperand - Print out an operand for an inline asm expression.
427 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
429 const char *ExtraCode) {
430 // Does this asm operand have a single letter operand modifier?
431 if (ExtraCode && ExtraCode[0]) {
432 if (ExtraCode[1] != 0) return true; // Unknown modifier.
434 switch (ExtraCode[0]) {
435 default: return true; // Unknown modifier.
436 case 'c': // Don't print "$" before a global var name or constant.
437 // PPC never has a prefix.
438 printOperand(MI, OpNo);
440 case 'L': // Write second word of DImode reference.
441 // Verify that this operand has two consecutive registers.
442 if (!MI->getOperand(OpNo).isReg() ||
443 OpNo+1 == MI->getNumOperands() ||
444 !MI->getOperand(OpNo+1).isReg())
446 ++OpNo; // Return the high-part.
449 // Write 'i' if an integer constant, otherwise nothing. Used to print
451 if (MI->getOperand(OpNo).isImm())
457 printOperand(MI, OpNo);
461 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
463 const char *ExtraCode) {
464 if (ExtraCode && ExtraCode[0])
465 return true; // Unknown modifier.
466 if (MI->getOperand(OpNo).isReg())
467 printMemRegReg(MI, OpNo);
469 printMemRegImm(MI, OpNo);
473 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
474 const char *Modifier) {
475 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
476 unsigned Code = MI->getOperand(OpNo).getImm();
477 if (!strcmp(Modifier, "cc")) {
478 switch ((PPC::Predicate)Code) {
479 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
480 case PPC::PRED_LT: O << "lt"; return;
481 case PPC::PRED_LE: O << "le"; return;
482 case PPC::PRED_EQ: O << "eq"; return;
483 case PPC::PRED_GE: O << "ge"; return;
484 case PPC::PRED_GT: O << "gt"; return;
485 case PPC::PRED_NE: O << "ne"; return;
486 case PPC::PRED_UN: O << "un"; return;
487 case PPC::PRED_NU: O << "nu"; return;
491 assert(!strcmp(Modifier, "reg") &&
492 "Need to specify 'cc' or 'reg' as predicate op modifier!");
493 // Don't print the register for 'always'.
494 if (Code == PPC::PRED_ALWAYS) return;
495 printOperand(MI, OpNo+1);
500 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
501 /// the current output stream.
503 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
506 // Check for slwi/srwi mnemonics.
507 if (MI->getOpcode() == PPC::RLWINM) {
508 bool FoundMnemonic = false;
509 unsigned char SH = MI->getOperand(2).getImm();
510 unsigned char MB = MI->getOperand(3).getImm();
511 unsigned char ME = MI->getOperand(4).getImm();
512 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
513 O << "\tslwi "; FoundMnemonic = true;
515 if (SH <= 31 && MB == (32-SH) && ME == 31) {
516 O << "\tsrwi "; FoundMnemonic = true;
523 O << ", " << (unsigned int)SH << '\n';
526 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
527 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
535 } else if (MI->getOpcode() == PPC::RLDICR) {
536 unsigned char SH = MI->getOperand(2).getImm();
537 unsigned char ME = MI->getOperand(3).getImm();
538 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
544 O << ", " << (unsigned int)SH << '\n';
549 if (printInstruction(MI))
550 return; // Printer was automatically generated
552 llvm_unreachable("Unhandled instruction in asm writer!");
555 /// runOnMachineFunction - This uses the printMachineInstruction()
556 /// method to print assembly for each instruction.
558 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
561 SetupMachineFunction(MF);
564 // Print out constants referenced by the function
565 EmitConstantPool(MF.getConstantPool());
567 // Print out labels for the function.
568 const Function *F = MF.getFunction();
569 SwitchToSection(TAI->SectionForGlobal(F));
571 switch (F->getLinkage()) {
572 default: llvm_unreachable("Unknown linkage type!");
573 case Function::PrivateLinkage:
574 case Function::InternalLinkage: // Symbols default to internal.
576 case Function::ExternalLinkage:
577 O << "\t.global\t" << CurrentFnName << '\n'
578 << "\t.type\t" << CurrentFnName << ", @function\n";
580 case Function::WeakAnyLinkage:
581 case Function::WeakODRLinkage:
582 case Function::LinkOnceAnyLinkage:
583 case Function::LinkOnceODRLinkage:
584 O << "\t.global\t" << CurrentFnName << '\n';
585 O << "\t.weak\t" << CurrentFnName << '\n';
589 printVisibility(CurrentFnName, F->getVisibility());
591 EmitAlignment(MF.getAlignment(), F);
592 O << CurrentFnName << ":\n";
594 // Emit pre-function debug information.
595 DW->BeginFunction(&MF);
597 // Print out code for the function.
598 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
600 // Print a label for the basic block.
601 if (I != MF.begin()) {
602 printBasicBlockLabel(I, true, true);
605 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
607 // Print the assembly for the instruction.
608 printMachineInstruction(II);
612 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
614 // Print out jump tables referenced by the function.
615 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
617 SwitchToSection(TAI->SectionForGlobal(F));
619 // Emit post-function debug information.
620 DW->EndFunction(&MF);
624 // We didn't modify anything.
628 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
629 /// Don't print things like \\n or \\0.
630 static void PrintUnmangledNameSafely(const Value *V, formatted_raw_ostream &OS) {
631 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
637 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
638 const TargetData *TD = TM.getTargetData();
640 if (!GVar->hasInitializer())
641 return; // External global require no code
643 // Check to see if this is a special global used by LLVM, if so, emit it.
644 if (EmitSpecialLLVMGlobal(GVar))
647 std::string name = Mang->getMangledName(GVar);
649 printVisibility(name, GVar->getVisibility());
651 Constant *C = GVar->getInitializer();
652 if (isa<MDNode>(C) || isa<MDString>(C))
654 const Type *Type = C->getType();
655 unsigned Size = TD->getTypeAllocSize(Type);
656 unsigned Align = TD->getPreferredAlignmentLog(GVar);
658 SwitchToSection(TAI->SectionForGlobal(GVar));
660 if (C->isNullValue() && /* FIXME: Verify correct */
661 !GVar->hasSection() &&
662 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
663 GVar->isWeakForLinker())) {
664 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
666 if (GVar->hasExternalLinkage()) {
667 O << "\t.global " << name << '\n';
668 O << "\t.type " << name << ", @object\n";
670 O << "\t.zero " << Size << '\n';
671 } else if (GVar->hasLocalLinkage()) {
672 O << TAI->getLCOMMDirective() << name << ',' << Size;
674 O << ".comm " << name << ',' << Size;
677 O << "\t\t" << TAI->getCommentString() << " '";
678 PrintUnmangledNameSafely(GVar, O);
685 switch (GVar->getLinkage()) {
686 case GlobalValue::LinkOnceAnyLinkage:
687 case GlobalValue::LinkOnceODRLinkage:
688 case GlobalValue::WeakAnyLinkage:
689 case GlobalValue::WeakODRLinkage:
690 case GlobalValue::CommonLinkage:
691 O << "\t.global " << name << '\n'
692 << "\t.type " << name << ", @object\n"
693 << "\t.weak " << name << '\n';
695 case GlobalValue::AppendingLinkage:
696 // FIXME: appending linkage variables should go into a section of
697 // their name or something. For now, just emit them as external.
698 case GlobalValue::ExternalLinkage:
699 // If external or appending, declare as a global symbol
700 O << "\t.global " << name << '\n'
701 << "\t.type " << name << ", @object\n";
703 case GlobalValue::InternalLinkage:
704 case GlobalValue::PrivateLinkage:
707 llvm_unreachable("Unknown linkage type!");
710 EmitAlignment(Align, GVar);
713 O << "\t\t\t\t" << TAI->getCommentString() << " '";
714 PrintUnmangledNameSafely(GVar, O);
719 EmitGlobalConstant(C);
723 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
724 // Print out module-level global variables here.
725 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
727 printModuleLevelGV(I);
729 return AsmPrinter::doFinalization(M);
732 /// runOnMachineFunction - This uses the printMachineInstruction()
733 /// method to print assembly for each instruction.
735 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
738 SetupMachineFunction(MF);
741 // Print out constants referenced by the function
742 EmitConstantPool(MF.getConstantPool());
744 // Print out labels for the function.
745 const Function *F = MF.getFunction();
746 SwitchToSection(TAI->SectionForGlobal(F));
748 switch (F->getLinkage()) {
749 default: llvm_unreachable("Unknown linkage type!");
750 case Function::PrivateLinkage:
751 case Function::InternalLinkage: // Symbols default to internal.
753 case Function::ExternalLinkage:
754 O << "\t.globl\t" << CurrentFnName << '\n';
756 case Function::WeakAnyLinkage:
757 case Function::WeakODRLinkage:
758 case Function::LinkOnceAnyLinkage:
759 case Function::LinkOnceODRLinkage:
760 O << "\t.globl\t" << CurrentFnName << '\n';
761 O << "\t.weak_definition\t" << CurrentFnName << '\n';
765 printVisibility(CurrentFnName, F->getVisibility());
767 EmitAlignment(MF.getAlignment(), F);
768 O << CurrentFnName << ":\n";
770 // Emit pre-function debug information.
771 DW->BeginFunction(&MF);
773 // If the function is empty, then we need to emit *something*. Otherwise, the
774 // function's label might be associated with something that it wasn't meant to
775 // be associated with. We emit a noop in this situation.
776 MachineFunction::iterator I = MF.begin();
778 if (++I == MF.end() && MF.front().empty())
781 // Print out code for the function.
782 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
784 // Print a label for the basic block.
785 if (I != MF.begin()) {
786 printBasicBlockLabel(I, true, true, VerboseAsm);
789 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
791 // Print the assembly for the instruction.
792 printMachineInstruction(II);
796 // Print out jump tables referenced by the function.
797 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
799 // Emit post-function debug information.
800 DW->EndFunction(&MF);
802 // We didn't modify anything.
807 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
808 static const char *const CPUDirectives[] = {
820 unsigned Directive = Subtarget.getDarwinDirective();
821 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
822 Directive = PPC::DIR_970;
823 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
824 Directive = PPC::DIR_7400;
825 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
826 Directive = PPC::DIR_64;
827 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
828 O << "\t.machine " << CPUDirectives[Directive] << '\n';
830 bool Result = AsmPrinter::doInitialization(M);
833 // Prime text sections so they are adjacent. This reduces the likelihood a
834 // large data or debug section causes a branch to exceed 16M limit.
835 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
836 "pure_instructions");
837 if (TM.getRelocationModel() == Reloc::PIC_) {
838 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
839 "pure_instructions,32");
840 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
841 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
842 "pure_instructions,16");
844 SwitchToSection(TAI->getTextSection());
849 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
850 const TargetData *TD = TM.getTargetData();
852 if (!GVar->hasInitializer())
853 return; // External global require no code
855 // Check to see if this is a special global used by LLVM, if so, emit it.
856 if (EmitSpecialLLVMGlobal(GVar)) {
857 if (TM.getRelocationModel() == Reloc::Static) {
858 if (GVar->getName() == "llvm.global_ctors")
859 O << ".reference .constructors_used\n";
860 else if (GVar->getName() == "llvm.global_dtors")
861 O << ".reference .destructors_used\n";
866 std::string name = Mang->getMangledName(GVar);
867 printVisibility(name, GVar->getVisibility());
869 Constant *C = GVar->getInitializer();
870 const Type *Type = C->getType();
871 unsigned Size = TD->getTypeAllocSize(Type);
872 unsigned Align = TD->getPreferredAlignmentLog(GVar);
874 SwitchToSection(TAI->SectionForGlobal(GVar));
876 if (C->isNullValue() && /* FIXME: Verify correct */
877 !GVar->hasSection() &&
878 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
879 GVar->isWeakForLinker()) &&
880 TAI->SectionKindForGlobal(GVar) != SectionKind::RODataMergeStr) {
881 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
883 if (GVar->hasExternalLinkage()) {
884 O << "\t.globl " << name << '\n';
885 O << "\t.zerofill __DATA, __common, " << name << ", "
886 << Size << ", " << Align;
887 } else if (GVar->hasLocalLinkage()) {
888 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
889 } else if (!GVar->hasCommonLinkage()) {
890 O << "\t.globl " << name << '\n'
891 << TAI->getWeakDefDirective() << name << '\n';
892 EmitAlignment(Align, GVar);
895 O << "\t\t\t\t" << TAI->getCommentString() << " ";
896 PrintUnmangledNameSafely(GVar, O);
899 EmitGlobalConstant(C);
902 O << ".comm " << name << ',' << Size;
903 // Darwin 9 and above support aligned common data.
904 if (Subtarget.isDarwin9())
908 O << "\t\t" << TAI->getCommentString() << " '";
909 PrintUnmangledNameSafely(GVar, O);
916 switch (GVar->getLinkage()) {
917 case GlobalValue::LinkOnceAnyLinkage:
918 case GlobalValue::LinkOnceODRLinkage:
919 case GlobalValue::WeakAnyLinkage:
920 case GlobalValue::WeakODRLinkage:
921 case GlobalValue::CommonLinkage:
922 O << "\t.globl " << name << '\n'
923 << "\t.weak_definition " << name << '\n';
925 case GlobalValue::AppendingLinkage:
926 // FIXME: appending linkage variables should go into a section of
927 // their name or something. For now, just emit them as external.
928 case GlobalValue::ExternalLinkage:
929 // If external or appending, declare as a global symbol
930 O << "\t.globl " << name << '\n';
932 case GlobalValue::InternalLinkage:
933 case GlobalValue::PrivateLinkage:
936 llvm_unreachable("Unknown linkage type!");
939 EmitAlignment(Align, GVar);
942 O << "\t\t\t\t" << TAI->getCommentString() << " '";
943 PrintUnmangledNameSafely(GVar, O);
948 EmitGlobalConstant(C);
952 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
953 const TargetData *TD = TM.getTargetData();
955 // Print out module-level global variables here.
956 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
958 printModuleLevelGV(I);
960 bool isPPC64 = TD->getPointerSizeInBits() == 64;
962 // Output stubs for dynamically-linked functions
963 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
964 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
965 "pure_instructions,32");
966 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
969 const char *p = I->getKeyData();
970 bool hasQuote = p[0]=='\"';
971 printSuffixedName(p, "$stub");
973 O << "\t.indirect_symbol " << p << '\n';
977 O << "\"L0$" << &p[1];
982 O << "\"L0$" << &p[1];
987 O << "\taddis r11,r11,ha16(";
988 printSuffixedName(p, "$lazy_ptr");
991 O << "\"L0$" << &p[1];
997 O << "\tldu r12,lo16(";
999 O << "\tlwzu r12,lo16(";
1000 printSuffixedName(p, "$lazy_ptr");
1003 O << "\"L0$" << &p[1];
1007 O << "\tmtctr r12\n";
1009 SwitchToDataSection(".lazy_symbol_pointer");
1010 printSuffixedName(p, "$lazy_ptr");
1012 O << "\t.indirect_symbol " << p << '\n';
1014 O << "\t.quad dyld_stub_binding_helper\n";
1016 O << "\t.long dyld_stub_binding_helper\n";
1018 } else if (!FnStubs.empty()) {
1019 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1020 "pure_instructions,16");
1021 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1024 const char *p = I->getKeyData();
1025 printSuffixedName(p, "$stub");
1027 O << "\t.indirect_symbol " << p << '\n';
1028 O << "\tlis r11,ha16(";
1029 printSuffixedName(p, "$lazy_ptr");
1032 O << "\tldu r12,lo16(";
1034 O << "\tlwzu r12,lo16(";
1035 printSuffixedName(p, "$lazy_ptr");
1037 O << "\tmtctr r12\n";
1039 SwitchToDataSection(".lazy_symbol_pointer");
1040 printSuffixedName(p, "$lazy_ptr");
1042 O << "\t.indirect_symbol " << p << '\n';
1044 O << "\t.quad dyld_stub_binding_helper\n";
1046 O << "\t.long dyld_stub_binding_helper\n";
1052 if (TAI->doesSupportExceptionHandling() && MMI) {
1053 // Add the (possibly multiple) personalities to the set of global values.
1054 // Only referenced functions get into the Personalities list.
1055 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1056 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1057 E = Personalities.end(); I != E; ++I) {
1059 GVStubs[Mang->getMangledName(*I)] =
1060 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1064 // Output stubs for external and common global variables.
1065 if (!GVStubs.empty()) {
1066 SwitchToDataSection(".non_lazy_symbol_pointer");
1067 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1068 E = GVStubs.end(); I != E; ++I) {
1069 O << I->second << ":\n";
1070 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1071 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1075 if (!HiddenGVStubs.empty()) {
1076 SwitchToSection(TAI->getDataSection());
1077 EmitAlignment(isPPC64 ? 3 : 2);
1078 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1079 E = HiddenGVStubs.end(); I != E; ++I) {
1080 O << I->second << ":\n";
1081 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1085 // Funny Darwin hack: This flag tells the linker that no global symbols
1086 // contain code that falls through to other global symbols (e.g. the obvious
1087 // implementation of multiple entry points). If this doesn't occur, the
1088 // linker can safely perform dead code stripping. Since LLVM never generates
1089 // code that does this, it is always safe to set.
1090 O << "\t.subsections_via_symbols\n";
1092 return AsmPrinter::doFinalization(M);
1097 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1098 /// for a MachineFunction to the given output stream, in a format that the
1099 /// Darwin assembler can deal with.
1101 FunctionPass *llvm::createPPCAsmPrinterPass(formatted_raw_ostream &o,
1102 PPCTargetMachine &tm,
1104 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1106 if (Subtarget->isDarwin()) {
1107 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1109 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1114 static struct Register {
1116 PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);
1121 extern "C" int PowerPCAsmPrinterForceLink;
1122 int PowerPCAsmPrinterForceLink = 0;
1124 // Force static initialization.
1125 extern "C" void LLVMInitializePowerPCAsmPrinter() { }