1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
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 implements the AsmPrinter class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/DwarfWriter.h"
24 #include "llvm/Support/Mangler.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetAsmInfo.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
38 char AsmPrinter::ID = 0;
39 AsmPrinter::AsmPrinter(raw_ostream &o, TargetMachine &tm,
40 const TargetAsmInfo *T, bool F)
41 : MachineFunctionPass(&ID), FunctionNumber(0), Fast(F), O(o),
42 TM(tm), TAI(T), TRI(tm.getRegisterInfo()),
43 IsInTextSection(false)
46 AsmPrinter::~AsmPrinter() {
47 for (gcp_iterator I = GCMetadataPrinters.begin(),
48 E = GCMetadataPrinters.end(); I != E; ++I)
52 /// SwitchToTextSection - Switch to the specified text section of the executable
53 /// if we are not already in it!
55 void AsmPrinter::SwitchToTextSection(const char *NewSection,
56 const GlobalValue *GV) {
58 if (GV && GV->hasSection())
59 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
63 // If we're already in this section, we're done.
64 if (CurrentSection == NS) return;
66 // Close the current section, if applicable.
67 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
68 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
72 if (!CurrentSection.empty())
73 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
75 IsInTextSection = true;
78 /// SwitchToDataSection - Switch to the specified data section of the executable
79 /// if we are not already in it!
81 void AsmPrinter::SwitchToDataSection(const char *NewSection,
82 const GlobalValue *GV) {
84 if (GV && GV->hasSection())
85 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
89 // If we're already in this section, we're done.
90 if (CurrentSection == NS) return;
92 // Close the current section, if applicable.
93 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
94 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
98 if (!CurrentSection.empty())
99 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
101 IsInTextSection = false;
104 /// SwitchToSection - Switch to the specified section of the executable if we
105 /// are not already in it!
106 void AsmPrinter::SwitchToSection(const Section* NS) {
107 const std::string& NewSection = NS->getName();
109 // If we're already in this section, we're done.
110 if (CurrentSection == NewSection) return;
112 // Close the current section, if applicable.
113 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
114 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
116 // FIXME: Make CurrentSection a Section* in the future
117 CurrentSection = NewSection;
118 CurrentSection_ = NS;
120 if (!CurrentSection.empty()) {
121 // If section is named we need to switch into it via special '.section'
122 // directive and also append funky flags. Otherwise - section name is just
123 // some magic assembler directive.
125 O << TAI->getSwitchToSectionDirective()
127 << TAI->getSectionFlags(NS->getFlags());
130 O << TAI->getDataSectionStartSuffix() << '\n';
133 IsInTextSection = (NS->getFlags() & SectionFlags::Code);
136 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
137 MachineFunctionPass::getAnalysisUsage(AU);
138 AU.addRequired<GCModuleInfo>();
141 bool AsmPrinter::doInitialization(Module &M) {
142 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix());
144 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
145 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
147 if (TAI->hasSingleParameterDotFile()) {
148 /* Very minimal debug info. It is ignored if we emit actual
149 debug info. If we don't, this at helps the user find where
150 a function came from. */
151 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
154 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
155 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
156 MP->beginAssembly(O, *this, *TAI);
158 if (!M.getModuleInlineAsm().empty())
159 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
160 << M.getModuleInlineAsm()
161 << '\n' << TAI->getCommentString()
162 << " End of file scope inline assembly\n";
164 SwitchToDataSection(""); // Reset back to no section.
166 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
167 if (MMI) MMI->AnalyzeModule(M);
168 DW = getAnalysisIfAvailable<DwarfWriter>();
172 bool AsmPrinter::doFinalization(Module &M) {
173 if (TAI->getWeakRefDirective()) {
174 if (!ExtWeakSymbols.empty())
175 SwitchToDataSection("");
177 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
178 e = ExtWeakSymbols.end(); i != e; ++i) {
179 const GlobalValue *GV = *i;
180 std::string Name = Mang->getValueName(GV);
181 O << TAI->getWeakRefDirective() << Name << '\n';
185 if (TAI->getSetDirective()) {
186 if (!M.alias_empty())
187 SwitchToSection(TAI->getTextSection());
190 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
192 std::string Name = Mang->getValueName(I);
195 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
196 Target = Mang->getValueName(GV);
198 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
199 O << "\t.globl\t" << Name << '\n';
200 else if (I->hasWeakLinkage())
201 O << TAI->getWeakRefDirective() << Name << '\n';
202 else if (!I->hasLocalLinkage())
203 assert(0 && "Invalid alias linkage");
205 printVisibility(Name, I->getVisibility());
207 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
211 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
212 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
213 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
214 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
215 MP->finishAssembly(O, *this, *TAI);
217 // If we don't have any trampolines, then we don't require stack memory
218 // to be executable. Some targets have a directive to declare this.
219 Function* InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
220 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
221 if (TAI->getNonexecutableStackDirective())
222 O << TAI->getNonexecutableStackDirective() << '\n';
224 delete Mang; Mang = 0;
228 std::string AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
229 assert(MF && "No machine function?");
230 std::string Name = MF->getFunction()->getName();
232 Name = Mang->getValueName(MF->getFunction());
233 return Mang->makeNameProper(TAI->getEHGlobalPrefix() +
234 Name + ".eh", TAI->getGlobalPrefix());
237 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
238 // What's my mangled name?
239 CurrentFnName = Mang->getValueName(MF.getFunction());
240 IncrementFunctionNumber();
244 // SectionCPs - Keep track the alignment, constpool entries per Section.
248 SmallVector<unsigned, 4> CPEs;
249 SectionCPs(const Section *s, unsigned a) : S(s), Alignment(a) {};
253 /// EmitConstantPool - Print to the current output stream assembly
254 /// representations of the constants in the constant pool MCP. This is
255 /// used to print out constants which have been "spilled to memory" by
256 /// the code generator.
258 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
259 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
260 if (CP.empty()) return;
262 // Calculate sections for constant pool entries. We collect entries to go into
263 // the same section together to reduce amount of section switch statements.
264 SmallVector<SectionCPs, 4> CPSections;
265 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
266 MachineConstantPoolEntry CPE = CP[i];
267 unsigned Align = CPE.getAlignment();
268 const Section* S = TAI->SelectSectionForMachineConst(CPE.getType());
269 // The number of sections are small, just do a linear search from the
270 // last section to the first.
272 unsigned SecIdx = CPSections.size();
273 while (SecIdx != 0) {
274 if (CPSections[--SecIdx].S == S) {
280 SecIdx = CPSections.size();
281 CPSections.push_back(SectionCPs(S, Align));
284 if (Align > CPSections[SecIdx].Alignment)
285 CPSections[SecIdx].Alignment = Align;
286 CPSections[SecIdx].CPEs.push_back(i);
289 // Now print stuff into the calculated sections.
290 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
291 SwitchToSection(CPSections[i].S);
292 EmitAlignment(Log2_32(CPSections[i].Alignment));
295 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
296 unsigned CPI = CPSections[i].CPEs[j];
297 MachineConstantPoolEntry CPE = CP[CPI];
299 // Emit inter-object padding for alignment.
300 unsigned AlignMask = CPE.getAlignment() - 1;
301 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
302 EmitZeros(NewOffset - Offset);
304 const Type *Ty = CPE.getType();
305 Offset = NewOffset + TM.getTargetData()->getTypePaddedSize(Ty);
307 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
308 << CPI << ":\t\t\t\t\t";
310 O << TAI->getCommentString() << ' ';
311 WriteTypeSymbolic(O, CPE.getType(), 0);
314 if (CPE.isMachineConstantPoolEntry())
315 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
317 EmitGlobalConstant(CPE.Val.ConstVal);
322 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
323 /// by the current function to the current output stream.
325 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
326 MachineFunction &MF) {
327 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
328 if (JT.empty()) return;
330 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
332 // Pick the directive to use to print the jump table entries, and switch to
333 // the appropriate section.
334 TargetLowering *LoweringInfo = TM.getTargetLowering();
336 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
337 const Function *F = MF.getFunction();
338 unsigned SectionFlags = TAI->SectionFlagsForGlobal(F);
339 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
340 !JumpTableDataSection ||
341 SectionFlags & SectionFlags::Linkonce) {
342 // In PIC mode, we need to emit the jump table to the same section as the
343 // function body itself, otherwise the label differences won't make sense.
344 // We should also do if the section name is NULL or function is declared in
345 // discardable section.
346 SwitchToSection(TAI->SectionForGlobal(F));
348 SwitchToDataSection(JumpTableDataSection);
351 EmitAlignment(Log2_32(MJTI->getAlignment()));
353 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
354 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
356 // If this jump table was deleted, ignore it.
357 if (JTBBs.empty()) continue;
359 // For PIC codegen, if possible we want to use the SetDirective to reduce
360 // the number of relocations the assembler will generate for the jump table.
361 // Set directives are all printed before the jump table itself.
362 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
363 if (TAI->getSetDirective() && IsPic)
364 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
365 if (EmittedSets.insert(JTBBs[ii]))
366 printPICJumpTableSetLabel(i, JTBBs[ii]);
368 // On some targets (e.g. darwin) we want to emit two consequtive labels
369 // before each jump table. The first label is never referenced, but tells
370 // the assembler and linker the extents of the jump table object. The
371 // second label is actually referenced by the code.
372 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
373 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
375 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
376 << '_' << i << ":\n";
378 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
379 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
385 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
386 const MachineBasicBlock *MBB,
387 unsigned uid) const {
388 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
390 // Use JumpTableDirective otherwise honor the entry size from the jump table
392 const char *JTEntryDirective = TAI->getJumpTableDirective();
393 bool HadJTEntryDirective = JTEntryDirective != NULL;
394 if (!HadJTEntryDirective) {
395 JTEntryDirective = MJTI->getEntrySize() == 4 ?
396 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
399 O << JTEntryDirective << ' ';
401 // If we have emitted set directives for the jump table entries, print
402 // them rather than the entries themselves. If we're emitting PIC, then
403 // emit the table entries as differences between two text section labels.
404 // If we're emitting non-PIC code, then emit the entries as direct
405 // references to the target basic blocks.
407 if (TAI->getSetDirective()) {
408 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
409 << '_' << uid << "_set_" << MBB->getNumber();
411 printBasicBlockLabel(MBB, false, false, false);
412 // If the arch uses custom Jump Table directives, don't calc relative to
414 if (!HadJTEntryDirective)
415 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
416 << getFunctionNumber() << '_' << uid;
419 printBasicBlockLabel(MBB, false, false, false);
424 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
425 /// special global used by LLVM. If so, emit it and return true, otherwise
426 /// do nothing and return false.
427 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
428 if (GV->getName() == "llvm.used") {
429 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
430 EmitLLVMUsedList(GV->getInitializer());
434 // Ignore debug and non-emitted data.
435 if (GV->getSection() == "llvm.metadata") return true;
437 if (!GV->hasAppendingLinkage()) return false;
439 assert(GV->hasInitializer() && "Not a special LLVM global!");
441 const TargetData *TD = TM.getTargetData();
442 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
443 if (GV->getName() == "llvm.global_ctors") {
444 SwitchToDataSection(TAI->getStaticCtorsSection());
445 EmitAlignment(Align, 0);
446 EmitXXStructorList(GV->getInitializer());
450 if (GV->getName() == "llvm.global_dtors") {
451 SwitchToDataSection(TAI->getStaticDtorsSection());
452 EmitAlignment(Align, 0);
453 EmitXXStructorList(GV->getInitializer());
460 /// findGlobalValue - if CV is an expression equivalent to a single
461 /// global value, return that value.
462 const GlobalValue * AsmPrinter::findGlobalValue(const Constant *CV) {
463 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
465 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
466 const TargetData *TD = TM.getTargetData();
467 unsigned Opcode = CE->getOpcode();
469 case Instruction::GetElementPtr: {
470 const Constant *ptrVal = CE->getOperand(0);
471 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
472 if (TD->getIndexedOffset(ptrVal->getType(), &idxVec[0], idxVec.size()))
474 return findGlobalValue(ptrVal);
476 case Instruction::BitCast:
477 return findGlobalValue(CE->getOperand(0));
485 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
486 /// global in the specified llvm.used list for which emitUsedDirectiveFor
487 /// is true, as being used with this directive.
489 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
490 const char *Directive = TAI->getUsedDirective();
492 // Should be an array of 'sbyte*'.
493 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
494 if (InitList == 0) return;
496 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
497 const GlobalValue *GV = findGlobalValue(InitList->getOperand(i));
498 if (TAI->emitUsedDirectiveFor(GV, Mang)) {
500 EmitConstantValueOnly(InitList->getOperand(i));
506 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
507 /// function pointers, ignoring the init priority.
508 void AsmPrinter::EmitXXStructorList(Constant *List) {
509 // Should be an array of '{ int, void ()* }' structs. The first value is the
510 // init priority, which we ignore.
511 if (!isa<ConstantArray>(List)) return;
512 ConstantArray *InitList = cast<ConstantArray>(List);
513 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
514 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
515 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
517 if (CS->getOperand(1)->isNullValue())
518 return; // Found a null terminator, exit printing.
519 // Emit the function pointer.
520 EmitGlobalConstant(CS->getOperand(1));
524 /// getGlobalLinkName - Returns the asm/link name of of the specified
525 /// global variable. Should be overridden by each target asm printer to
526 /// generate the appropriate value.
527 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
528 std::string LinkName;
530 if (isa<Function>(GV)) {
531 LinkName += TAI->getFunctionAddrPrefix();
532 LinkName += Mang->getValueName(GV);
533 LinkName += TAI->getFunctionAddrSuffix();
535 LinkName += TAI->getGlobalVarAddrPrefix();
536 LinkName += Mang->getValueName(GV);
537 LinkName += TAI->getGlobalVarAddrSuffix();
543 /// EmitExternalGlobal - Emit the external reference to a global variable.
544 /// Should be overridden if an indirect reference should be used.
545 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
546 O << getGlobalLinkName(GV);
551 //===----------------------------------------------------------------------===//
552 /// LEB 128 number encoding.
554 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
555 /// representing an unsigned leb128 value.
556 void AsmPrinter::PrintULEB128(unsigned Value) const {
559 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
561 if (Value) Byte |= 0x80;
562 O << "0x" << utohex_buffer(Byte, Buffer+20);
563 if (Value) O << ", ";
567 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
568 /// representing a signed leb128 value.
569 void AsmPrinter::PrintSLEB128(int Value) const {
570 int Sign = Value >> (8 * sizeof(Value) - 1);
575 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
577 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
578 if (IsMore) Byte |= 0x80;
579 O << "0x" << utohex_buffer(Byte, Buffer+20);
580 if (IsMore) O << ", ";
584 //===--------------------------------------------------------------------===//
585 // Emission and print routines
588 /// PrintHex - Print a value as a hexidecimal value.
590 void AsmPrinter::PrintHex(int Value) const {
592 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
595 /// EOL - Print a newline character to asm stream. If a comment is present
596 /// then it will be printed first. Comments should not contain '\n'.
597 void AsmPrinter::EOL() const {
601 void AsmPrinter::EOL(const std::string &Comment) const {
602 if (VerboseAsm && !Comment.empty()) {
604 << TAI->getCommentString()
611 void AsmPrinter::EOL(const char* Comment) const {
612 if (VerboseAsm && *Comment) {
614 << TAI->getCommentString()
621 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
622 /// unsigned leb128 value.
623 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
624 if (TAI->hasLEB128()) {
628 O << TAI->getData8bitsDirective();
633 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
634 /// signed leb128 value.
635 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
636 if (TAI->hasLEB128()) {
640 O << TAI->getData8bitsDirective();
645 /// EmitInt8 - Emit a byte directive and value.
647 void AsmPrinter::EmitInt8(int Value) const {
648 O << TAI->getData8bitsDirective();
649 PrintHex(Value & 0xFF);
652 /// EmitInt16 - Emit a short directive and value.
654 void AsmPrinter::EmitInt16(int Value) const {
655 O << TAI->getData16bitsDirective();
656 PrintHex(Value & 0xFFFF);
659 /// EmitInt32 - Emit a long directive and value.
661 void AsmPrinter::EmitInt32(int Value) const {
662 O << TAI->getData32bitsDirective();
666 /// EmitInt64 - Emit a long long directive and value.
668 void AsmPrinter::EmitInt64(uint64_t Value) const {
669 if (TAI->getData64bitsDirective()) {
670 O << TAI->getData64bitsDirective();
673 if (TM.getTargetData()->isBigEndian()) {
674 EmitInt32(unsigned(Value >> 32)); O << '\n';
675 EmitInt32(unsigned(Value));
677 EmitInt32(unsigned(Value)); O << '\n';
678 EmitInt32(unsigned(Value >> 32));
683 /// toOctal - Convert the low order bits of X into an octal digit.
685 static inline char toOctal(int X) {
689 /// printStringChar - Print a char, escaped if necessary.
691 static void printStringChar(raw_ostream &O, char C) {
694 } else if (C == '\\') {
696 } else if (isprint((unsigned char)C)) {
700 case '\b': O << "\\b"; break;
701 case '\f': O << "\\f"; break;
702 case '\n': O << "\\n"; break;
703 case '\r': O << "\\r"; break;
704 case '\t': O << "\\t"; break;
707 O << toOctal(C >> 6);
708 O << toOctal(C >> 3);
709 O << toOctal(C >> 0);
715 /// EmitString - Emit a string with quotes and a null terminator.
716 /// Special characters are emitted properly.
717 /// \literal (Eg. '\t') \endliteral
718 void AsmPrinter::EmitString(const std::string &String) const {
719 const char* AscizDirective = TAI->getAscizDirective();
723 O << TAI->getAsciiDirective();
725 for (unsigned i = 0, N = String.size(); i < N; ++i) {
726 unsigned char C = String[i];
727 printStringChar(O, C);
736 /// EmitFile - Emit a .file directive.
737 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
738 O << "\t.file\t" << Number << " \"";
739 for (unsigned i = 0, N = Name.size(); i < N; ++i) {
740 unsigned char C = Name[i];
741 printStringChar(O, C);
747 //===----------------------------------------------------------------------===//
749 // EmitAlignment - Emit an alignment directive to the specified power of
750 // two boundary. For example, if you pass in 3 here, you will get an 8
751 // byte alignment. If a global value is specified, and if that global has
752 // an explicit alignment requested, it will unconditionally override the
753 // alignment request. However, if ForcedAlignBits is specified, this value
754 // has final say: the ultimate alignment will be the max of ForcedAlignBits
755 // and the alignment computed with NumBits and the global.
759 // if (GV && GV->hasalignment) Align = GV->getalignment();
760 // Align = std::max(Align, ForcedAlignBits);
762 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
763 unsigned ForcedAlignBits,
764 bool UseFillExpr) const {
765 if (GV && GV->getAlignment())
766 NumBits = Log2_32(GV->getAlignment());
767 NumBits = std::max(NumBits, ForcedAlignBits);
769 if (NumBits == 0) return; // No need to emit alignment.
770 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
771 O << TAI->getAlignDirective() << NumBits;
773 unsigned FillValue = TAI->getTextAlignFillValue();
774 UseFillExpr &= IsInTextSection && FillValue;
783 /// EmitZeros - Emit a block of zeros.
785 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
787 if (TAI->getZeroDirective()) {
788 O << TAI->getZeroDirective() << NumZeros;
789 if (TAI->getZeroDirectiveSuffix())
790 O << TAI->getZeroDirectiveSuffix();
793 for (; NumZeros; --NumZeros)
794 O << TAI->getData8bitsDirective(AddrSpace) << "0\n";
799 // Print out the specified constant, without a storage class. Only the
800 // constants valid in constant expressions can occur here.
801 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
802 if (CV->isNullValue() || isa<UndefValue>(CV))
804 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
805 O << CI->getZExtValue();
806 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
807 // This is a constant address for a global variable or function. Use the
808 // name of the variable or function as the address value, possibly
809 // decorating it with GlobalVarAddrPrefix/Suffix or
810 // FunctionAddrPrefix/Suffix (these all default to "" )
811 if (isa<Function>(GV)) {
812 O << TAI->getFunctionAddrPrefix()
813 << Mang->getValueName(GV)
814 << TAI->getFunctionAddrSuffix();
816 O << TAI->getGlobalVarAddrPrefix()
817 << Mang->getValueName(GV)
818 << TAI->getGlobalVarAddrSuffix();
820 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
821 const TargetData *TD = TM.getTargetData();
822 unsigned Opcode = CE->getOpcode();
824 case Instruction::GetElementPtr: {
825 // generate a symbolic expression for the byte address
826 const Constant *ptrVal = CE->getOperand(0);
827 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
828 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
830 // Truncate/sext the offset to the pointer size.
831 if (TD->getPointerSizeInBits() != 64) {
832 int SExtAmount = 64-TD->getPointerSizeInBits();
833 Offset = (Offset << SExtAmount) >> SExtAmount;
838 EmitConstantValueOnly(ptrVal);
840 O << ") + " << Offset;
842 O << ") - " << -Offset;
844 EmitConstantValueOnly(ptrVal);
848 case Instruction::Trunc:
849 case Instruction::ZExt:
850 case Instruction::SExt:
851 case Instruction::FPTrunc:
852 case Instruction::FPExt:
853 case Instruction::UIToFP:
854 case Instruction::SIToFP:
855 case Instruction::FPToUI:
856 case Instruction::FPToSI:
857 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
859 case Instruction::BitCast:
860 return EmitConstantValueOnly(CE->getOperand(0));
862 case Instruction::IntToPtr: {
863 // Handle casts to pointers by changing them into casts to the appropriate
864 // integer type. This promotes constant folding and simplifies this code.
865 Constant *Op = CE->getOperand(0);
866 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
867 return EmitConstantValueOnly(Op);
871 case Instruction::PtrToInt: {
872 // Support only foldable casts to/from pointers that can be eliminated by
873 // changing the pointer to the appropriately sized integer type.
874 Constant *Op = CE->getOperand(0);
875 const Type *Ty = CE->getType();
877 // We can emit the pointer value into this slot if the slot is an
878 // integer slot greater or equal to the size of the pointer.
879 if (TD->getTypePaddedSize(Ty) >= TD->getTypePaddedSize(Op->getType()))
880 return EmitConstantValueOnly(Op);
883 EmitConstantValueOnly(Op);
884 APInt ptrMask = APInt::getAllOnesValue(TD->getTypePaddedSizeInBits(Ty));
887 ptrMask.toStringUnsigned(S);
888 O << ") & " << S.c_str() << ')';
891 case Instruction::Add:
892 case Instruction::Sub:
893 case Instruction::And:
894 case Instruction::Or:
895 case Instruction::Xor:
897 EmitConstantValueOnly(CE->getOperand(0));
900 case Instruction::Add:
903 case Instruction::Sub:
906 case Instruction::And:
909 case Instruction::Or:
912 case Instruction::Xor:
919 EmitConstantValueOnly(CE->getOperand(1));
923 assert(0 && "Unsupported operator!");
926 assert(0 && "Unknown constant value!");
930 /// printAsCString - Print the specified array as a C compatible string, only if
931 /// the predicate isString is true.
933 static void printAsCString(raw_ostream &O, const ConstantArray *CVA,
935 assert(CVA->isString() && "Array is not string compatible!");
938 for (unsigned i = 0; i != LastElt; ++i) {
940 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
941 printStringChar(O, C);
946 /// EmitString - Emit a zero-byte-terminated string constant.
948 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
949 unsigned NumElts = CVA->getNumOperands();
950 if (TAI->getAscizDirective() && NumElts &&
951 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
952 O << TAI->getAscizDirective();
953 printAsCString(O, CVA, NumElts-1);
955 O << TAI->getAsciiDirective();
956 printAsCString(O, CVA, NumElts);
961 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA) {
962 if (CVA->isString()) {
964 } else { // Not a string. Print the values in successive locations
965 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
966 EmitGlobalConstant(CVA->getOperand(i));
970 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
971 const VectorType *PTy = CP->getType();
973 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
974 EmitGlobalConstant(CP->getOperand(I));
977 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
978 unsigned AddrSpace) {
979 // Print the fields in successive locations. Pad to align if needed!
980 const TargetData *TD = TM.getTargetData();
981 unsigned Size = TD->getTypePaddedSize(CVS->getType());
982 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
983 uint64_t sizeSoFar = 0;
984 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
985 const Constant* field = CVS->getOperand(i);
987 // Check if padding is needed and insert one or more 0s.
988 uint64_t fieldSize = TD->getTypePaddedSize(field->getType());
989 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
990 - cvsLayout->getElementOffset(i)) - fieldSize;
991 sizeSoFar += fieldSize + padSize;
993 // Now print the actual field value.
994 EmitGlobalConstant(field, AddrSpace);
996 // Insert padding - this may include padding to increase the size of the
997 // current field up to the ABI size (if the struct is not packed) as well
998 // as padding to ensure that the next field starts at the right offset.
999 EmitZeros(padSize, AddrSpace);
1001 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1002 "Layout of constant struct may be incorrect!");
1005 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1006 unsigned AddrSpace) {
1007 // FP Constants are printed as integer constants to avoid losing
1009 const TargetData *TD = TM.getTargetData();
1010 if (CFP->getType() == Type::DoubleTy) {
1011 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1012 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1013 if (TAI->getData64bitsDirective(AddrSpace))
1014 O << TAI->getData64bitsDirective(AddrSpace) << i << '\t'
1015 << TAI->getCommentString() << " double value: " << Val << '\n';
1016 else if (TD->isBigEndian()) {
1017 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32)
1018 << '\t' << TAI->getCommentString()
1019 << " double most significant word " << Val << '\n';
1020 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i)
1021 << '\t' << TAI->getCommentString()
1022 << " double least significant word " << Val << '\n';
1024 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i)
1025 << '\t' << TAI->getCommentString()
1026 << " double least significant word " << Val << '\n';
1027 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32)
1028 << '\t' << TAI->getCommentString()
1029 << " double most significant word " << Val << '\n';
1032 } else if (CFP->getType() == Type::FloatTy) {
1033 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1034 O << TAI->getData32bitsDirective(AddrSpace)
1035 << CFP->getValueAPF().bitcastToAPInt().getZExtValue()
1036 << '\t' << TAI->getCommentString() << " float " << Val << '\n';
1038 } else if (CFP->getType() == Type::X86_FP80Ty) {
1039 // all long double variants are printed as hex
1040 // api needed to prevent premature destruction
1041 APInt api = CFP->getValueAPF().bitcastToAPInt();
1042 const uint64_t *p = api.getRawData();
1043 // Convert to double so we can print the approximate val as a comment.
1044 APFloat DoubleVal = CFP->getValueAPF();
1046 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1048 if (TD->isBigEndian()) {
1049 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1])
1050 << '\t' << TAI->getCommentString()
1051 << " long double most significant halfword of ~"
1052 << DoubleVal.convertToDouble() << '\n';
1053 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48)
1054 << '\t' << TAI->getCommentString()
1055 << " long double next halfword\n";
1056 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32)
1057 << '\t' << TAI->getCommentString()
1058 << " long double next halfword\n";
1059 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16)
1060 << '\t' << TAI->getCommentString()
1061 << " long double next halfword\n";
1062 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0])
1063 << '\t' << TAI->getCommentString()
1064 << " long double least significant halfword\n";
1066 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0])
1067 << '\t' << TAI->getCommentString()
1068 << " long double least significant halfword of ~"
1069 << DoubleVal.convertToDouble() << '\n';
1070 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16)
1071 << '\t' << TAI->getCommentString()
1072 << " long double next halfword\n";
1073 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32)
1074 << '\t' << TAI->getCommentString()
1075 << " long double next halfword\n";
1076 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48)
1077 << '\t' << TAI->getCommentString()
1078 << " long double next halfword\n";
1079 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1])
1080 << '\t' << TAI->getCommentString()
1081 << " long double most significant halfword\n";
1083 EmitZeros(TD->getTypePaddedSize(Type::X86_FP80Ty) -
1084 TD->getTypeStoreSize(Type::X86_FP80Ty), AddrSpace);
1086 } else if (CFP->getType() == Type::PPC_FP128Ty) {
1087 // all long double variants are printed as hex
1088 // api needed to prevent premature destruction
1089 APInt api = CFP->getValueAPF().bitcastToAPInt();
1090 const uint64_t *p = api.getRawData();
1091 if (TD->isBigEndian()) {
1092 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32)
1093 << '\t' << TAI->getCommentString()
1094 << " long double most significant word\n";
1095 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0])
1096 << '\t' << TAI->getCommentString()
1097 << " long double next word\n";
1098 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32)
1099 << '\t' << TAI->getCommentString()
1100 << " long double next word\n";
1101 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1])
1102 << '\t' << TAI->getCommentString()
1103 << " long double least significant word\n";
1105 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1])
1106 << '\t' << TAI->getCommentString()
1107 << " long double least significant word\n";
1108 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32)
1109 << '\t' << TAI->getCommentString()
1110 << " long double next word\n";
1111 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0])
1112 << '\t' << TAI->getCommentString()
1113 << " long double next word\n";
1114 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32)
1115 << '\t' << TAI->getCommentString()
1116 << " long double most significant word\n";
1119 } else assert(0 && "Floating point constant type not handled");
1122 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1123 unsigned AddrSpace) {
1124 const TargetData *TD = TM.getTargetData();
1125 unsigned BitWidth = CI->getBitWidth();
1126 assert(isPowerOf2_32(BitWidth) &&
1127 "Non-power-of-2-sized integers not handled!");
1129 // We don't expect assemblers to support integer data directives
1130 // for more than 64 bits, so we emit the data in at most 64-bit
1131 // quantities at a time.
1132 const uint64_t *RawData = CI->getValue().getRawData();
1133 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1135 if (TD->isBigEndian())
1136 Val = RawData[e - i - 1];
1140 if (TAI->getData64bitsDirective(AddrSpace))
1141 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1142 else if (TD->isBigEndian()) {
1143 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32)
1144 << '\t' << TAI->getCommentString()
1145 << " Double-word most significant word " << Val << '\n';
1146 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val)
1147 << '\t' << TAI->getCommentString()
1148 << " Double-word least significant word " << Val << '\n';
1150 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val)
1151 << '\t' << TAI->getCommentString()
1152 << " Double-word least significant word " << Val << '\n';
1153 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32)
1154 << '\t' << TAI->getCommentString()
1155 << " Double-word most significant word " << Val << '\n';
1160 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1161 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1162 const TargetData *TD = TM.getTargetData();
1163 const Type *type = CV->getType();
1164 unsigned Size = TD->getTypePaddedSize(type);
1166 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1167 EmitZeros(Size, AddrSpace);
1169 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1170 EmitGlobalConstantArray(CVA);
1172 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1173 EmitGlobalConstantStruct(CVS, AddrSpace);
1175 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1176 EmitGlobalConstantFP(CFP, AddrSpace);
1178 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1179 // Small integers are handled below; large integers are handled here.
1181 EmitGlobalConstantLargeInt(CI, AddrSpace);
1184 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1185 EmitGlobalConstantVector(CP);
1189 printDataDirective(type, AddrSpace);
1190 EmitConstantValueOnly(CV);
1191 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1193 CI->getValue().toStringUnsigned(S, 16);
1194 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str();
1199 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1200 // Target doesn't support this yet!
1204 /// PrintSpecial - Print information related to the specified machine instr
1205 /// that is independent of the operand, and may be independent of the instr
1206 /// itself. This can be useful for portably encoding the comment character
1207 /// or other bits of target-specific knowledge into the asmstrings. The
1208 /// syntax used is ${:comment}. Targets can override this to add support
1209 /// for their own strange codes.
1210 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1211 if (!strcmp(Code, "private")) {
1212 O << TAI->getPrivateGlobalPrefix();
1213 } else if (!strcmp(Code, "comment")) {
1214 O << TAI->getCommentString();
1215 } else if (!strcmp(Code, "uid")) {
1216 // Assign a unique ID to this machine instruction.
1217 static const MachineInstr *LastMI = 0;
1218 static const Function *F = 0;
1219 static unsigned Counter = 0U-1;
1221 // Comparing the address of MI isn't sufficient, because machineinstrs may
1222 // be allocated to the same address across functions.
1223 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1225 // If this is a new machine instruction, bump the counter.
1226 if (LastMI != MI || F != ThisF) {
1233 cerr << "Unknown special formatter '" << Code
1234 << "' for machine instr: " << *MI;
1240 /// printInlineAsm - This method formats and prints the specified machine
1241 /// instruction that is an inline asm.
1242 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1243 unsigned NumOperands = MI->getNumOperands();
1245 // Count the number of register definitions.
1246 unsigned NumDefs = 0;
1247 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1249 assert(NumDefs != NumOperands-1 && "No asm string?");
1251 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1253 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1254 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1256 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1257 // These are useful to see where empty asm's wound up.
1258 if (AsmStr[0] == 0) {
1259 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1263 O << TAI->getInlineAsmStart() << "\n\t";
1265 // The variant of the current asmprinter.
1266 int AsmPrinterVariant = TAI->getAssemblerDialect();
1268 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1269 const char *LastEmitted = AsmStr; // One past the last character emitted.
1271 while (*LastEmitted) {
1272 switch (*LastEmitted) {
1274 // Not a special case, emit the string section literally.
1275 const char *LiteralEnd = LastEmitted+1;
1276 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1277 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1279 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1280 O.write(LastEmitted, LiteralEnd-LastEmitted);
1281 LastEmitted = LiteralEnd;
1285 ++LastEmitted; // Consume newline character.
1286 O << '\n'; // Indent code with newline.
1289 ++LastEmitted; // Consume '$' character.
1293 switch (*LastEmitted) {
1294 default: Done = false; break;
1295 case '$': // $$ -> $
1296 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1298 ++LastEmitted; // Consume second '$' character.
1300 case '(': // $( -> same as GCC's { character.
1301 ++LastEmitted; // Consume '(' character.
1302 if (CurVariant != -1) {
1303 cerr << "Nested variants found in inline asm string: '"
1307 CurVariant = 0; // We're in the first variant now.
1310 ++LastEmitted; // consume '|' character.
1311 if (CurVariant == -1)
1312 O << '|'; // this is gcc's behavior for | outside a variant
1314 ++CurVariant; // We're in the next variant.
1316 case ')': // $) -> same as GCC's } char.
1317 ++LastEmitted; // consume ')' character.
1318 if (CurVariant == -1)
1319 O << '}'; // this is gcc's behavior for } outside a variant
1326 bool HasCurlyBraces = false;
1327 if (*LastEmitted == '{') { // ${variable}
1328 ++LastEmitted; // Consume '{' character.
1329 HasCurlyBraces = true;
1332 // If we have ${:foo}, then this is not a real operand reference, it is a
1333 // "magic" string reference, just like in .td files. Arrange to call
1335 if (HasCurlyBraces && *LastEmitted == ':') {
1337 const char *StrStart = LastEmitted;
1338 const char *StrEnd = strchr(StrStart, '}');
1340 cerr << "Unterminated ${:foo} operand in inline asm string: '"
1345 std::string Val(StrStart, StrEnd);
1346 PrintSpecial(MI, Val.c_str());
1347 LastEmitted = StrEnd+1;
1351 const char *IDStart = LastEmitted;
1354 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1355 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1356 cerr << "Bad $ operand number in inline asm string: '"
1360 LastEmitted = IDEnd;
1362 char Modifier[2] = { 0, 0 };
1364 if (HasCurlyBraces) {
1365 // If we have curly braces, check for a modifier character. This
1366 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1367 if (*LastEmitted == ':') {
1368 ++LastEmitted; // Consume ':' character.
1369 if (*LastEmitted == 0) {
1370 cerr << "Bad ${:} expression in inline asm string: '"
1375 Modifier[0] = *LastEmitted;
1376 ++LastEmitted; // Consume modifier character.
1379 if (*LastEmitted != '}') {
1380 cerr << "Bad ${} expression in inline asm string: '"
1384 ++LastEmitted; // Consume '}' character.
1387 if ((unsigned)Val >= NumOperands-1) {
1388 cerr << "Invalid $ operand number in inline asm string: '"
1393 // Okay, we finally have a value number. Ask the target to print this
1395 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1400 // Scan to find the machine operand number for the operand.
1401 for (; Val; --Val) {
1402 if (OpNo >= MI->getNumOperands()) break;
1403 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1404 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1407 if (OpNo >= MI->getNumOperands()) {
1410 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1411 ++OpNo; // Skip over the ID number.
1413 if (Modifier[0]=='l') // labels are target independent
1414 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1415 false, false, false);
1417 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1418 if ((OpFlags & 7) == 4) {
1419 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1420 Modifier[0] ? Modifier : 0);
1422 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1423 Modifier[0] ? Modifier : 0);
1428 cerr << "Invalid operand found in inline asm: '"
1438 O << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1441 /// printImplicitDef - This method prints the specified machine instruction
1442 /// that is an implicit def.
1443 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1444 O << '\t' << TAI->getCommentString() << " implicit-def: "
1445 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1448 /// printLabel - This method prints a local label used by debug and
1449 /// exception handling tables.
1450 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1451 printLabel(MI->getOperand(0).getImm());
1454 void AsmPrinter::printLabel(unsigned Id) const {
1455 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1458 /// printDeclare - This method prints a local variable declaration used by
1460 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1461 /// entry into dwarf table.
1462 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1463 unsigned FI = MI->getOperand(0).getIndex();
1464 GlobalValue *GV = MI->getOperand(1).getGlobal();
1465 DW->RecordVariable(cast<GlobalVariable>(GV), FI);
1468 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1469 /// instruction, using the specified assembler variant. Targets should
1470 /// overried this to format as appropriate.
1471 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1472 unsigned AsmVariant, const char *ExtraCode) {
1473 // Target doesn't support this yet!
1477 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1478 unsigned AsmVariant,
1479 const char *ExtraCode) {
1480 // Target doesn't support this yet!
1484 /// printBasicBlockLabel - This method prints the label for the specified
1485 /// MachineBasicBlock
1486 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1489 bool printComment) const {
1491 unsigned Align = MBB->getAlignment();
1493 EmitAlignment(Log2_32(Align));
1496 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1497 << MBB->getNumber();
1500 if (printComment && MBB->getBasicBlock())
1501 O << '\t' << TAI->getCommentString() << ' '
1502 << MBB->getBasicBlock()->getNameStart();
1505 /// printPICJumpTableSetLabel - This method prints a set label for the
1506 /// specified MachineBasicBlock for a jumptable entry.
1507 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1508 const MachineBasicBlock *MBB) const {
1509 if (!TAI->getSetDirective())
1512 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1513 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1514 printBasicBlockLabel(MBB, false, false, false);
1515 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1516 << '_' << uid << '\n';
1519 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1520 const MachineBasicBlock *MBB) const {
1521 if (!TAI->getSetDirective())
1524 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1525 << getFunctionNumber() << '_' << uid << '_' << uid2
1526 << "_set_" << MBB->getNumber() << ',';
1527 printBasicBlockLabel(MBB, false, false, false);
1528 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1529 << '_' << uid << '_' << uid2 << '\n';
1532 /// printDataDirective - This method prints the asm directive for the
1534 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1535 const TargetData *TD = TM.getTargetData();
1536 switch (type->getTypeID()) {
1537 case Type::IntegerTyID: {
1538 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1540 O << TAI->getData8bitsDirective(AddrSpace);
1541 else if (BitWidth <= 16)
1542 O << TAI->getData16bitsDirective(AddrSpace);
1543 else if (BitWidth <= 32)
1544 O << TAI->getData32bitsDirective(AddrSpace);
1545 else if (BitWidth <= 64) {
1546 assert(TAI->getData64bitsDirective(AddrSpace) &&
1547 "Target cannot handle 64-bit constant exprs!");
1548 O << TAI->getData64bitsDirective(AddrSpace);
1550 assert(0 && "Target cannot handle given data directive width!");
1554 case Type::PointerTyID:
1555 if (TD->getPointerSize() == 8) {
1556 assert(TAI->getData64bitsDirective(AddrSpace) &&
1557 "Target cannot handle 64-bit pointer exprs!");
1558 O << TAI->getData64bitsDirective(AddrSpace);
1559 } else if (TD->getPointerSize() == 2) {
1560 O << TAI->getData16bitsDirective(AddrSpace);
1561 } else if (TD->getPointerSize() == 1) {
1562 O << TAI->getData8bitsDirective(AddrSpace);
1564 O << TAI->getData32bitsDirective(AddrSpace);
1567 case Type::FloatTyID: case Type::DoubleTyID:
1568 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1569 assert (0 && "Should have already output floating point constant.");
1571 assert (0 && "Can't handle printing this type of thing");
1576 void AsmPrinter::printSuffixedName(const char *Name, const char *Suffix,
1577 const char *Prefix) {
1580 O << TAI->getPrivateGlobalPrefix();
1581 if (Prefix) O << Prefix;
1593 void AsmPrinter::printSuffixedName(const std::string &Name, const char* Suffix) {
1594 printSuffixedName(Name.c_str(), Suffix);
1597 void AsmPrinter::printVisibility(const std::string& Name,
1598 unsigned Visibility) const {
1599 if (Visibility == GlobalValue::HiddenVisibility) {
1600 if (const char *Directive = TAI->getHiddenDirective())
1601 O << Directive << Name << '\n';
1602 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1603 if (const char *Directive = TAI->getProtectedDirective())
1604 O << Directive << Name << '\n';
1608 void AsmPrinter::printOffset(int64_t Offset) const {
1611 else if (Offset < 0)
1615 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1616 if (!S->usesMetadata())
1619 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1620 if (GCPI != GCMetadataPrinters.end())
1621 return GCPI->second;
1623 const char *Name = S->getName().c_str();
1625 for (GCMetadataPrinterRegistry::iterator
1626 I = GCMetadataPrinterRegistry::begin(),
1627 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1628 if (strcmp(Name, I->getName()) == 0) {
1629 GCMetadataPrinter *GMP = I->instantiate();
1631 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1635 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";