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/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegistry.h"
44 #include "llvm/Support/Mangler.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
59 class PPCAsmPrinter : public AsmPrinter {
62 MCSymbol *Stub, *LazyPtr, *AnonSymbol;
65 Stub = LazyPtr = AnonSymbol = 0;
68 void Init(const GlobalValue *GV, AsmPrinter *Printer) {
69 // Already initialized.
70 if (Stub != 0) return;
73 Stub = Printer->GetPrivateGlobalValueSymbolStub(GV, "$stub");
74 LazyPtr = Printer->GetPrivateGlobalValueSymbolStub(GV, "$lazy_ptr");
75 AnonSymbol = Printer->GetPrivateGlobalValueSymbolStub(GV, "$stub$tmp");
78 void Init(StringRef GVName, Mangler *Mang, MCContext &Ctx) {
79 assert(!GVName.empty() && "external symbol name shouldn't be empty");
80 if (Stub != 0) return; // Already initialized.
81 // Get the names for the external symbol name.
82 SmallString<128> TmpStr;
83 Mang->getNameWithPrefix(TmpStr, GVName, Mangler::Private);
85 Stub = Ctx.GetOrCreateSymbol(TmpStr.str());
86 TmpStr.erase(TmpStr.end()-5, TmpStr.end()); // Remove $stub
88 TmpStr += "$lazy_ptr";
89 LazyPtr = Ctx.GetOrCreateSymbol(TmpStr.str());
90 TmpStr.erase(TmpStr.end()-9, TmpStr.end()); // Remove $lazy_ptr
92 TmpStr += "$stub$tmp";
93 AnonSymbol = Ctx.GetOrCreateSymbol(TmpStr.str());
97 DenseMap<const MCSymbol*, FnStubInfo> FnStubs;
98 DenseMap<const MCSymbol*, const MCSymbol*> GVStubs, HiddenGVStubs, TOC;
99 const PPCSubtarget &Subtarget;
102 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
103 const MCAsmInfo *T, bool V)
104 : AsmPrinter(O, TM, T, V),
105 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
107 virtual const char *getPassName() const {
108 return "PowerPC Assembly Printer";
111 PPCTargetMachine &getTM() {
112 return static_cast<PPCTargetMachine&>(TM);
115 unsigned enumRegToMachineReg(unsigned enumReg) {
117 default: llvm_unreachable("Unhandled register!");
118 case PPC::CR0: return 0;
119 case PPC::CR1: return 1;
120 case PPC::CR2: return 2;
121 case PPC::CR3: return 3;
122 case PPC::CR4: return 4;
123 case PPC::CR5: return 5;
124 case PPC::CR6: return 6;
125 case PPC::CR7: return 7;
130 /// printInstruction - This method is automatically generated by tablegen
131 /// from the instruction set description. This method returns true if the
132 /// machine instruction was sufficiently described to print it, otherwise it
134 void printInstruction(const MachineInstr *MI);
135 static const char *getRegisterName(unsigned RegNo);
138 void printMachineInstruction(const MachineInstr *MI);
139 void printOp(const MachineOperand &MO);
141 /// stripRegisterPrefix - This method strips the character prefix from a
142 /// register name so that only the number is left. Used by for linux asm.
143 const char *stripRegisterPrefix(const char *RegName) {
144 switch (RegName[0]) {
147 case 'v': return RegName + 1;
148 case 'c': if (RegName[1] == 'r') return RegName + 2;
154 /// printRegister - Print register according to target requirements.
156 void printRegister(const MachineOperand &MO, bool R0AsZero) {
157 unsigned RegNo = MO.getReg();
158 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
160 // If we should use 0 for R0.
161 if (R0AsZero && RegNo == PPC::R0) {
166 const char *RegName = getRegisterName(RegNo);
167 // Linux assembler (Others?) does not take register mnemonics.
168 // FIXME - What about special registers used in mfspr/mtspr?
169 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
173 void printOperand(const MachineInstr *MI, unsigned OpNo) {
174 const MachineOperand &MO = MI->getOperand(OpNo);
176 printRegister(MO, false);
177 } else if (MO.isImm()) {
184 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
185 unsigned AsmVariant, const char *ExtraCode);
186 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
187 unsigned AsmVariant, const char *ExtraCode);
190 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
191 char value = MI->getOperand(OpNo).getImm();
192 value = (value << (32-5)) >> (32-5);
195 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
196 unsigned char value = MI->getOperand(OpNo).getImm();
197 assert(value <= 31 && "Invalid u5imm argument!");
198 O << (unsigned int)value;
200 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
201 unsigned char value = MI->getOperand(OpNo).getImm();
202 assert(value <= 63 && "Invalid u6imm argument!");
203 O << (unsigned int)value;
205 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
206 O << (short)MI->getOperand(OpNo).getImm();
208 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
209 O << (unsigned short)MI->getOperand(OpNo).getImm();
211 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
212 if (MI->getOperand(OpNo).isImm()) {
213 O << (short)(MI->getOperand(OpNo).getImm()*4);
216 printOp(MI->getOperand(OpNo));
217 if (TM.getRelocationModel() == Reloc::PIC_)
218 O << "-\"L" << getFunctionNumber() << "$pb\")";
223 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
224 // Branches can take an immediate operand. This is used by the branch
225 // selection pass to print $+8, an eight byte displacement from the PC.
226 if (MI->getOperand(OpNo).isImm()) {
227 O << "$+" << MI->getOperand(OpNo).getImm()*4;
229 printOp(MI->getOperand(OpNo));
232 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
233 const MachineOperand &MO = MI->getOperand(OpNo);
234 if (TM.getRelocationModel() != Reloc::Static) {
235 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
236 GlobalValue *GV = MO.getGlobal();
237 if (GV->isDeclaration() || GV->isWeakForLinker()) {
238 // Dynamically-resolved functions need a stub for the function.
239 FnStubInfo &FnInfo = FnStubs[GetGlobalValueSymbol(GV)];
240 FnInfo.Init(GV, this);
241 FnInfo.Stub->print(O, MAI);
245 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
247 FnStubs[GetExternalSymbolSymbol(MO.getSymbolName())];
248 FnInfo.Init(MO.getSymbolName(), Mang, OutContext);
249 FnInfo.Stub->print(O, MAI);
254 printOp(MI->getOperand(OpNo));
256 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
257 O << (int)MI->getOperand(OpNo).getImm()*4;
259 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
260 O << "\"L" << getFunctionNumber() << "$pb\"\n";
261 O << "\"L" << getFunctionNumber() << "$pb\":";
263 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
264 if (MI->getOperand(OpNo).isImm()) {
265 printS16ImmOperand(MI, OpNo);
267 if (Subtarget.isDarwin()) O << "ha16(";
268 printOp(MI->getOperand(OpNo));
269 if (TM.getRelocationModel() == Reloc::PIC_)
270 O << "-\"L" << getFunctionNumber() << "$pb\"";
271 if (Subtarget.isDarwin())
277 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
278 if (MI->getOperand(OpNo).isImm()) {
279 printS16ImmOperand(MI, OpNo);
281 if (Subtarget.isDarwin()) O << "lo16(";
282 printOp(MI->getOperand(OpNo));
283 if (TM.getRelocationModel() == Reloc::PIC_)
284 O << "-\"L" << getFunctionNumber() << "$pb\"";
285 if (Subtarget.isDarwin())
291 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
292 unsigned CCReg = MI->getOperand(OpNo).getReg();
293 unsigned RegNo = enumRegToMachineReg(CCReg);
294 O << (0x80 >> RegNo);
296 // The new addressing mode printers.
297 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
298 printSymbolLo(MI, OpNo);
300 if (MI->getOperand(OpNo+1).isReg() &&
301 MI->getOperand(OpNo+1).getReg() == PPC::R0)
304 printOperand(MI, OpNo+1);
307 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
308 if (MI->getOperand(OpNo).isImm())
309 printS16X4ImmOperand(MI, OpNo);
311 printSymbolLo(MI, OpNo);
313 if (MI->getOperand(OpNo+1).isReg() &&
314 MI->getOperand(OpNo+1).getReg() == PPC::R0)
317 printOperand(MI, OpNo+1);
321 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
322 // When used as the base register, r0 reads constant zero rather than
323 // the value contained in the register. For this reason, the darwin
324 // assembler requires that we print r0 as 0 (no r) when used as the base.
325 const MachineOperand &MO = MI->getOperand(OpNo);
326 printRegister(MO, true);
328 printOperand(MI, OpNo+1);
331 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
332 const MachineOperand &MO = MI->getOperand(OpNo);
334 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
336 const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
338 // Map symbol -> label of TOC entry.
339 const MCSymbol *&TOCEntry = TOC[Sym];
341 TOCEntry = OutContext.
342 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
345 TOCEntry->print(O, MAI);
349 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
350 const char *Modifier);
352 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
355 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
356 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
358 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
359 const MCAsmInfo *T, bool V)
360 : PPCAsmPrinter(O, TM, T, V){}
362 virtual const char *getPassName() const {
363 return "Linux PPC Assembly Printer";
366 bool runOnMachineFunction(MachineFunction &F);
367 bool doFinalization(Module &M);
369 void getAnalysisUsage(AnalysisUsage &AU) const {
370 AU.setPreservesAll();
371 AU.addRequired<MachineModuleInfo>();
372 AU.addRequired<DwarfWriter>();
373 PPCAsmPrinter::getAnalysisUsage(AU);
376 void PrintGlobalVariable(const GlobalVariable *GVar);
379 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
381 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
382 formatted_raw_ostream &OS;
384 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
385 const MCAsmInfo *T, bool V)
386 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
388 virtual const char *getPassName() const {
389 return "Darwin PPC Assembly Printer";
392 bool runOnMachineFunction(MachineFunction &F);
393 bool doFinalization(Module &M);
394 void EmitStartOfAsmFile(Module &M);
396 void getAnalysisUsage(AnalysisUsage &AU) const {
397 AU.setPreservesAll();
398 AU.addRequired<MachineModuleInfo>();
399 AU.addRequired<DwarfWriter>();
400 PPCAsmPrinter::getAnalysisUsage(AU);
403 void PrintGlobalVariable(const GlobalVariable *GVar);
405 } // end of anonymous namespace
407 // Include the auto-generated portion of the assembly writer
408 #include "PPCGenAsmWriter.inc"
410 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
411 switch (MO.getType()) {
412 case MachineOperand::MO_Immediate:
413 llvm_unreachable("printOp() does not handle immediate values");
415 case MachineOperand::MO_MachineBasicBlock:
416 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
418 case MachineOperand::MO_JumpTableIndex:
419 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
420 << '_' << MO.getIndex();
421 // FIXME: PIC relocation model
423 case MachineOperand::MO_ConstantPoolIndex:
424 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
425 << '_' << MO.getIndex();
427 case MachineOperand::MO_BlockAddress:
428 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
430 case MachineOperand::MO_ExternalSymbol: {
431 // Computing the address of an external symbol, not calling it.
432 const MCSymbol *SymName = GetExternalSymbolSymbol(MO.getSymbolName());
433 if (TM.getRelocationModel() == Reloc::Static) {
434 SymName->print(O, MAI);
437 const MCSymbol *NLPSym =
438 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
439 MO.getSymbolName()+"$non_lazy_ptr");
440 GVStubs[SymName] = NLPSym;
441 NLPSym->print(O, MAI);
444 case MachineOperand::MO_GlobalAddress: {
445 // Computing the address of a global symbol, not calling it.
446 GlobalValue *GV = MO.getGlobal();
447 MCSymbol *SymToPrint;
449 // External or weakly linked global variables need non-lazily-resolved stubs
450 if (TM.getRelocationModel() != Reloc::Static &&
451 (GV->isDeclaration() || GV->isWeakForLinker())) {
452 if (!GV->hasHiddenVisibility()) {
453 SymToPrint = GetPrivateGlobalValueSymbolStub(GV, "$non_lazy_ptr");
454 GVStubs[GetGlobalValueSymbol(GV)] = SymToPrint;
455 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
456 GV->hasAvailableExternallyLinkage()) {
457 SymToPrint = GetPrivateGlobalValueSymbolStub(GV, "$non_lazy_ptr");
458 HiddenGVStubs[GetGlobalValueSymbol(GV)] = SymToPrint;
460 SymToPrint = GetGlobalValueSymbol(GV);
463 SymToPrint = GetGlobalValueSymbol(GV);
466 SymToPrint->print(O, MAI);
468 printOffset(MO.getOffset());
473 O << "<unknown operand type: " << MO.getType() << ">";
478 /// PrintAsmOperand - Print out an operand for an inline asm expression.
480 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
482 const char *ExtraCode) {
483 // Does this asm operand have a single letter operand modifier?
484 if (ExtraCode && ExtraCode[0]) {
485 if (ExtraCode[1] != 0) return true; // Unknown modifier.
487 switch (ExtraCode[0]) {
488 default: return true; // Unknown modifier.
489 case 'c': // Don't print "$" before a global var name or constant.
490 // PPC never has a prefix.
491 printOperand(MI, OpNo);
493 case 'L': // Write second word of DImode reference.
494 // Verify that this operand has two consecutive registers.
495 if (!MI->getOperand(OpNo).isReg() ||
496 OpNo+1 == MI->getNumOperands() ||
497 !MI->getOperand(OpNo+1).isReg())
499 ++OpNo; // Return the high-part.
502 // Write 'i' if an integer constant, otherwise nothing. Used to print
504 if (MI->getOperand(OpNo).isImm())
510 printOperand(MI, OpNo);
514 // At the moment, all inline asm memory operands are a single register.
515 // In any case, the output of this routine should always be just one
516 // assembler operand.
518 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
520 const char *ExtraCode) {
521 if (ExtraCode && ExtraCode[0])
522 return true; // Unknown modifier.
523 assert (MI->getOperand(OpNo).isReg());
525 printOperand(MI, OpNo);
530 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
531 const char *Modifier) {
532 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
533 unsigned Code = MI->getOperand(OpNo).getImm();
534 if (!strcmp(Modifier, "cc")) {
535 switch ((PPC::Predicate)Code) {
536 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
537 case PPC::PRED_LT: O << "lt"; return;
538 case PPC::PRED_LE: O << "le"; return;
539 case PPC::PRED_EQ: O << "eq"; return;
540 case PPC::PRED_GE: O << "ge"; return;
541 case PPC::PRED_GT: O << "gt"; return;
542 case PPC::PRED_NE: O << "ne"; return;
543 case PPC::PRED_UN: O << "un"; return;
544 case PPC::PRED_NU: O << "nu"; return;
548 assert(!strcmp(Modifier, "reg") &&
549 "Need to specify 'cc' or 'reg' as predicate op modifier!");
550 // Don't print the register for 'always'.
551 if (Code == PPC::PRED_ALWAYS) return;
552 printOperand(MI, OpNo+1);
557 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
558 /// the current output stream.
560 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
563 processDebugLoc(MI, true);
565 // Check for slwi/srwi mnemonics.
566 bool useSubstituteMnemonic = false;
567 if (MI->getOpcode() == PPC::RLWINM) {
568 unsigned char SH = MI->getOperand(2).getImm();
569 unsigned char MB = MI->getOperand(3).getImm();
570 unsigned char ME = MI->getOperand(4).getImm();
571 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
572 O << "\tslwi "; useSubstituteMnemonic = true;
574 if (SH <= 31 && MB == (32-SH) && ME == 31) {
575 O << "\tsrwi "; useSubstituteMnemonic = true;
578 if (useSubstituteMnemonic) {
582 O << ", " << (unsigned int)SH;
584 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
585 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
586 useSubstituteMnemonic = true;
592 } else if (MI->getOpcode() == PPC::RLDICR) {
593 unsigned char SH = MI->getOperand(2).getImm();
594 unsigned char ME = MI->getOperand(3).getImm();
595 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
597 useSubstituteMnemonic = true;
602 O << ", " << (unsigned int)SH;
606 if (!useSubstituteMnemonic)
607 printInstruction(MI);
613 processDebugLoc(MI, false);
616 /// runOnMachineFunction - This uses the printMachineInstruction()
617 /// method to print assembly for each instruction.
619 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
622 SetupMachineFunction(MF);
625 // Print out constants referenced by the function
626 EmitConstantPool(MF.getConstantPool());
628 // Print out labels for the function.
629 const Function *F = MF.getFunction();
630 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
632 switch (F->getLinkage()) {
633 default: llvm_unreachable("Unknown linkage type!");
634 case Function::PrivateLinkage:
635 case Function::InternalLinkage: // Symbols default to internal.
637 case Function::ExternalLinkage:
639 CurrentFnSym->print(O, MAI);
640 O << '\n' << "\t.type\t";
641 CurrentFnSym->print(O, MAI);
642 O << ", @function\n";
644 case Function::LinkerPrivateLinkage:
645 case Function::WeakAnyLinkage:
646 case Function::WeakODRLinkage:
647 case Function::LinkOnceAnyLinkage:
648 case Function::LinkOnceODRLinkage:
650 CurrentFnSym->print(O, MAI);
653 CurrentFnSym->print(O, MAI);
658 printVisibility(CurrentFnSym, F->getVisibility());
660 EmitAlignment(MF.getAlignment(), F);
662 if (Subtarget.isPPC64()) {
663 // Emit an official procedure descriptor.
664 // FIXME 64-bit SVR4: Use MCSection here!
665 O << "\t.section\t\".opd\",\"aw\"\n";
667 CurrentFnSym->print(O, MAI);
670 CurrentFnSym->print(O, MAI);
671 O << ",.TOC.@tocbase\n";
672 O << "\t.previous\n";
674 CurrentFnSym->print(O, MAI);
677 CurrentFnSym->print(O, MAI);
681 // Emit pre-function debug information.
682 DW->BeginFunction(&MF);
684 // Print out code for the function.
685 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
687 // Print a label for the basic block.
688 if (I != MF.begin()) {
689 EmitBasicBlockStart(I);
691 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
693 // Print the assembly for the instruction.
694 printMachineInstruction(II);
699 CurrentFnSym->print(O, MAI);
701 CurrentFnSym->print(O, MAI);
704 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
706 // Emit post-function debug information.
707 DW->EndFunction(&MF);
709 // Print out jump tables referenced by the function.
710 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
712 // We didn't modify anything.
716 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
717 const TargetData *TD = TM.getTargetData();
719 if (!GVar->hasInitializer())
720 return; // External global require no code
722 // Check to see if this is a special global used by LLVM, if so, emit it.
723 if (EmitSpecialLLVMGlobal(GVar))
726 MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
728 printVisibility(GVarSym, GVar->getVisibility());
730 Constant *C = GVar->getInitializer();
731 const Type *Type = C->getType();
732 unsigned Size = TD->getTypeAllocSize(Type);
733 unsigned Align = TD->getPreferredAlignmentLog(GVar);
735 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
738 if (C->isNullValue() && /* FIXME: Verify correct */
739 !GVar->hasSection() &&
740 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
741 GVar->isWeakForLinker())) {
742 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
744 if (GVar->hasExternalLinkage()) {
746 GVarSym->print(O, MAI);
749 GVarSym->print(O, MAI);
751 GVarSym->print(O, MAI);
753 O << "\t.zero " << Size << '\n';
754 } else if (GVar->hasLocalLinkage()) {
755 O << MAI->getLCOMMDirective();
756 GVarSym->print(O, MAI);
760 GVarSym->print(O, MAI);
764 O << "\t\t" << MAI->getCommentString() << " '";
765 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
772 switch (GVar->getLinkage()) {
773 case GlobalValue::LinkOnceAnyLinkage:
774 case GlobalValue::LinkOnceODRLinkage:
775 case GlobalValue::WeakAnyLinkage:
776 case GlobalValue::WeakODRLinkage:
777 case GlobalValue::CommonLinkage:
778 case GlobalValue::LinkerPrivateLinkage:
780 GVarSym->print(O, MAI);
782 GVarSym->print(O, MAI);
783 O << ", @object\n\t.weak ";
784 GVarSym->print(O, MAI);
787 case GlobalValue::AppendingLinkage:
788 // FIXME: appending linkage variables should go into a section of
789 // their name or something. For now, just emit them as external.
790 case GlobalValue::ExternalLinkage:
791 // If external or appending, declare as a global symbol
793 GVarSym->print(O, MAI);
795 GVarSym->print(O, MAI);
798 case GlobalValue::InternalLinkage:
799 case GlobalValue::PrivateLinkage:
802 llvm_unreachable("Unknown linkage type!");
805 EmitAlignment(Align, GVar);
806 GVarSym->print(O, MAI);
809 O << "\t\t\t\t" << MAI->getCommentString() << " '";
810 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
815 EmitGlobalConstant(C);
819 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
820 const TargetData *TD = TM.getTargetData();
822 bool isPPC64 = TD->getPointerSizeInBits() == 64;
824 if (isPPC64 && !TOC.empty()) {
825 // FIXME 64-bit SVR4: Use MCSection here?
826 O << "\t.section\t\".toc\",\"aw\"\n";
828 // FIXME: This is nondeterminstic!
829 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
830 E = TOC.end(); I != E; ++I) {
831 I->second->print(O, MAI);
834 I->first->print(O, MAI);
836 I->first->print(O, MAI);
841 return AsmPrinter::doFinalization(M);
844 /// runOnMachineFunction - This uses the printMachineInstruction()
845 /// method to print assembly for each instruction.
847 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
850 SetupMachineFunction(MF);
853 // Print out constants referenced by the function
854 EmitConstantPool(MF.getConstantPool());
856 // Print out labels for the function.
857 const Function *F = MF.getFunction();
858 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
860 switch (F->getLinkage()) {
861 default: llvm_unreachable("Unknown linkage type!");
862 case Function::PrivateLinkage:
863 case Function::InternalLinkage: // Symbols default to internal.
865 case Function::ExternalLinkage:
867 CurrentFnSym->print(O, MAI);
870 case Function::WeakAnyLinkage:
871 case Function::WeakODRLinkage:
872 case Function::LinkOnceAnyLinkage:
873 case Function::LinkOnceODRLinkage:
874 case Function::LinkerPrivateLinkage:
876 CurrentFnSym->print(O, MAI);
878 O << "\t.weak_definition\t";
879 CurrentFnSym->print(O, MAI);
884 printVisibility(CurrentFnSym, F->getVisibility());
886 EmitAlignment(MF.getAlignment(), F);
887 CurrentFnSym->print(O, MAI);
890 // Emit pre-function debug information.
891 DW->BeginFunction(&MF);
893 // If the function is empty, then we need to emit *something*. Otherwise, the
894 // function's label might be associated with something that it wasn't meant to
895 // be associated with. We emit a noop in this situation.
896 MachineFunction::iterator I = MF.begin();
898 if (++I == MF.end() && MF.front().empty())
901 // Print out code for the function.
902 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
904 // Print a label for the basic block.
905 if (I != MF.begin()) {
906 EmitBasicBlockStart(I);
908 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
910 // Print the assembly for the instruction.
911 printMachineInstruction(II);
915 // Emit post-function debug information.
916 DW->EndFunction(&MF);
918 // Print out jump tables referenced by the function.
919 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
921 // We didn't modify anything.
926 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
927 static const char *const CPUDirectives[] = {
939 unsigned Directive = Subtarget.getDarwinDirective();
940 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
941 Directive = PPC::DIR_970;
942 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
943 Directive = PPC::DIR_7400;
944 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
945 Directive = PPC::DIR_64;
946 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
947 O << "\t.machine " << CPUDirectives[Directive] << '\n';
949 // Prime text sections so they are adjacent. This reduces the likelihood a
950 // large data or debug section causes a branch to exceed 16M limit.
951 TargetLoweringObjectFileMachO &TLOFMacho =
952 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
953 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
954 if (TM.getRelocationModel() == Reloc::PIC_) {
955 OutStreamer.SwitchSection(
956 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
957 MCSectionMachO::S_SYMBOL_STUBS |
958 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
959 32, SectionKind::getText()));
960 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
961 OutStreamer.SwitchSection(
962 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
963 MCSectionMachO::S_SYMBOL_STUBS |
964 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
965 16, SectionKind::getText()));
967 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
970 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
971 const TargetData *TD = TM.getTargetData();
973 if (!GVar->hasInitializer())
974 return; // External global require no code
976 // Check to see if this is a special global used by LLVM, if so, emit it.
977 if (EmitSpecialLLVMGlobal(GVar)) {
978 if (TM.getRelocationModel() == Reloc::Static) {
979 if (GVar->getName() == "llvm.global_ctors")
980 O << ".reference .constructors_used\n";
981 else if (GVar->getName() == "llvm.global_dtors")
982 O << ".reference .destructors_used\n";
987 MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
988 printVisibility(GVarSym, GVar->getVisibility());
990 Constant *C = GVar->getInitializer();
991 const Type *Type = C->getType();
992 unsigned Size = TD->getTypeAllocSize(Type);
993 unsigned Align = TD->getPreferredAlignmentLog(GVar);
995 const MCSection *TheSection =
996 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
997 OutStreamer.SwitchSection(TheSection);
999 /// FIXME: Drive this off the section!
1000 if (C->isNullValue() && /* FIXME: Verify correct */
1001 !GVar->hasSection() &&
1002 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
1003 GVar->isWeakForLinker()) &&
1004 // Don't put things that should go in the cstring section into "comm".
1005 !TheSection->getKind().isMergeableCString()) {
1006 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
1008 if (GVar->hasExternalLinkage()) {
1010 GVarSym->print(O, MAI);
1012 O << "\t.zerofill __DATA, __common, ";
1013 GVarSym->print(O, MAI);
1014 O << ", " << Size << ", " << Align;
1015 } else if (GVar->hasLocalLinkage()) {
1016 O << MAI->getLCOMMDirective();
1017 GVarSym->print(O, MAI);
1018 O << ',' << Size << ',' << Align;
1019 } else if (!GVar->hasCommonLinkage()) {
1021 GVarSym->print(O, MAI);
1022 O << '\n' << MAI->getWeakDefDirective();
1023 GVarSym->print(O, MAI);
1025 EmitAlignment(Align, GVar);
1026 GVarSym->print(O, MAI);
1029 O << "\t\t\t\t" << MAI->getCommentString() << " ";
1030 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1033 EmitGlobalConstant(C);
1037 GVarSym->print(O, MAI);
1039 // Darwin 9 and above support aligned common data.
1040 if (Subtarget.isDarwin9())
1044 O << "\t\t" << MAI->getCommentString() << " '";
1045 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1052 switch (GVar->getLinkage()) {
1053 case GlobalValue::LinkOnceAnyLinkage:
1054 case GlobalValue::LinkOnceODRLinkage:
1055 case GlobalValue::WeakAnyLinkage:
1056 case GlobalValue::WeakODRLinkage:
1057 case GlobalValue::CommonLinkage:
1058 case GlobalValue::LinkerPrivateLinkage:
1060 GVarSym->print(O, MAI);
1061 O << "\n\t.weak_definition ";
1062 GVarSym->print(O, MAI);
1065 case GlobalValue::AppendingLinkage:
1066 // FIXME: appending linkage variables should go into a section of
1067 // their name or something. For now, just emit them as external.
1068 case GlobalValue::ExternalLinkage:
1069 // If external or appending, declare as a global symbol
1071 GVarSym->print(O, MAI);
1074 case GlobalValue::InternalLinkage:
1075 case GlobalValue::PrivateLinkage:
1078 llvm_unreachable("Unknown linkage type!");
1081 EmitAlignment(Align, GVar);
1082 GVarSym->print(O, MAI);
1085 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1086 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1091 EmitGlobalConstant(C);
1095 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1096 const TargetData *TD = TM.getTargetData();
1098 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1100 // Darwin/PPC always uses mach-o.
1101 TargetLoweringObjectFileMachO &TLOFMacho =
1102 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1105 const MCSection *LSPSection = 0;
1106 if (!FnStubs.empty()) // .lazy_symbol_pointer
1107 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1110 // Output stubs for dynamically-linked functions
1111 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1112 const MCSection *StubSection =
1113 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1114 MCSectionMachO::S_SYMBOL_STUBS |
1115 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1116 32, SectionKind::getText());
1117 // FIXME: This is emitting in nondeterminstic order!
1118 for (DenseMap<const MCSymbol*, FnStubInfo>::iterator I =
1119 FnStubs.begin(), E = FnStubs.end(); I != E; ++I) {
1120 OutStreamer.SwitchSection(StubSection);
1122 const FnStubInfo &Info = I->second;
1123 Info.Stub->print(O, MAI);
1125 O << "\t.indirect_symbol ";
1126 I->first->print(O, MAI);
1129 O << "\tbcl 20,31,";
1130 Info.AnonSymbol->print(O, MAI);
1132 Info.AnonSymbol->print(O, MAI);
1134 O << "\tmflr r11\n";
1135 O << "\taddis r11,r11,ha16(";
1136 Info.LazyPtr->print(O, MAI);
1138 Info.AnonSymbol->print(O, MAI);
1141 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1142 Info.LazyPtr->print(O, MAI);
1144 Info.AnonSymbol->print(O, MAI);
1146 O << "\tmtctr r12\n";
1149 OutStreamer.SwitchSection(LSPSection);
1150 Info.LazyPtr->print(O, MAI);
1152 O << "\t.indirect_symbol ";
1153 I->first->print(O, MAI);
1155 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1157 } else if (!FnStubs.empty()) {
1158 const MCSection *StubSection =
1159 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1160 MCSectionMachO::S_SYMBOL_STUBS |
1161 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1162 16, SectionKind::getText());
1164 // FIXME: This is emitting in nondeterminstic order!
1165 for (DenseMap<const MCSymbol*, FnStubInfo>::iterator I = FnStubs.begin(),
1166 E = FnStubs.end(); I != E; ++I) {
1167 OutStreamer.SwitchSection(StubSection);
1169 const FnStubInfo &Info = I->second;
1170 Info.Stub->print(O, MAI);
1172 O << "\t.indirect_symbol ";
1173 I->first->print(O, MAI);
1175 O << "\tlis r11,ha16(";
1176 Info.LazyPtr->print(O, MAI);
1178 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1179 Info.LazyPtr->print(O, MAI);
1181 O << "\tmtctr r12\n";
1183 OutStreamer.SwitchSection(LSPSection);
1184 Info.LazyPtr->print(O, MAI);
1186 O << "\t.indirect_symbol ";
1187 I->first->print(O, MAI);
1189 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1195 if (MAI->doesSupportExceptionHandling() && MMI) {
1196 // Add the (possibly multiple) personalities to the set of global values.
1197 // Only referenced functions get into the Personalities list.
1198 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1199 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1200 E = Personalities.end(); I != E; ++I) {
1202 GVStubs[GetGlobalValueSymbol(*I)] =
1203 GetPrivateGlobalValueSymbolStub(*I, "$non_lazy_ptr");
1207 // Output macho stubs for external and common global variables.
1208 if (!GVStubs.empty()) {
1209 // Switch with ".non_lazy_symbol_pointer" directive.
1210 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1211 EmitAlignment(isPPC64 ? 3 : 2);
1213 // FIXME: This is nondeterminstic.
1214 for (DenseMap<const MCSymbol *, const MCSymbol *>::iterator
1215 I = GVStubs.begin(), E = GVStubs.end(); I != E; ++I) {
1216 I->second->print(O, MAI);
1218 O << "\t.indirect_symbol ";
1219 I->first->print(O, MAI);
1221 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1225 if (!HiddenGVStubs.empty()) {
1226 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1227 EmitAlignment(isPPC64 ? 3 : 2);
1228 // FIXME: This is nondeterminstic.
1229 for (DenseMap<const MCSymbol *, const MCSymbol *>::iterator
1230 I = HiddenGVStubs.begin(), E = HiddenGVStubs.end(); I != E; ++I) {
1231 I->second->print(O, MAI);
1233 O << (isPPC64 ? "\t.quad\t" : "\t.long\t");
1234 I->first->print(O, MAI);
1239 // Funny Darwin hack: This flag tells the linker that no global symbols
1240 // contain code that falls through to other global symbols (e.g. the obvious
1241 // implementation of multiple entry points). If this doesn't occur, the
1242 // linker can safely perform dead code stripping. Since LLVM never generates
1243 // code that does this, it is always safe to set.
1244 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1246 return AsmPrinter::doFinalization(M);
1251 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1252 /// for a MachineFunction to the given output stream, in a format that the
1253 /// Darwin assembler can deal with.
1255 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1257 const MCAsmInfo *tai,
1259 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1261 if (Subtarget->isDarwin())
1262 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1263 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1266 // Force static initialization.
1267 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1268 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1269 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);