1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Support/Mangler.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/MRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/StringExtras.h"
47 STATISTIC(EmittedInsts, "Number of machine instrs printed");
50 struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
51 std::set<std::string> FnStubs, GVStubs;
52 const PPCSubtarget &Subtarget;
54 PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
55 : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
58 virtual const char *getPassName() const {
59 return "PowerPC Assembly Printer";
62 PPCTargetMachine &getTM() {
63 return static_cast<PPCTargetMachine&>(TM);
66 unsigned enumRegToMachineReg(unsigned enumReg) {
68 default: assert(0 && "Unhandled register!"); break;
69 case PPC::CR0: return 0;
70 case PPC::CR1: return 1;
71 case PPC::CR2: return 2;
72 case PPC::CR3: return 3;
73 case PPC::CR4: return 4;
74 case PPC::CR5: return 5;
75 case PPC::CR6: return 6;
76 case PPC::CR7: return 7;
81 /// printInstruction - This method is automatically generated by tablegen
82 /// from the instruction set description. This method returns true if the
83 /// machine instruction was sufficiently described to print it, otherwise it
85 bool printInstruction(const MachineInstr *MI);
87 void printMachineInstruction(const MachineInstr *MI);
88 void printOp(const MachineOperand &MO);
90 /// stripRegisterPrefix - This method strips the character prefix from a
91 /// register name so that only the number is left. Used by for linux asm.
92 const char *stripRegisterPrefix(const char *RegName) {
96 case 'v': return RegName + 1;
97 case 'c': if (RegName[1] == 'r') return RegName + 2;
103 /// printRegister - Print register according to target requirements.
105 void printRegister(const MachineOperand &MO, bool R0AsZero) {
106 unsigned RegNo = MO.getReg();
107 assert(MRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
109 // If we should use 0 for R0.
110 if (R0AsZero && RegNo == PPC::R0) {
115 const char *RegName = TM.getRegisterInfo()->get(RegNo).Name;
116 // Linux assembler (Others?) does not take register mnemonics.
117 // FIXME - What about special registers used in mfspr/mtspr?
118 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
122 void printOperand(const MachineInstr *MI, unsigned OpNo) {
123 const MachineOperand &MO = MI->getOperand(OpNo);
124 if (MO.isRegister()) {
125 printRegister(MO, false);
126 } else if (MO.isImmediate()) {
127 O << MO.getImmedValue();
133 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
134 unsigned AsmVariant, const char *ExtraCode);
135 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
136 unsigned AsmVariant, const char *ExtraCode);
139 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
140 char value = MI->getOperand(OpNo).getImmedValue();
141 value = (value << (32-5)) >> (32-5);
144 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
145 unsigned char value = MI->getOperand(OpNo).getImmedValue();
146 assert(value <= 31 && "Invalid u5imm argument!");
147 O << (unsigned int)value;
149 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
150 unsigned char value = MI->getOperand(OpNo).getImmedValue();
151 assert(value <= 63 && "Invalid u6imm argument!");
152 O << (unsigned int)value;
154 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
155 O << (short)MI->getOperand(OpNo).getImmedValue();
157 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
158 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
160 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
161 if (MI->getOperand(OpNo).isImmediate()) {
162 O << (short)(MI->getOperand(OpNo).getImmedValue()*4);
165 printOp(MI->getOperand(OpNo));
166 if (TM.getRelocationModel() == Reloc::PIC_)
167 O << "-\"L" << getFunctionNumber() << "$pb\")";
172 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
173 // Branches can take an immediate operand. This is used by the branch
174 // selection pass to print $+8, an eight byte displacement from the PC.
175 if (MI->getOperand(OpNo).isImmediate()) {
176 O << "$+" << MI->getOperand(OpNo).getImmedValue()*4;
178 printOp(MI->getOperand(OpNo));
181 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
182 const MachineOperand &MO = MI->getOperand(OpNo);
183 if (TM.getRelocationModel() != Reloc::Static) {
184 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
185 GlobalValue *GV = MO.getGlobal();
186 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
187 GV->hasLinkOnceLinkage()))) {
188 // Dynamically-resolved functions need a stub for the function.
189 std::string Name = Mang->getValueName(GV);
190 FnStubs.insert(Name);
191 O << "L" << Name << "$stub";
192 if (GV->hasExternalWeakLinkage())
193 ExtWeakSymbols.insert(GV);
197 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
198 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
199 FnStubs.insert(Name);
200 O << "L" << Name << "$stub";
205 printOp(MI->getOperand(OpNo));
207 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
208 O << (int)MI->getOperand(OpNo).getImmedValue()*4;
210 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
211 O << "\"L" << getFunctionNumber() << "$pb\"\n";
212 O << "\"L" << getFunctionNumber() << "$pb\":";
214 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
215 if (MI->getOperand(OpNo).isImmediate()) {
216 printS16ImmOperand(MI, OpNo);
218 if (Subtarget.isDarwin()) O << "ha16(";
219 printOp(MI->getOperand(OpNo));
220 if (TM.getRelocationModel() == Reloc::PIC_)
221 O << "-\"L" << getFunctionNumber() << "$pb\"";
222 if (Subtarget.isDarwin())
228 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
229 if (MI->getOperand(OpNo).isImmediate()) {
230 printS16ImmOperand(MI, OpNo);
232 if (Subtarget.isDarwin()) O << "lo16(";
233 printOp(MI->getOperand(OpNo));
234 if (TM.getRelocationModel() == Reloc::PIC_)
235 O << "-\"L" << getFunctionNumber() << "$pb\"";
236 if (Subtarget.isDarwin())
242 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
243 unsigned CCReg = MI->getOperand(OpNo).getReg();
244 unsigned RegNo = enumRegToMachineReg(CCReg);
245 O << (0x80 >> RegNo);
247 // The new addressing mode printers.
248 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
249 printSymbolLo(MI, OpNo);
251 if (MI->getOperand(OpNo+1).isRegister() &&
252 MI->getOperand(OpNo+1).getReg() == PPC::R0)
255 printOperand(MI, OpNo+1);
258 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
259 if (MI->getOperand(OpNo).isImmediate())
260 printS16X4ImmOperand(MI, OpNo);
262 printSymbolLo(MI, OpNo);
264 if (MI->getOperand(OpNo+1).isRegister() &&
265 MI->getOperand(OpNo+1).getReg() == PPC::R0)
268 printOperand(MI, OpNo+1);
272 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
273 // When used as the base register, r0 reads constant zero rather than
274 // the value contained in the register. For this reason, the darwin
275 // assembler requires that we print r0 as 0 (no r) when used as the base.
276 const MachineOperand &MO = MI->getOperand(OpNo);
277 printRegister(MO, true);
279 printOperand(MI, OpNo+1);
282 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
283 const char *Modifier);
285 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
286 virtual bool doFinalization(Module &M) = 0;
288 virtual void EmitExternalGlobal(const GlobalVariable *GV);
291 /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
292 struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
296 LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
297 const TargetAsmInfo *T)
298 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
301 virtual const char *getPassName() const {
302 return "Linux PPC Assembly Printer";
305 bool runOnMachineFunction(MachineFunction &F);
306 bool doInitialization(Module &M);
307 bool doFinalization(Module &M);
309 void getAnalysisUsage(AnalysisUsage &AU) const {
310 AU.setPreservesAll();
311 AU.addRequired<MachineModuleInfo>();
312 PPCAsmPrinter::getAnalysisUsage(AU);
315 /// getSectionForFunction - Return the section that we should emit the
316 /// specified function body into.
317 virtual std::string getSectionForFunction(const Function &F) const;
320 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
322 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
326 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
327 const TargetAsmInfo *T)
328 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
331 virtual const char *getPassName() const {
332 return "Darwin PPC Assembly Printer";
335 bool runOnMachineFunction(MachineFunction &F);
336 bool doInitialization(Module &M);
337 bool doFinalization(Module &M);
339 void getAnalysisUsage(AnalysisUsage &AU) const {
340 AU.setPreservesAll();
341 AU.addRequired<MachineModuleInfo>();
342 PPCAsmPrinter::getAnalysisUsage(AU);
345 /// getSectionForFunction - Return the section that we should emit the
346 /// specified function body into.
347 virtual std::string getSectionForFunction(const Function &F) const;
349 } // end of anonymous namespace
351 // Include the auto-generated portion of the assembly writer
352 #include "PPCGenAsmWriter.inc"
354 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
355 switch (MO.getType()) {
356 case MachineOperand::MO_Immediate:
357 cerr << "printOp() does not handle immediate values\n";
361 case MachineOperand::MO_MachineBasicBlock:
362 printBasicBlockLabel(MO.getMachineBasicBlock());
364 case MachineOperand::MO_JumpTableIndex:
365 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
366 << '_' << MO.getJumpTableIndex();
367 // FIXME: PIC relocation model
369 case MachineOperand::MO_ConstantPoolIndex:
370 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
371 << '_' << MO.getConstantPoolIndex();
373 case MachineOperand::MO_ExternalSymbol:
374 // Computing the address of an external symbol, not calling it.
375 if (TM.getRelocationModel() != Reloc::Static) {
376 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
377 GVStubs.insert(Name);
378 O << "L" << Name << "$non_lazy_ptr";
381 O << TAI->getGlobalPrefix() << MO.getSymbolName();
383 case MachineOperand::MO_GlobalAddress: {
384 // Computing the address of a global symbol, not calling it.
385 GlobalValue *GV = MO.getGlobal();
386 std::string Name = Mang->getValueName(GV);
388 // External or weakly linked global variables need non-lazily-resolved stubs
389 if (TM.getRelocationModel() != Reloc::Static) {
390 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
391 GV->hasLinkOnceLinkage()))) {
392 GVStubs.insert(Name);
393 O << "L" << Name << "$non_lazy_ptr";
399 if (MO.getOffset() > 0)
400 O << "+" << MO.getOffset();
401 else if (MO.getOffset() < 0)
404 if (GV->hasExternalWeakLinkage())
405 ExtWeakSymbols.insert(GV);
410 O << "<unknown operand type: " << MO.getType() << ">";
415 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
417 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
418 std::string Name = getGlobalLinkName(GV);
419 if (TM.getRelocationModel() != Reloc::Static) {
420 GVStubs.insert(Name);
421 O << "L" << Name << "$non_lazy_ptr";
427 /// PrintAsmOperand - Print out an operand for an inline asm expression.
429 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
431 const char *ExtraCode) {
432 // Does this asm operand have a single letter operand modifier?
433 if (ExtraCode && ExtraCode[0]) {
434 if (ExtraCode[1] != 0) return true; // Unknown modifier.
436 switch (ExtraCode[0]) {
437 default: return true; // Unknown modifier.
438 case 'c': // Don't print "$" before a global var name or constant.
439 // PPC never has a prefix.
440 printOperand(MI, OpNo);
442 case 'L': // Write second word of DImode reference.
443 // Verify that this operand has two consecutive registers.
444 if (!MI->getOperand(OpNo).isRegister() ||
445 OpNo+1 == MI->getNumOperands() ||
446 !MI->getOperand(OpNo+1).isRegister())
448 ++OpNo; // Return the high-part.
451 // Write 'i' if an integer constant, otherwise nothing. Used to print
453 if (MI->getOperand(OpNo).isImm())
459 printOperand(MI, OpNo);
463 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
465 const char *ExtraCode) {
466 if (ExtraCode && ExtraCode[0])
467 return true; // Unknown modifier.
468 if (MI->getOperand(OpNo).isRegister())
469 printMemRegReg(MI, OpNo);
471 printMemRegImm(MI, OpNo);
475 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
476 const char *Modifier) {
477 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
478 unsigned Code = MI->getOperand(OpNo).getImm();
479 if (!strcmp(Modifier, "cc")) {
480 switch ((PPC::Predicate)Code) {
481 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
482 case PPC::PRED_LT: O << "lt"; return;
483 case PPC::PRED_LE: O << "le"; return;
484 case PPC::PRED_EQ: O << "eq"; return;
485 case PPC::PRED_GE: O << "ge"; return;
486 case PPC::PRED_GT: O << "gt"; return;
487 case PPC::PRED_NE: O << "ne"; return;
488 case PPC::PRED_UN: O << "un"; return;
489 case PPC::PRED_NU: O << "nu"; return;
493 assert(!strcmp(Modifier, "reg") &&
494 "Need to specify 'cc' or 'reg' as predicate op modifier!");
495 // Don't print the register for 'always'.
496 if (Code == PPC::PRED_ALWAYS) return;
497 printOperand(MI, OpNo+1);
502 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
503 /// the current output stream.
505 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
508 // Check for slwi/srwi mnemonics.
509 if (MI->getOpcode() == PPC::RLWINM) {
510 bool FoundMnemonic = false;
511 unsigned char SH = MI->getOperand(2).getImmedValue();
512 unsigned char MB = MI->getOperand(3).getImmedValue();
513 unsigned char ME = MI->getOperand(4).getImmedValue();
514 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
515 O << "slwi "; FoundMnemonic = true;
517 if (SH <= 31 && MB == (32-SH) && ME == 31) {
518 O << "srwi "; FoundMnemonic = true;
525 O << ", " << (unsigned int)SH << "\n";
528 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
529 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
537 } else if (MI->getOpcode() == PPC::RLDICR) {
538 unsigned char SH = MI->getOperand(2).getImmedValue();
539 unsigned char ME = MI->getOperand(3).getImmedValue();
540 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
546 O << ", " << (unsigned int)SH << "\n";
551 if (printInstruction(MI))
552 return; // Printer was automatically generated
554 assert(0 && "Unhandled instruction in asm writer!");
559 /// runOnMachineFunction - This uses the printMachineInstruction()
560 /// method to print assembly for each instruction.
562 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
563 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
565 SetupMachineFunction(MF);
568 // Print out constants referenced by the function
569 EmitConstantPool(MF.getConstantPool());
571 // Print out labels for the function.
572 const Function *F = MF.getFunction();
573 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
575 switch (F->getLinkage()) {
576 default: assert(0 && "Unknown linkage type!");
577 case Function::InternalLinkage: // Symbols default to internal.
579 case Function::ExternalLinkage:
580 O << "\t.global\t" << CurrentFnName << '\n'
581 << "\t.type\t" << CurrentFnName << ", @function\n";
583 case Function::WeakLinkage:
584 case Function::LinkOnceLinkage:
585 O << "\t.global\t" << CurrentFnName << '\n';
586 O << "\t.weak\t" << CurrentFnName << '\n';
590 if (F->hasHiddenVisibility())
591 if (const char *Directive = TAI->getHiddenDirective())
592 O << Directive << CurrentFnName << "\n";
595 O << CurrentFnName << ":\n";
597 // Emit pre-function debug information.
598 DW.BeginFunction(&MF);
600 // Print out code for the function.
601 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
603 // Print a label for the basic block.
604 if (I != MF.begin()) {
605 printBasicBlockLabel(I, true);
608 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
610 // Print the assembly for the instruction.
612 printMachineInstruction(II);
616 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
618 // Print out jump tables referenced by the function.
619 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
621 // Emit post-function debug information.
624 // We didn't modify anything.
628 bool LinuxAsmPrinter::doInitialization(Module &M) {
629 bool Result = AsmPrinter::doInitialization(M);
631 // GNU as handles section names wrapped in quotes
632 Mang->setUseQuotes(true);
634 SwitchToTextSection(TAI->getTextSection());
636 // Emit initial debug information.
641 bool LinuxAsmPrinter::doFinalization(Module &M) {
642 const TargetData *TD = TM.getTargetData();
644 // Print out module-level global variables here.
645 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
647 if (!I->hasInitializer()) continue; // External global require no code
649 // Check to see if this is a special global used by LLVM, if so, emit it.
650 if (EmitSpecialLLVMGlobal(I))
653 std::string name = Mang->getValueName(I);
655 if (I->hasHiddenVisibility())
656 if (const char *Directive = TAI->getHiddenDirective())
657 O << Directive << name << "\n";
659 Constant *C = I->getInitializer();
660 unsigned Size = TD->getTypeSize(C->getType());
661 unsigned Align = TD->getPreferredAlignmentLog(I);
663 if (C->isNullValue() && /* FIXME: Verify correct */
664 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
665 I->hasLinkOnceLinkage() ||
666 (I->hasExternalLinkage() && !I->hasSection()))) {
667 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
668 if (I->hasExternalLinkage()) {
669 O << "\t.global " << name << '\n';
670 O << "\t.type " << name << ", @object\n";
672 O << "\t.zero " << Size << "\n";
673 } else if (I->hasInternalLinkage()) {
674 SwitchToDataSection("\t.data", I);
675 O << TAI->getLCOMMDirective() << name << "," << Size;
677 SwitchToDataSection("\t.data", I);
678 O << ".comm " << name << "," << Size;
680 O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
682 switch (I->getLinkage()) {
683 case GlobalValue::LinkOnceLinkage:
684 case GlobalValue::WeakLinkage:
685 O << "\t.global " << name << '\n'
686 << "\t.type " << name << ", @object\n"
687 << "\t.weak " << name << '\n';
688 SwitchToDataSection("\t.data", I);
690 case GlobalValue::AppendingLinkage:
691 // FIXME: appending linkage variables should go into a section of
692 // their name or something. For now, just emit them as external.
693 case GlobalValue::ExternalLinkage:
694 // If external or appending, declare as a global symbol
695 O << "\t.global " << name << "\n"
696 << "\t.type " << name << ", @object\n";
698 case GlobalValue::InternalLinkage:
699 if (I->isConstant()) {
700 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
701 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
702 SwitchToDataSection(TAI->getCStringSection(), I);
707 // FIXME: special handling for ".ctors" & ".dtors" sections
708 if (I->hasSection() &&
709 (I->getSection() == ".ctors" ||
710 I->getSection() == ".dtors")) {
711 std::string SectionName = ".section " + I->getSection()
712 + ",\"aw\",@progbits";
713 SwitchToDataSection(SectionName.c_str());
715 if (I->isConstant() && TAI->getReadOnlySection())
716 SwitchToDataSection(TAI->getReadOnlySection(), I);
718 SwitchToDataSection(TAI->getDataSection(), I);
722 cerr << "Unknown linkage type!";
726 EmitAlignment(Align, I);
727 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
728 << I->getName() << "'\n";
730 // If the initializer is a extern weak symbol, remember to emit the weak
732 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
733 if (GV->hasExternalWeakLinkage())
734 ExtWeakSymbols.insert(GV);
736 EmitGlobalConstant(C);
743 // Emit initial debug information.
746 return AsmPrinter::doFinalization(M);
749 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
750 switch (F.getLinkage()) {
751 default: assert(0 && "Unknown linkage type!");
752 case Function::ExternalLinkage:
753 case Function::InternalLinkage: return TAI->getTextSection();
754 case Function::WeakLinkage:
755 case Function::LinkOnceLinkage:
760 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
761 switch (F.getLinkage()) {
762 default: assert(0 && "Unknown linkage type!");
763 case Function::ExternalLinkage:
764 case Function::InternalLinkage: return TAI->getTextSection();
765 case Function::WeakLinkage:
766 case Function::LinkOnceLinkage:
767 return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
771 /// runOnMachineFunction - This uses the printMachineInstruction()
772 /// method to print assembly for each instruction.
774 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
775 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
777 SetupMachineFunction(MF);
780 // Print out constants referenced by the function
781 EmitConstantPool(MF.getConstantPool());
783 // Print out labels for the function.
784 const Function *F = MF.getFunction();
785 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
787 switch (F->getLinkage()) {
788 default: assert(0 && "Unknown linkage type!");
789 case Function::InternalLinkage: // Symbols default to internal.
791 case Function::ExternalLinkage:
792 O << "\t.globl\t" << CurrentFnName << "\n";
794 case Function::WeakLinkage:
795 case Function::LinkOnceLinkage:
796 O << "\t.globl\t" << CurrentFnName << "\n";
797 O << "\t.weak_definition\t" << CurrentFnName << "\n";
801 if (F->hasHiddenVisibility())
802 if (const char *Directive = TAI->getHiddenDirective())
803 O << Directive << CurrentFnName << "\n";
806 O << CurrentFnName << ":\n";
808 // Emit pre-function debug information.
809 DW.BeginFunction(&MF);
811 // Print out code for the function.
812 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
814 // Print a label for the basic block.
815 if (I != MF.begin()) {
816 printBasicBlockLabel(I, true);
819 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
821 // Print the assembly for the instruction.
823 printMachineInstruction(II);
827 // Print out jump tables referenced by the function.
828 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
830 // Emit post-function debug information.
833 // We didn't modify anything.
838 bool DarwinAsmPrinter::doInitialization(Module &M) {
839 static const char *CPUDirectives[] = {
850 unsigned Directive = Subtarget.getDarwinDirective();
851 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
852 Directive = PPC::DIR_970;
853 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
854 Directive = PPC::DIR_7400;
855 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
856 Directive = PPC::DIR_64;
857 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
858 O << "\t.machine " << CPUDirectives[Directive] << "\n";
860 bool Result = AsmPrinter::doInitialization(M);
862 // Darwin wants symbols to be quoted if they have complex names.
863 Mang->setUseQuotes(true);
865 // Prime text sections so they are adjacent. This reduces the likelihood a
866 // large data or debug section causes a branch to exceed 16M limit.
867 SwitchToTextSection(".section __TEXT,__textcoal_nt,coalesced,"
868 "pure_instructions");
869 if (TM.getRelocationModel() == Reloc::PIC_) {
870 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
871 "pure_instructions,32");
872 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
873 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
874 "pure_instructions,16");
876 SwitchToTextSection(TAI->getTextSection());
878 // Emit initial debug information.
883 bool DarwinAsmPrinter::doFinalization(Module &M) {
884 const TargetData *TD = TM.getTargetData();
886 // Print out module-level global variables here.
887 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
889 if (!I->hasInitializer()) continue; // External global require no code
891 // Check to see if this is a special global used by LLVM, if so, emit it.
892 if (EmitSpecialLLVMGlobal(I)) {
893 if (TM.getRelocationModel() == Reloc::Static) {
894 if (I->getName() == "llvm.global_ctors")
895 O << ".reference .constructors_used\n";
896 else if (I->getName() == "llvm.global_dtors")
897 O << ".reference .destructors_used\n";
902 std::string name = Mang->getValueName(I);
904 if (I->hasHiddenVisibility())
905 if (const char *Directive = TAI->getHiddenDirective())
906 O << Directive << name << "\n";
908 Constant *C = I->getInitializer();
909 const Type *Type = C->getType();
910 unsigned Size = TD->getTypeSize(Type);
911 unsigned Align = TD->getPreferredAlignmentLog(I);
913 if (C->isNullValue() && /* FIXME: Verify correct */
914 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
915 I->hasLinkOnceLinkage() ||
916 (I->hasExternalLinkage() && !I->hasSection()))) {
917 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
918 if (I->hasExternalLinkage()) {
919 O << "\t.globl " << name << '\n';
920 O << "\t.zerofill __DATA, __common, " << name << ", "
921 << Size << ", " << Align;
922 } else if (I->hasInternalLinkage()) {
923 SwitchToDataSection("\t.data", I);
924 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
926 SwitchToDataSection("\t.data", I);
927 O << ".comm " << name << "," << Size;
929 O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
931 switch (I->getLinkage()) {
932 case GlobalValue::LinkOnceLinkage:
933 case GlobalValue::WeakLinkage:
934 O << "\t.globl " << name << '\n'
935 << "\t.weak_definition " << name << '\n';
936 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
938 case GlobalValue::AppendingLinkage:
939 // FIXME: appending linkage variables should go into a section of
940 // their name or something. For now, just emit them as external.
941 case GlobalValue::ExternalLinkage:
942 // If external or appending, declare as a global symbol
943 O << "\t.globl " << name << "\n";
945 case GlobalValue::InternalLinkage:
946 if (I->isConstant()) {
947 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
948 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
949 SwitchToDataSection(TAI->getCStringSection(), I);
954 if (!I->isConstant())
955 SwitchToDataSection(TAI->getDataSection(), I);
958 bool HasReloc = C->ContainsRelocations();
960 TM.getRelocationModel() != Reloc::Static)
961 SwitchToDataSection("\t.const_data\n");
962 else if (!HasReloc && Size == 4 &&
963 TAI->getFourByteConstantSection())
964 SwitchToDataSection(TAI->getFourByteConstantSection(), I);
965 else if (!HasReloc && Size == 8 &&
966 TAI->getEightByteConstantSection())
967 SwitchToDataSection(TAI->getEightByteConstantSection(), I);
968 else if (!HasReloc && Size == 16 &&
969 TAI->getSixteenByteConstantSection())
970 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
971 else if (TAI->getReadOnlySection())
972 SwitchToDataSection(TAI->getReadOnlySection(), I);
974 SwitchToDataSection(TAI->getDataSection(), I);
978 cerr << "Unknown linkage type!";
982 EmitAlignment(Align, I);
983 O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
984 << I->getName() << "'\n";
986 // If the initializer is a extern weak symbol, remember to emit the weak
988 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
989 if (GV->hasExternalWeakLinkage())
990 ExtWeakSymbols.insert(GV);
992 EmitGlobalConstant(C);
997 bool isPPC64 = TD->getPointerSizeInBits() == 64;
999 // Output stubs for dynamically-linked functions
1000 if (TM.getRelocationModel() == Reloc::PIC_) {
1001 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1003 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
1004 "pure_instructions,32");
1006 O << "L" << *i << "$stub:\n";
1007 O << "\t.indirect_symbol " << *i << "\n";
1009 O << "\tbcl 20,31,L0$" << *i << "\n";
1010 O << "L0$" << *i << ":\n";
1011 O << "\tmflr r11\n";
1012 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
1015 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1017 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1018 O << "\tmtctr r12\n";
1020 SwitchToDataSection(".lazy_symbol_pointer");
1021 O << "L" << *i << "$lazy_ptr:\n";
1022 O << "\t.indirect_symbol " << *i << "\n";
1024 O << "\t.quad dyld_stub_binding_helper\n";
1026 O << "\t.long dyld_stub_binding_helper\n";
1029 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1031 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
1032 "pure_instructions,16");
1034 O << "L" << *i << "$stub:\n";
1035 O << "\t.indirect_symbol " << *i << "\n";
1036 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
1038 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1040 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1041 O << "\tmtctr r12\n";
1043 SwitchToDataSection(".lazy_symbol_pointer");
1044 O << "L" << *i << "$lazy_ptr:\n";
1045 O << "\t.indirect_symbol " << *i << "\n";
1047 O << "\t.quad dyld_stub_binding_helper\n";
1049 O << "\t.long dyld_stub_binding_helper\n";
1055 // Output stubs for external and common global variables.
1056 if (GVStubs.begin() != GVStubs.end()) {
1057 SwitchToDataSection(".non_lazy_symbol_pointer");
1058 for (std::set<std::string>::iterator I = GVStubs.begin(),
1059 E = GVStubs.end(); I != E; ++I) {
1060 O << "L" << *I << "$non_lazy_ptr:\n";
1061 O << "\t.indirect_symbol " << *I << "\n";
1063 O << "\t.quad\t0\n";
1065 O << "\t.long\t0\n";
1070 // Emit initial debug information.
1073 // Funny Darwin hack: This flag tells the linker that no global symbols
1074 // contain code that falls through to other global symbols (e.g. the obvious
1075 // implementation of multiple entry points). If this doesn't occur, the
1076 // linker can safely perform dead code stripping. Since LLVM never generates
1077 // code that does this, it is always safe to set.
1078 O << "\t.subsections_via_symbols\n";
1080 return AsmPrinter::doFinalization(M);
1085 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1086 /// for a MachineFunction to the given output stream, in a format that the
1087 /// Darwin assembler can deal with.
1089 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1090 PPCTargetMachine &tm) {
1091 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1093 if (Subtarget->isDarwin()) {
1094 return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1096 return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());