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/Support/Mangler.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetAsmInfo.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/StringSet.h"
49 STATISTIC(EmittedInsts, "Number of machine instrs printed");
52 struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
53 StringSet<> FnStubs, GVStubs, HiddenGVStubs;
54 const PPCSubtarget &Subtarget;
56 PPCAsmPrinter(raw_ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
57 : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
60 virtual const char *getPassName() const {
61 return "PowerPC Assembly Printer";
64 PPCTargetMachine &getTM() {
65 return static_cast<PPCTargetMachine&>(TM);
68 unsigned enumRegToMachineReg(unsigned enumReg) {
70 default: assert(0 && "Unhandled register!"); break;
71 case PPC::CR0: return 0;
72 case PPC::CR1: return 1;
73 case PPC::CR2: return 2;
74 case PPC::CR3: return 3;
75 case PPC::CR4: return 4;
76 case PPC::CR5: return 5;
77 case PPC::CR6: return 6;
78 case PPC::CR7: return 7;
83 /// printInstruction - This method is automatically generated by tablegen
84 /// from the instruction set description. This method returns true if the
85 /// machine instruction was sufficiently described to print it, otherwise it
87 bool printInstruction(const MachineInstr *MI);
89 void printMachineInstruction(const MachineInstr *MI);
90 void printOp(const MachineOperand &MO);
92 /// stripRegisterPrefix - This method strips the character prefix from a
93 /// register name so that only the number is left. Used by for linux asm.
94 const char *stripRegisterPrefix(const char *RegName) {
98 case 'v': return RegName + 1;
99 case 'c': if (RegName[1] == 'r') return RegName + 2;
105 /// printRegister - Print register according to target requirements.
107 void printRegister(const MachineOperand &MO, bool R0AsZero) {
108 unsigned RegNo = MO.getReg();
109 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
111 // If we should use 0 for R0.
112 if (R0AsZero && RegNo == PPC::R0) {
117 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
118 // Linux assembler (Others?) does not take register mnemonics.
119 // FIXME - What about special registers used in mfspr/mtspr?
120 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
124 void printOperand(const MachineInstr *MI, unsigned OpNo) {
125 const MachineOperand &MO = MI->getOperand(OpNo);
127 printRegister(MO, false);
128 } else if (MO.isImm()) {
135 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
136 unsigned AsmVariant, const char *ExtraCode);
137 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
138 unsigned AsmVariant, const char *ExtraCode);
141 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
142 char value = MI->getOperand(OpNo).getImm();
143 value = (value << (32-5)) >> (32-5);
146 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
147 unsigned char value = MI->getOperand(OpNo).getImm();
148 assert(value <= 31 && "Invalid u5imm argument!");
149 O << (unsigned int)value;
151 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
152 unsigned char value = MI->getOperand(OpNo).getImm();
153 assert(value <= 63 && "Invalid u6imm argument!");
154 O << (unsigned int)value;
156 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
157 O << (short)MI->getOperand(OpNo).getImm();
159 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
160 O << (unsigned short)MI->getOperand(OpNo).getImm();
162 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
163 if (MI->getOperand(OpNo).isImm()) {
164 O << (short)(MI->getOperand(OpNo).getImm()*4);
167 printOp(MI->getOperand(OpNo));
168 if (TM.getRelocationModel() == Reloc::PIC_)
169 O << "-\"L" << getFunctionNumber() << "$pb\")";
174 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
175 // Branches can take an immediate operand. This is used by the branch
176 // selection pass to print $+8, an eight byte displacement from the PC.
177 if (MI->getOperand(OpNo).isImm()) {
178 O << "$+" << MI->getOperand(OpNo).getImm()*4;
180 printOp(MI->getOperand(OpNo));
183 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
184 const MachineOperand &MO = MI->getOperand(OpNo);
185 if (TM.getRelocationModel() != Reloc::Static) {
186 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
187 GlobalValue *GV = MO.getGlobal();
188 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
189 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
190 // Dynamically-resolved functions need a stub for the function.
191 std::string Name = Mang->getValueName(GV);
192 FnStubs.insert(Name);
193 printSuffixedName(Name, "$stub");
194 if (GV->hasExternalWeakLinkage())
195 ExtWeakSymbols.insert(GV);
199 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
200 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
201 FnStubs.insert(Name);
202 printSuffixedName(Name, "$stub");
207 printOp(MI->getOperand(OpNo));
209 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
210 O << (int)MI->getOperand(OpNo).getImm()*4;
212 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
213 O << "\"L" << getFunctionNumber() << "$pb\"\n";
214 O << "\"L" << getFunctionNumber() << "$pb\":";
216 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
217 if (MI->getOperand(OpNo).isImm()) {
218 printS16ImmOperand(MI, OpNo);
220 if (Subtarget.isDarwin()) O << "ha16(";
221 printOp(MI->getOperand(OpNo));
222 if (TM.getRelocationModel() == Reloc::PIC_)
223 O << "-\"L" << getFunctionNumber() << "$pb\"";
224 if (Subtarget.isDarwin())
230 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
231 if (MI->getOperand(OpNo).isImm()) {
232 printS16ImmOperand(MI, OpNo);
234 if (Subtarget.isDarwin()) O << "lo16(";
235 printOp(MI->getOperand(OpNo));
236 if (TM.getRelocationModel() == Reloc::PIC_)
237 O << "-\"L" << getFunctionNumber() << "$pb\"";
238 if (Subtarget.isDarwin())
244 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
245 unsigned CCReg = MI->getOperand(OpNo).getReg();
246 unsigned RegNo = enumRegToMachineReg(CCReg);
247 O << (0x80 >> RegNo);
249 // The new addressing mode printers.
250 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
251 printSymbolLo(MI, OpNo);
253 if (MI->getOperand(OpNo+1).isReg() &&
254 MI->getOperand(OpNo+1).getReg() == PPC::R0)
257 printOperand(MI, OpNo+1);
260 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
261 if (MI->getOperand(OpNo).isImm())
262 printS16X4ImmOperand(MI, OpNo);
264 printSymbolLo(MI, OpNo);
266 if (MI->getOperand(OpNo+1).isReg() &&
267 MI->getOperand(OpNo+1).getReg() == PPC::R0)
270 printOperand(MI, OpNo+1);
274 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
275 // When used as the base register, r0 reads constant zero rather than
276 // the value contained in the register. For this reason, the darwin
277 // assembler requires that we print r0 as 0 (no r) when used as the base.
278 const MachineOperand &MO = MI->getOperand(OpNo);
279 printRegister(MO, true);
281 printOperand(MI, OpNo+1);
284 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
285 const char *Modifier);
287 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
288 virtual bool doFinalization(Module &M) = 0;
290 virtual void EmitExternalGlobal(const GlobalVariable *GV);
293 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
294 struct VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
296 MachineModuleInfo *MMI;
298 PPCLinuxAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
299 const TargetAsmInfo *T)
300 : PPCAsmPrinter(O, TM, T), DW(0), MMI(0) {
303 virtual const char *getPassName() const {
304 return "Linux PPC Assembly Printer";
307 bool runOnMachineFunction(MachineFunction &F);
308 bool doInitialization(Module &M);
309 bool doFinalization(Module &M);
311 void getAnalysisUsage(AnalysisUsage &AU) const {
312 AU.setPreservesAll();
313 AU.addRequired<MachineModuleInfo>();
314 AU.addRequired<DwarfWriter>();
315 PPCAsmPrinter::getAnalysisUsage(AU);
318 void printModuleLevelGV(const GlobalVariable* GVar);
321 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
323 struct VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
326 MachineModuleInfo *MMI;
328 PPCDarwinAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
329 const TargetAsmInfo *T)
330 : PPCAsmPrinter(O, TM, T), DW(0), MMI(0), OS(O) {
333 virtual const char *getPassName() const {
334 return "Darwin PPC Assembly Printer";
337 bool runOnMachineFunction(MachineFunction &F);
338 bool doInitialization(Module &M);
339 bool doFinalization(Module &M);
341 void getAnalysisUsage(AnalysisUsage &AU) const {
342 AU.setPreservesAll();
343 AU.addRequired<MachineModuleInfo>();
344 AU.addRequired<DwarfWriter>();
345 PPCAsmPrinter::getAnalysisUsage(AU);
348 void printModuleLevelGV(const GlobalVariable* GVar);
350 } // end of anonymous namespace
352 // Include the auto-generated portion of the assembly writer
353 #include "PPCGenAsmWriter.inc"
355 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
356 switch (MO.getType()) {
357 case MachineOperand::MO_Immediate:
358 cerr << "printOp() does not handle immediate values\n";
362 case MachineOperand::MO_MachineBasicBlock:
363 printBasicBlockLabel(MO.getMBB());
365 case MachineOperand::MO_JumpTableIndex:
366 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
367 << '_' << MO.getIndex();
368 // FIXME: PIC relocation model
370 case MachineOperand::MO_ConstantPoolIndex:
371 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
372 << '_' << MO.getIndex();
374 case MachineOperand::MO_ExternalSymbol:
375 // Computing the address of an external symbol, not calling it.
376 if (TM.getRelocationModel() != Reloc::Static) {
377 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
378 GVStubs.insert(Name);
379 printSuffixedName(Name, "$non_lazy_ptr");
382 O << TAI->getGlobalPrefix() << MO.getSymbolName();
384 case MachineOperand::MO_GlobalAddress: {
385 // Computing the address of a global symbol, not calling it.
386 GlobalValue *GV = MO.getGlobal();
387 std::string Name = Mang->getValueName(GV);
389 // External or weakly linked global variables need non-lazily-resolved stubs
390 if (TM.getRelocationModel() != Reloc::Static) {
391 if (GV->isDeclaration() || GV->mayBeOverridden()) {
392 if (GV->hasHiddenVisibility()) {
393 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
396 HiddenGVStubs.insert(Name);
397 printSuffixedName(Name, "$non_lazy_ptr");
400 GVStubs.insert(Name);
401 printSuffixedName(Name, "$non_lazy_ptr");
403 if (GV->hasExternalWeakLinkage())
404 ExtWeakSymbols.insert(GV);
410 printOffset(MO.getOffset());
412 if (GV->hasExternalWeakLinkage())
413 ExtWeakSymbols.insert(GV);
418 O << "<unknown operand type: " << MO.getType() << ">";
423 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
425 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
426 std::string Name = getGlobalLinkName(GV);
427 if (TM.getRelocationModel() != Reloc::Static) {
428 if (GV->hasHiddenVisibility())
429 HiddenGVStubs.insert(Name);
431 GVStubs.insert(Name);
432 printSuffixedName(Name, "$non_lazy_ptr");
438 /// PrintAsmOperand - Print out an operand for an inline asm expression.
440 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
442 const char *ExtraCode) {
443 // Does this asm operand have a single letter operand modifier?
444 if (ExtraCode && ExtraCode[0]) {
445 if (ExtraCode[1] != 0) return true; // Unknown modifier.
447 switch (ExtraCode[0]) {
448 default: return true; // Unknown modifier.
449 case 'c': // Don't print "$" before a global var name or constant.
450 // PPC never has a prefix.
451 printOperand(MI, OpNo);
453 case 'L': // Write second word of DImode reference.
454 // Verify that this operand has two consecutive registers.
455 if (!MI->getOperand(OpNo).isReg() ||
456 OpNo+1 == MI->getNumOperands() ||
457 !MI->getOperand(OpNo+1).isReg())
459 ++OpNo; // Return the high-part.
462 // Write 'i' if an integer constant, otherwise nothing. Used to print
464 if (MI->getOperand(OpNo).isImm())
470 printOperand(MI, OpNo);
474 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
476 const char *ExtraCode) {
477 if (ExtraCode && ExtraCode[0])
478 return true; // Unknown modifier.
479 if (MI->getOperand(OpNo).isReg())
480 printMemRegReg(MI, OpNo);
482 printMemRegImm(MI, OpNo);
486 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
487 const char *Modifier) {
488 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
489 unsigned Code = MI->getOperand(OpNo).getImm();
490 if (!strcmp(Modifier, "cc")) {
491 switch ((PPC::Predicate)Code) {
492 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
493 case PPC::PRED_LT: O << "lt"; return;
494 case PPC::PRED_LE: O << "le"; return;
495 case PPC::PRED_EQ: O << "eq"; return;
496 case PPC::PRED_GE: O << "ge"; return;
497 case PPC::PRED_GT: O << "gt"; return;
498 case PPC::PRED_NE: O << "ne"; return;
499 case PPC::PRED_UN: O << "un"; return;
500 case PPC::PRED_NU: O << "nu"; return;
504 assert(!strcmp(Modifier, "reg") &&
505 "Need to specify 'cc' or 'reg' as predicate op modifier!");
506 // Don't print the register for 'always'.
507 if (Code == PPC::PRED_ALWAYS) return;
508 printOperand(MI, OpNo+1);
513 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
514 /// the current output stream.
516 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
519 // Check for slwi/srwi mnemonics.
520 if (MI->getOpcode() == PPC::RLWINM) {
521 bool FoundMnemonic = false;
522 unsigned char SH = MI->getOperand(2).getImm();
523 unsigned char MB = MI->getOperand(3).getImm();
524 unsigned char ME = MI->getOperand(4).getImm();
525 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
526 O << "\tslwi "; FoundMnemonic = true;
528 if (SH <= 31 && MB == (32-SH) && ME == 31) {
529 O << "\tsrwi "; FoundMnemonic = true;
536 O << ", " << (unsigned int)SH << '\n';
539 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
540 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
548 } else if (MI->getOpcode() == PPC::RLDICR) {
549 unsigned char SH = MI->getOperand(2).getImm();
550 unsigned char ME = MI->getOperand(3).getImm();
551 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
557 O << ", " << (unsigned int)SH << '\n';
562 if (printInstruction(MI))
563 return; // Printer was automatically generated
565 assert(0 && "Unhandled instruction in asm writer!");
570 /// runOnMachineFunction - This uses the printMachineInstruction()
571 /// method to print assembly for each instruction.
573 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
575 SetupMachineFunction(MF);
578 // Print out constants referenced by the function
579 EmitConstantPool(MF.getConstantPool());
581 // Print out labels for the function.
582 const Function *F = MF.getFunction();
583 SwitchToSection(TAI->SectionForGlobal(F));
585 switch (F->getLinkage()) {
586 default: assert(0 && "Unknown linkage type!");
587 case Function::PrivateLinkage:
588 case Function::InternalLinkage: // Symbols default to internal.
590 case Function::ExternalLinkage:
591 O << "\t.global\t" << CurrentFnName << '\n'
592 << "\t.type\t" << CurrentFnName << ", @function\n";
594 case Function::WeakLinkage:
595 case Function::LinkOnceLinkage:
596 O << "\t.global\t" << CurrentFnName << '\n';
597 O << "\t.weak\t" << CurrentFnName << '\n';
601 printVisibility(CurrentFnName, F->getVisibility());
604 O << CurrentFnName << ":\n";
606 // Emit pre-function debug information.
607 DW->BeginFunction(&MF);
609 // Print out code for the function.
610 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
612 // Print a label for the basic block.
613 if (I != MF.begin()) {
614 printBasicBlockLabel(I, true, true);
617 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
619 // Print the assembly for the instruction.
620 printMachineInstruction(II);
624 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
626 // Print out jump tables referenced by the function.
627 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
629 SwitchToSection(TAI->SectionForGlobal(F));
631 // Emit post-function debug information.
632 DW->EndFunction(&MF);
636 // We didn't modify anything.
640 bool PPCLinuxAsmPrinter::doInitialization(Module &M) {
641 bool Result = AsmPrinter::doInitialization(M);
643 // Emit initial debug information.
644 MMI = getAnalysisToUpdate<MachineModuleInfo>();
646 DW = getAnalysisToUpdate<DwarfWriter>();
647 assert(DW && "DwarfWriter is not available");
648 DW->BeginModule(&M, MMI, O, this, TAI);
650 // GNU as handles section names wrapped in quotes
651 Mang->setUseQuotes(true);
653 SwitchToSection(TAI->getTextSection());
658 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
659 /// Don't print things like \n or \0.
660 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
661 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
667 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
668 const TargetData *TD = TM.getTargetData();
670 if (!GVar->hasInitializer())
671 return; // External global require no code
673 // Check to see if this is a special global used by LLVM, if so, emit it.
674 if (EmitSpecialLLVMGlobal(GVar))
677 std::string name = Mang->getValueName(GVar);
679 printVisibility(name, GVar->getVisibility());
681 Constant *C = GVar->getInitializer();
682 const Type *Type = C->getType();
683 unsigned Size = TD->getTypePaddedSize(Type);
684 unsigned Align = TD->getPreferredAlignmentLog(GVar);
686 SwitchToSection(TAI->SectionForGlobal(GVar));
688 if (C->isNullValue() && /* FIXME: Verify correct */
689 !GVar->hasSection() &&
690 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
691 GVar->mayBeOverridden())) {
692 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
694 if (GVar->hasExternalLinkage()) {
695 O << "\t.global " << name << '\n';
696 O << "\t.type " << name << ", @object\n";
698 O << "\t.zero " << Size << '\n';
699 } else if (GVar->hasLocalLinkage()) {
700 O << TAI->getLCOMMDirective() << name << ',' << Size;
702 O << ".comm " << name << ',' << Size;
704 O << "\t\t" << TAI->getCommentString() << " '";
705 PrintUnmangledNameSafely(GVar, O);
710 switch (GVar->getLinkage()) {
711 case GlobalValue::LinkOnceLinkage:
712 case GlobalValue::WeakLinkage:
713 case GlobalValue::CommonLinkage:
714 O << "\t.global " << name << '\n'
715 << "\t.type " << name << ", @object\n"
716 << "\t.weak " << name << '\n';
718 case GlobalValue::AppendingLinkage:
719 // FIXME: appending linkage variables should go into a section of
720 // their name or something. For now, just emit them as external.
721 case GlobalValue::ExternalLinkage:
722 // If external or appending, declare as a global symbol
723 O << "\t.global " << name << '\n'
724 << "\t.type " << name << ", @object\n";
726 case GlobalValue::InternalLinkage:
727 case GlobalValue::PrivateLinkage:
730 cerr << "Unknown linkage type!";
734 EmitAlignment(Align, GVar);
735 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
736 PrintUnmangledNameSafely(GVar, O);
739 // If the initializer is a extern weak symbol, remember to emit the weak
741 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
742 if (GV->hasExternalWeakLinkage())
743 ExtWeakSymbols.insert(GV);
745 EmitGlobalConstant(C);
749 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
750 // Print out module-level global variables here.
751 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
753 printModuleLevelGV(I);
757 // Emit initial debug information.
760 return AsmPrinter::doFinalization(M);
763 /// runOnMachineFunction - This uses the printMachineInstruction()
764 /// method to print assembly for each instruction.
766 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
767 SetupMachineFunction(MF);
770 // Print out constants referenced by the function
771 EmitConstantPool(MF.getConstantPool());
773 // Print out labels for the function.
774 const Function *F = MF.getFunction();
775 SwitchToSection(TAI->SectionForGlobal(F));
777 switch (F->getLinkage()) {
778 default: assert(0 && "Unknown linkage type!");
779 case Function::InternalLinkage: // Symbols default to internal.
781 case Function::ExternalLinkage:
782 O << "\t.globl\t" << CurrentFnName << '\n';
784 case Function::WeakLinkage:
785 case Function::LinkOnceLinkage:
786 O << "\t.globl\t" << CurrentFnName << '\n';
787 O << "\t.weak_definition\t" << CurrentFnName << '\n';
791 printVisibility(CurrentFnName, F->getVisibility());
793 EmitAlignment(F->hasFnAttr(Attribute::OptimizeForSize) ? 2 : 4, F);
794 O << CurrentFnName << ":\n";
796 // Emit pre-function debug information.
797 DW->BeginFunction(&MF);
799 // If the function is empty, then we need to emit *something*. Otherwise, the
800 // function's label might be associated with something that it wasn't meant to
801 // be associated with. We emit a noop in this situation.
802 MachineFunction::iterator I = MF.begin();
804 if (++I == MF.end() && MF.front().empty())
807 // Print out code for the function.
808 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
810 // Print a label for the basic block.
811 if (I != MF.begin()) {
812 printBasicBlockLabel(I, true, true);
815 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
817 // Print the assembly for the instruction.
818 printMachineInstruction(II);
822 // Print out jump tables referenced by the function.
823 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
825 // Emit post-function debug information.
826 DW->EndFunction(&MF);
828 // We didn't modify anything.
833 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
834 static const char *const CPUDirectives[] = {
846 unsigned Directive = Subtarget.getDarwinDirective();
847 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
848 Directive = PPC::DIR_970;
849 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
850 Directive = PPC::DIR_7400;
851 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
852 Directive = PPC::DIR_64;
853 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
854 O << "\t.machine " << CPUDirectives[Directive] << '\n';
856 bool Result = AsmPrinter::doInitialization(M);
858 // Emit initial debug information.
859 // We need this for Personality functions.
860 // AsmPrinter::doInitialization should have done this analysis.
861 MMI = getAnalysisToUpdate<MachineModuleInfo>();
863 DW = getAnalysisToUpdate<DwarfWriter>();
864 assert(DW && "DwarfWriter is not available");
865 DW->BeginModule(&M, MMI, O, this, TAI);
867 // Darwin wants symbols to be quoted if they have complex names.
868 Mang->setUseQuotes(true);
870 // Prime text sections so they are adjacent. This reduces the likelihood a
871 // large data or debug section causes a branch to exceed 16M limit.
872 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
873 "pure_instructions");
874 if (TM.getRelocationModel() == Reloc::PIC_) {
875 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
876 "pure_instructions,32");
877 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
878 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
879 "pure_instructions,16");
881 SwitchToSection(TAI->getTextSection());
886 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
887 const TargetData *TD = TM.getTargetData();
889 if (!GVar->hasInitializer())
890 return; // External global require no code
892 // Check to see if this is a special global used by LLVM, if so, emit it.
893 if (EmitSpecialLLVMGlobal(GVar)) {
894 if (TM.getRelocationModel() == Reloc::Static) {
895 if (GVar->getName() == "llvm.global_ctors")
896 O << ".reference .constructors_used\n";
897 else if (GVar->getName() == "llvm.global_dtors")
898 O << ".reference .destructors_used\n";
903 std::string name = Mang->getValueName(GVar);
905 printVisibility(name, GVar->getVisibility());
907 Constant *C = GVar->getInitializer();
908 const Type *Type = C->getType();
909 unsigned Size = TD->getTypePaddedSize(Type);
910 unsigned Align = TD->getPreferredAlignmentLog(GVar);
912 SwitchToSection(TAI->SectionForGlobal(GVar));
914 if (C->isNullValue() && /* FIXME: Verify correct */
915 !GVar->hasSection() &&
916 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
917 GVar->mayBeOverridden())) {
918 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
920 if (GVar->hasExternalLinkage()) {
921 O << "\t.globl " << name << '\n';
922 O << "\t.zerofill __DATA, __common, " << name << ", "
923 << Size << ", " << Align;
924 } else if (GVar->hasLocalLinkage()) {
925 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
926 } else if (!GVar->hasCommonLinkage()) {
927 O << "\t.globl " << name << '\n'
928 << TAI->getWeakDefDirective() << name << '\n';
929 EmitAlignment(Align, GVar);
930 O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
931 PrintUnmangledNameSafely(GVar, O);
933 EmitGlobalConstant(C);
936 O << ".comm " << name << ',' << Size;
937 // Darwin 9 and above support aligned common data.
938 if (Subtarget.isDarwin9())
941 O << "\t\t" << TAI->getCommentString() << " '";
942 PrintUnmangledNameSafely(GVar, O);
947 switch (GVar->getLinkage()) {
948 case GlobalValue::LinkOnceLinkage:
949 case GlobalValue::WeakLinkage:
950 case GlobalValue::CommonLinkage:
951 O << "\t.globl " << name << '\n'
952 << "\t.weak_definition " << name << '\n';
954 case GlobalValue::AppendingLinkage:
955 // FIXME: appending linkage variables should go into a section of
956 // their name or something. For now, just emit them as external.
957 case GlobalValue::ExternalLinkage:
958 // If external or appending, declare as a global symbol
959 O << "\t.globl " << name << '\n';
961 case GlobalValue::InternalLinkage:
964 cerr << "Unknown linkage type!";
968 EmitAlignment(Align, GVar);
969 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
970 PrintUnmangledNameSafely(GVar, O);
973 // If the initializer is a extern weak symbol, remember to emit the weak
975 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
976 if (GV->hasExternalWeakLinkage())
977 ExtWeakSymbols.insert(GV);
979 EmitGlobalConstant(C);
983 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
984 const TargetData *TD = TM.getTargetData();
986 // Print out module-level global variables here.
987 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
989 printModuleLevelGV(I);
991 bool isPPC64 = TD->getPointerSizeInBits() == 64;
993 // Output stubs for dynamically-linked functions
994 if (TM.getRelocationModel() == Reloc::PIC_) {
995 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
997 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
998 "pure_instructions,32");
1000 const char *p = i->getKeyData();
1001 bool hasQuote = p[0]=='\"';
1002 printSuffixedName(p, "$stub");
1004 O << "\t.indirect_symbol " << p << '\n';
1006 O << "\tbcl 20,31,";
1008 O << "\"L0$" << &p[1];
1013 O << "\"L0$" << &p[1];
1017 O << "\tmflr r11\n";
1018 O << "\taddis r11,r11,ha16(";
1019 printSuffixedName(p, "$lazy_ptr");
1022 O << "\"L0$" << &p[1];
1028 O << "\tldu r12,lo16(";
1030 O << "\tlwzu r12,lo16(";
1031 printSuffixedName(p, "$lazy_ptr");
1034 O << "\"L0$" << &p[1];
1038 O << "\tmtctr r12\n";
1040 SwitchToDataSection(".lazy_symbol_pointer");
1041 printSuffixedName(p, "$lazy_ptr");
1043 O << "\t.indirect_symbol " << p << '\n';
1045 O << "\t.quad dyld_stub_binding_helper\n";
1047 O << "\t.long dyld_stub_binding_helper\n";
1050 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1052 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1053 "pure_instructions,16");
1055 const char *p = i->getKeyData();
1056 printSuffixedName(p, "$stub");
1058 O << "\t.indirect_symbol " << p << '\n';
1059 O << "\tlis r11,ha16(";
1060 printSuffixedName(p, "$lazy_ptr");
1063 O << "\tldu r12,lo16(";
1065 O << "\tlwzu r12,lo16(";
1066 printSuffixedName(p, "$lazy_ptr");
1068 O << "\tmtctr r12\n";
1070 SwitchToDataSection(".lazy_symbol_pointer");
1071 printSuffixedName(p, "$lazy_ptr");
1073 O << "\t.indirect_symbol " << p << '\n';
1075 O << "\t.quad dyld_stub_binding_helper\n";
1077 O << "\t.long dyld_stub_binding_helper\n";
1083 if (TAI->doesSupportExceptionHandling() && MMI) {
1084 // Add the (possibly multiple) personalities to the set of global values.
1085 // Only referenced functions get into the Personalities list.
1086 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1088 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1089 E = Personalities.end(); I != E; ++I)
1090 if (*I) GVStubs.insert("_" + (*I)->getName());
1093 // Output stubs for external and common global variables.
1094 if (!GVStubs.empty()) {
1095 SwitchToDataSection(".non_lazy_symbol_pointer");
1096 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1098 std::string p = i->getKeyData();
1099 printSuffixedName(p, "$non_lazy_ptr");
1101 O << "\t.indirect_symbol " << p << '\n';
1103 O << "\t.quad\t0\n";
1105 O << "\t.long\t0\n";
1109 if (!HiddenGVStubs.empty()) {
1110 SwitchToSection(TAI->getDataSection());
1111 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1113 std::string p = i->getKeyData();
1114 EmitAlignment(isPPC64 ? 3 : 2);
1115 printSuffixedName(p, "$non_lazy_ptr");
1126 // Emit initial debug information.
1129 // Funny Darwin hack: This flag tells the linker that no global symbols
1130 // contain code that falls through to other global symbols (e.g. the obvious
1131 // implementation of multiple entry points). If this doesn't occur, the
1132 // linker can safely perform dead code stripping. Since LLVM never generates
1133 // code that does this, it is always safe to set.
1134 O << "\t.subsections_via_symbols\n";
1136 return AsmPrinter::doFinalization(M);
1141 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1142 /// for a MachineFunction to the given output stream, in a format that the
1143 /// Darwin assembler can deal with.
1145 FunctionPass *llvm::createPPCAsmPrinterPass(raw_ostream &o,
1146 PPCTargetMachine &tm) {
1147 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1149 if (Subtarget->isDarwin()) {
1150 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1152 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1157 static struct Register {
1159 PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);
1164 extern "C" int PowerPCAsmPrinterForceLink;
1165 int PowerPCAsmPrinterForceLink = 0;