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/Analysis/DebugInfo.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
40 static cl::opt<cl::boolOrDefault>
41 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
42 cl::init(cl::BOU_UNSET));
44 char AsmPrinter::ID = 0;
45 AsmPrinter::AsmPrinter(raw_ostream &o, TargetMachine &tm,
46 const TargetAsmInfo *T, bool VDef)
47 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
48 TM(tm), TAI(T), TRI(tm.getRegisterInfo()),
49 IsInTextSection(false), LastMI(0), LastFn(0), Counter(~0U),
50 PrevDLT(0, ~0U, ~0U) {
53 case cl::BOU_UNSET: VerboseAsm = VDef; break;
54 case cl::BOU_TRUE: VerboseAsm = true; break;
55 case cl::BOU_FALSE: VerboseAsm = false; break;
59 AsmPrinter::~AsmPrinter() {
60 for (gcp_iterator I = GCMetadataPrinters.begin(),
61 E = GCMetadataPrinters.end(); I != E; ++I)
65 /// SwitchToTextSection - Switch to the specified text section of the executable
66 /// if we are not already in it!
68 void AsmPrinter::SwitchToTextSection(const char *NewSection,
69 const GlobalValue *GV) {
71 if (GV && GV->hasSection())
72 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
76 // If we're already in this section, we're done.
77 if (CurrentSection == NS) return;
79 // Close the current section, if applicable.
80 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
81 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
85 if (!CurrentSection.empty())
86 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
88 IsInTextSection = true;
91 /// SwitchToDataSection - Switch to the specified data section of the executable
92 /// if we are not already in it!
94 void AsmPrinter::SwitchToDataSection(const char *NewSection,
95 const GlobalValue *GV) {
97 if (GV && GV->hasSection())
98 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
102 // If we're already in this section, we're done.
103 if (CurrentSection == NS) return;
105 // Close the current section, if applicable.
106 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
107 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
111 if (!CurrentSection.empty())
112 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
114 IsInTextSection = false;
117 /// SwitchToSection - Switch to the specified section of the executable if we
118 /// are not already in it!
119 void AsmPrinter::SwitchToSection(const Section* NS) {
120 const std::string& NewSection = NS->getName();
122 // If we're already in this section, we're done.
123 if (CurrentSection == NewSection) return;
125 // Close the current section, if applicable.
126 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
127 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << '\n';
129 // FIXME: Make CurrentSection a Section* in the future
130 CurrentSection = NewSection;
131 CurrentSection_ = NS;
133 if (!CurrentSection.empty()) {
134 // If section is named we need to switch into it via special '.section'
135 // directive and also append funky flags. Otherwise - section name is just
136 // some magic assembler directive.
138 O << TAI->getSwitchToSectionDirective()
140 << TAI->getSectionFlags(NS->getFlags());
143 O << TAI->getDataSectionStartSuffix() << '\n';
146 IsInTextSection = (NS->getFlags() & SectionFlags::Code);
149 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
150 MachineFunctionPass::getAnalysisUsage(AU);
151 AU.addRequired<GCModuleInfo>();
154 bool AsmPrinter::doInitialization(Module &M) {
155 Mang = new Mangler(M, TAI->getGlobalPrefix(), TAI->getPrivateGlobalPrefix());
157 if (TAI->doesAllowQuotesInName())
158 Mang->setUseQuotes(true);
160 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
161 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
163 if (TAI->hasSingleParameterDotFile()) {
164 /* Very minimal debug info. It is ignored if we emit actual
165 debug info. If we don't, this at helps the user find where
166 a function came from. */
167 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
170 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
171 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
172 MP->beginAssembly(O, *this, *TAI);
174 if (!M.getModuleInlineAsm().empty())
175 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
176 << M.getModuleInlineAsm()
177 << '\n' << TAI->getCommentString()
178 << " End of file scope inline assembly\n";
180 SwitchToDataSection(""); // Reset back to no section.
182 if (TAI->doesSupportDebugInformation() ||
183 TAI->doesSupportExceptionHandling()) {
184 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
186 MMI->AnalyzeModule(M);
187 DW = getAnalysisIfAvailable<DwarfWriter>();
189 DW->BeginModule(&M, MMI, O, this, TAI);
195 bool AsmPrinter::doFinalization(Module &M) {
196 // Emit final debug information.
197 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
200 // If the target wants to know about weak references, print them all.
201 if (TAI->getWeakRefDirective()) {
202 // FIXME: This is not lazy, it would be nice to only print weak references
203 // to stuff that is actually used. Note that doing so would require targets
204 // to notice uses in operands (due to constant exprs etc). This should
205 // happen with the MC stuff eventually.
206 SwitchToDataSection("");
208 // Print out module-level global variables here.
209 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
211 if (I->hasExternalWeakLinkage())
212 O << TAI->getWeakRefDirective() << Mang->getValueName(I) << '\n';
215 for (Module::const_iterator I = M.begin(), E = M.end();
217 if (I->hasExternalWeakLinkage())
218 O << TAI->getWeakRefDirective() << Mang->getValueName(I) << '\n';
222 if (TAI->getSetDirective()) {
223 if (!M.alias_empty())
224 SwitchToSection(TAI->getTextSection());
227 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
229 std::string Name = Mang->getValueName(I);
232 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
233 Target = Mang->getValueName(GV);
235 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
236 O << "\t.globl\t" << Name << '\n';
237 else if (I->hasWeakLinkage())
238 O << TAI->getWeakRefDirective() << Name << '\n';
239 else if (!I->hasLocalLinkage())
240 LLVM_UNREACHABLE("Invalid alias linkage");
242 printVisibility(Name, I->getVisibility());
244 O << TAI->getSetDirective() << ' ' << Name << ", " << Target << '\n';
248 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
249 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
250 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
251 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
252 MP->finishAssembly(O, *this, *TAI);
254 // If we don't have any trampolines, then we don't require stack memory
255 // to be executable. Some targets have a directive to declare this.
256 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
257 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
258 if (TAI->getNonexecutableStackDirective())
259 O << TAI->getNonexecutableStackDirective() << '\n';
261 delete Mang; Mang = 0;
267 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF,
268 std::string &Name) const {
269 assert(MF && "No machine function?");
270 Name = MF->getFunction()->getName();
272 Name = Mang->getValueName(MF->getFunction());
273 Name = Mang->makeNameProper(TAI->getEHGlobalPrefix() +
274 Name + ".eh", TAI->getGlobalPrefix());
278 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
279 // What's my mangled name?
280 CurrentFnName = Mang->getValueName(MF.getFunction());
281 IncrementFunctionNumber();
285 // SectionCPs - Keep track the alignment, constpool entries per Section.
289 SmallVector<unsigned, 4> CPEs;
290 SectionCPs(const Section *s, unsigned a) : S(s), Alignment(a) {};
294 /// EmitConstantPool - Print to the current output stream assembly
295 /// representations of the constants in the constant pool MCP. This is
296 /// used to print out constants which have been "spilled to memory" by
297 /// the code generator.
299 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
300 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
301 if (CP.empty()) return;
303 // Calculate sections for constant pool entries. We collect entries to go into
304 // the same section together to reduce amount of section switch statements.
305 SmallVector<SectionCPs, 4> CPSections;
306 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
307 MachineConstantPoolEntry CPE = CP[i];
308 unsigned Align = CPE.getAlignment();
309 const Section* S = TAI->SelectSectionForMachineConst(CPE.getType());
310 // The number of sections are small, just do a linear search from the
311 // last section to the first.
313 unsigned SecIdx = CPSections.size();
314 while (SecIdx != 0) {
315 if (CPSections[--SecIdx].S == S) {
321 SecIdx = CPSections.size();
322 CPSections.push_back(SectionCPs(S, Align));
325 if (Align > CPSections[SecIdx].Alignment)
326 CPSections[SecIdx].Alignment = Align;
327 CPSections[SecIdx].CPEs.push_back(i);
330 // Now print stuff into the calculated sections.
331 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
332 SwitchToSection(CPSections[i].S);
333 EmitAlignment(Log2_32(CPSections[i].Alignment));
336 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
337 unsigned CPI = CPSections[i].CPEs[j];
338 MachineConstantPoolEntry CPE = CP[CPI];
340 // Emit inter-object padding for alignment.
341 unsigned AlignMask = CPE.getAlignment() - 1;
342 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
343 EmitZeros(NewOffset - Offset);
345 const Type *Ty = CPE.getType();
346 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
348 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
349 << CPI << ":\t\t\t\t\t";
351 O << TAI->getCommentString() << ' ';
352 WriteTypeSymbolic(O, CPE.getType(), 0);
355 if (CPE.isMachineConstantPoolEntry())
356 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
358 EmitGlobalConstant(CPE.Val.ConstVal);
363 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
364 /// by the current function to the current output stream.
366 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
367 MachineFunction &MF) {
368 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
369 if (JT.empty()) return;
371 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
373 // Pick the directive to use to print the jump table entries, and switch to
374 // the appropriate section.
375 TargetLowering *LoweringInfo = TM.getTargetLowering();
377 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
378 const Function *F = MF.getFunction();
379 unsigned SectionFlags = TAI->SectionFlagsForGlobal(F);
380 bool JTInDiffSection = false;
381 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
382 !JumpTableDataSection ||
383 SectionFlags & SectionFlags::Linkonce) {
384 // In PIC mode, we need to emit the jump table to the same section as the
385 // function body itself, otherwise the label differences won't make sense.
386 // We should also do if the section name is NULL or function is declared in
387 // discardable section.
388 SwitchToSection(TAI->SectionForGlobal(F));
390 SwitchToDataSection(JumpTableDataSection);
391 JTInDiffSection = true;
394 EmitAlignment(Log2_32(MJTI->getAlignment()));
396 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
397 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
399 // If this jump table was deleted, ignore it.
400 if (JTBBs.empty()) continue;
402 // For PIC codegen, if possible we want to use the SetDirective to reduce
403 // the number of relocations the assembler will generate for the jump table.
404 // Set directives are all printed before the jump table itself.
405 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
406 if (TAI->getSetDirective() && IsPic)
407 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
408 if (EmittedSets.insert(JTBBs[ii]))
409 printPICJumpTableSetLabel(i, JTBBs[ii]);
411 // On some targets (e.g. darwin) we want to emit two consequtive labels
412 // before each jump table. The first label is never referenced, but tells
413 // the assembler and linker the extents of the jump table object. The
414 // second label is actually referenced by the code.
415 if (JTInDiffSection) {
416 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
417 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
420 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
421 << '_' << i << ":\n";
423 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
424 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
430 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
431 const MachineBasicBlock *MBB,
432 unsigned uid) const {
433 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
435 // Use JumpTableDirective otherwise honor the entry size from the jump table
437 const char *JTEntryDirective = TAI->getJumpTableDirective();
438 bool HadJTEntryDirective = JTEntryDirective != NULL;
439 if (!HadJTEntryDirective) {
440 JTEntryDirective = MJTI->getEntrySize() == 4 ?
441 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
444 O << JTEntryDirective << ' ';
446 // If we have emitted set directives for the jump table entries, print
447 // them rather than the entries themselves. If we're emitting PIC, then
448 // emit the table entries as differences between two text section labels.
449 // If we're emitting non-PIC code, then emit the entries as direct
450 // references to the target basic blocks.
452 if (TAI->getSetDirective()) {
453 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
454 << '_' << uid << "_set_" << MBB->getNumber();
456 printBasicBlockLabel(MBB, false, false, false);
457 // If the arch uses custom Jump Table directives, don't calc relative to
459 if (!HadJTEntryDirective)
460 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
461 << getFunctionNumber() << '_' << uid;
464 printBasicBlockLabel(MBB, false, false, false);
469 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
470 /// special global used by LLVM. If so, emit it and return true, otherwise
471 /// do nothing and return false.
472 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
473 if (GV->getName() == "llvm.used") {
474 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
475 EmitLLVMUsedList(GV->getInitializer());
479 // Ignore debug and non-emitted data.
480 if (GV->getSection() == "llvm.metadata" ||
481 GV->hasAvailableExternallyLinkage())
484 if (!GV->hasAppendingLinkage()) return false;
486 assert(GV->hasInitializer() && "Not a special LLVM global!");
488 const TargetData *TD = TM.getTargetData();
489 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
490 if (GV->getName() == "llvm.global_ctors") {
491 SwitchToDataSection(TAI->getStaticCtorsSection());
492 EmitAlignment(Align, 0);
493 EmitXXStructorList(GV->getInitializer());
497 if (GV->getName() == "llvm.global_dtors") {
498 SwitchToDataSection(TAI->getStaticDtorsSection());
499 EmitAlignment(Align, 0);
500 EmitXXStructorList(GV->getInitializer());
507 /// findGlobalValue - if CV is an expression equivalent to a single
508 /// global value, return that value.
509 const GlobalValue * AsmPrinter::findGlobalValue(const Constant *CV) {
510 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
512 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
513 const TargetData *TD = TM.getTargetData();
514 unsigned Opcode = CE->getOpcode();
516 case Instruction::GetElementPtr: {
517 const Constant *ptrVal = CE->getOperand(0);
518 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
519 if (TD->getIndexedOffset(ptrVal->getType(), &idxVec[0], idxVec.size()))
521 return findGlobalValue(ptrVal);
523 case Instruction::BitCast:
524 return findGlobalValue(CE->getOperand(0));
532 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
533 /// global in the specified llvm.used list for which emitUsedDirectiveFor
534 /// is true, as being used with this directive.
536 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
537 const char *Directive = TAI->getUsedDirective();
539 // Should be an array of 'i8*'.
540 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
541 if (InitList == 0) return;
543 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
544 const GlobalValue *GV = findGlobalValue(InitList->getOperand(i));
545 if (TAI->emitUsedDirectiveFor(GV, Mang)) {
547 EmitConstantValueOnly(InitList->getOperand(i));
553 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
554 /// function pointers, ignoring the init priority.
555 void AsmPrinter::EmitXXStructorList(Constant *List) {
556 // Should be an array of '{ int, void ()* }' structs. The first value is the
557 // init priority, which we ignore.
558 if (!isa<ConstantArray>(List)) return;
559 ConstantArray *InitList = cast<ConstantArray>(List);
560 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
561 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
562 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
564 if (CS->getOperand(1)->isNullValue())
565 return; // Found a null terminator, exit printing.
566 // Emit the function pointer.
567 EmitGlobalConstant(CS->getOperand(1));
571 /// getGlobalLinkName - Returns the asm/link name of of the specified
572 /// global variable. Should be overridden by each target asm printer to
573 /// generate the appropriate value.
574 const std::string &AsmPrinter::getGlobalLinkName(const GlobalVariable *GV,
575 std::string &LinkName) const {
576 if (isa<Function>(GV)) {
577 LinkName += TAI->getFunctionAddrPrefix();
578 LinkName += Mang->getValueName(GV);
579 LinkName += TAI->getFunctionAddrSuffix();
581 LinkName += TAI->getGlobalVarAddrPrefix();
582 LinkName += Mang->getValueName(GV);
583 LinkName += TAI->getGlobalVarAddrSuffix();
589 /// EmitExternalGlobal - Emit the external reference to a global variable.
590 /// Should be overridden if an indirect reference should be used.
591 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
593 O << getGlobalLinkName(GV, GLN);
598 //===----------------------------------------------------------------------===//
599 /// LEB 128 number encoding.
601 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
602 /// representing an unsigned leb128 value.
603 void AsmPrinter::PrintULEB128(unsigned Value) const {
606 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
608 if (Value) Byte |= 0x80;
609 O << "0x" << utohex_buffer(Byte, Buffer+20);
610 if (Value) O << ", ";
614 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
615 /// representing a signed leb128 value.
616 void AsmPrinter::PrintSLEB128(int Value) const {
617 int Sign = Value >> (8 * sizeof(Value) - 1);
622 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
624 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
625 if (IsMore) Byte |= 0x80;
626 O << "0x" << utohex_buffer(Byte, Buffer+20);
627 if (IsMore) O << ", ";
631 //===--------------------------------------------------------------------===//
632 // Emission and print routines
635 /// PrintHex - Print a value as a hexidecimal value.
637 void AsmPrinter::PrintHex(int Value) const {
639 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20);
642 /// EOL - Print a newline character to asm stream. If a comment is present
643 /// then it will be printed first. Comments should not contain '\n'.
644 void AsmPrinter::EOL() const {
648 void AsmPrinter::EOL(const std::string &Comment) const {
649 if (VerboseAsm && !Comment.empty()) {
651 << TAI->getCommentString()
658 void AsmPrinter::EOL(const char* Comment) const {
659 if (VerboseAsm && *Comment) {
661 << TAI->getCommentString()
668 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
669 /// unsigned leb128 value.
670 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
671 if (TAI->hasLEB128()) {
675 O << TAI->getData8bitsDirective();
680 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
681 /// signed leb128 value.
682 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
683 if (TAI->hasLEB128()) {
687 O << TAI->getData8bitsDirective();
692 /// EmitInt8 - Emit a byte directive and value.
694 void AsmPrinter::EmitInt8(int Value) const {
695 O << TAI->getData8bitsDirective();
696 PrintHex(Value & 0xFF);
699 /// EmitInt16 - Emit a short directive and value.
701 void AsmPrinter::EmitInt16(int Value) const {
702 O << TAI->getData16bitsDirective();
703 PrintHex(Value & 0xFFFF);
706 /// EmitInt32 - Emit a long directive and value.
708 void AsmPrinter::EmitInt32(int Value) const {
709 O << TAI->getData32bitsDirective();
713 /// EmitInt64 - Emit a long long directive and value.
715 void AsmPrinter::EmitInt64(uint64_t Value) const {
716 if (TAI->getData64bitsDirective()) {
717 O << TAI->getData64bitsDirective();
720 if (TM.getTargetData()->isBigEndian()) {
721 EmitInt32(unsigned(Value >> 32)); O << '\n';
722 EmitInt32(unsigned(Value));
724 EmitInt32(unsigned(Value)); O << '\n';
725 EmitInt32(unsigned(Value >> 32));
730 /// toOctal - Convert the low order bits of X into an octal digit.
732 static inline char toOctal(int X) {
736 /// printStringChar - Print a char, escaped if necessary.
738 static void printStringChar(raw_ostream &O, unsigned char C) {
741 } else if (C == '\\') {
743 } else if (isprint((unsigned char)C)) {
747 case '\b': O << "\\b"; break;
748 case '\f': O << "\\f"; break;
749 case '\n': O << "\\n"; break;
750 case '\r': O << "\\r"; break;
751 case '\t': O << "\\t"; break;
754 O << toOctal(C >> 6);
755 O << toOctal(C >> 3);
756 O << toOctal(C >> 0);
762 /// EmitString - Emit a string with quotes and a null terminator.
763 /// Special characters are emitted properly.
764 /// \literal (Eg. '\t') \endliteral
765 void AsmPrinter::EmitString(const std::string &String) const {
766 EmitString(String.c_str(), String.size());
769 void AsmPrinter::EmitString(const char *String, unsigned Size) const {
770 const char* AscizDirective = TAI->getAscizDirective();
774 O << TAI->getAsciiDirective();
776 for (unsigned i = 0; i < Size; ++i)
777 printStringChar(O, String[i]);
785 /// EmitFile - Emit a .file directive.
786 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
787 O << "\t.file\t" << Number << " \"";
788 for (unsigned i = 0, N = Name.size(); i < N; ++i)
789 printStringChar(O, Name[i]);
794 //===----------------------------------------------------------------------===//
796 // EmitAlignment - Emit an alignment directive to the specified power of
797 // two boundary. For example, if you pass in 3 here, you will get an 8
798 // byte alignment. If a global value is specified, and if that global has
799 // an explicit alignment requested, it will unconditionally override the
800 // alignment request. However, if ForcedAlignBits is specified, this value
801 // has final say: the ultimate alignment will be the max of ForcedAlignBits
802 // and the alignment computed with NumBits and the global.
806 // if (GV && GV->hasalignment) Align = GV->getalignment();
807 // Align = std::max(Align, ForcedAlignBits);
809 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
810 unsigned ForcedAlignBits,
811 bool UseFillExpr) const {
812 if (GV && GV->getAlignment())
813 NumBits = Log2_32(GV->getAlignment());
814 NumBits = std::max(NumBits, ForcedAlignBits);
816 if (NumBits == 0) return; // No need to emit alignment.
817 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
818 O << TAI->getAlignDirective() << NumBits;
820 unsigned FillValue = TAI->getTextAlignFillValue();
821 UseFillExpr &= IsInTextSection && FillValue;
830 /// EmitZeros - Emit a block of zeros.
832 void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const {
834 if (TAI->getZeroDirective()) {
835 O << TAI->getZeroDirective() << NumZeros;
836 if (TAI->getZeroDirectiveSuffix())
837 O << TAI->getZeroDirectiveSuffix();
840 for (; NumZeros; --NumZeros)
841 O << TAI->getData8bitsDirective(AddrSpace) << "0\n";
846 // Print out the specified constant, without a storage class. Only the
847 // constants valid in constant expressions can occur here.
848 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
849 if (CV->isNullValue() || isa<UndefValue>(CV))
851 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
852 O << CI->getZExtValue();
853 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
854 // This is a constant address for a global variable or function. Use the
855 // name of the variable or function as the address value, possibly
856 // decorating it with GlobalVarAddrPrefix/Suffix or
857 // FunctionAddrPrefix/Suffix (these all default to "" )
858 if (isa<Function>(GV)) {
859 O << TAI->getFunctionAddrPrefix()
860 << Mang->getValueName(GV)
861 << TAI->getFunctionAddrSuffix();
863 O << TAI->getGlobalVarAddrPrefix()
864 << Mang->getValueName(GV)
865 << TAI->getGlobalVarAddrSuffix();
867 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
868 const TargetData *TD = TM.getTargetData();
869 unsigned Opcode = CE->getOpcode();
871 case Instruction::GetElementPtr: {
872 // generate a symbolic expression for the byte address
873 const Constant *ptrVal = CE->getOperand(0);
874 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
875 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
877 // Truncate/sext the offset to the pointer size.
878 if (TD->getPointerSizeInBits() != 64) {
879 int SExtAmount = 64-TD->getPointerSizeInBits();
880 Offset = (Offset << SExtAmount) >> SExtAmount;
885 EmitConstantValueOnly(ptrVal);
887 O << ") + " << Offset;
889 O << ") - " << -Offset;
891 EmitConstantValueOnly(ptrVal);
895 case Instruction::Trunc:
896 case Instruction::ZExt:
897 case Instruction::SExt:
898 case Instruction::FPTrunc:
899 case Instruction::FPExt:
900 case Instruction::UIToFP:
901 case Instruction::SIToFP:
902 case Instruction::FPToUI:
903 case Instruction::FPToSI:
904 LLVM_UNREACHABLE("FIXME: Don't yet support this kind of constant cast expr");
906 case Instruction::BitCast:
907 return EmitConstantValueOnly(CE->getOperand(0));
909 case Instruction::IntToPtr: {
910 // Handle casts to pointers by changing them into casts to the appropriate
911 // integer type. This promotes constant folding and simplifies this code.
912 Constant *Op = CE->getOperand(0);
913 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
914 return EmitConstantValueOnly(Op);
918 case Instruction::PtrToInt: {
919 // Support only foldable casts to/from pointers that can be eliminated by
920 // changing the pointer to the appropriately sized integer type.
921 Constant *Op = CE->getOperand(0);
922 const Type *Ty = CE->getType();
924 // We can emit the pointer value into this slot if the slot is an
925 // integer slot greater or equal to the size of the pointer.
926 if (TD->getTypeAllocSize(Ty) >= TD->getTypeAllocSize(Op->getType()))
927 return EmitConstantValueOnly(Op);
930 EmitConstantValueOnly(Op);
931 APInt ptrMask = APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Ty));
934 ptrMask.toStringUnsigned(S);
935 O << ") & " << S.c_str() << ')';
938 case Instruction::Add:
939 case Instruction::Sub:
940 case Instruction::And:
941 case Instruction::Or:
942 case Instruction::Xor:
944 EmitConstantValueOnly(CE->getOperand(0));
947 case Instruction::Add:
950 case Instruction::Sub:
953 case Instruction::And:
956 case Instruction::Or:
959 case Instruction::Xor:
966 EmitConstantValueOnly(CE->getOperand(1));
970 LLVM_UNREACHABLE("Unsupported operator!");
973 LLVM_UNREACHABLE("Unknown constant value!");
977 /// printAsCString - Print the specified array as a C compatible string, only if
978 /// the predicate isString is true.
980 static void printAsCString(raw_ostream &O, const ConstantArray *CVA,
982 assert(CVA->isString() && "Array is not string compatible!");
985 for (unsigned i = 0; i != LastElt; ++i) {
987 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
988 printStringChar(O, C);
993 /// EmitString - Emit a zero-byte-terminated string constant.
995 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
996 unsigned NumElts = CVA->getNumOperands();
997 if (TAI->getAscizDirective() && NumElts &&
998 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
999 O << TAI->getAscizDirective();
1000 printAsCString(O, CVA, NumElts-1);
1002 O << TAI->getAsciiDirective();
1003 printAsCString(O, CVA, NumElts);
1008 void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
1009 unsigned AddrSpace) {
1010 if (CVA->isString()) {
1012 } else { // Not a string. Print the values in successive locations
1013 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
1014 EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
1018 void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
1019 const VectorType *PTy = CP->getType();
1021 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1022 EmitGlobalConstant(CP->getOperand(I));
1025 void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
1026 unsigned AddrSpace) {
1027 // Print the fields in successive locations. Pad to align if needed!
1028 const TargetData *TD = TM.getTargetData();
1029 unsigned Size = TD->getTypeAllocSize(CVS->getType());
1030 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
1031 uint64_t sizeSoFar = 0;
1032 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
1033 const Constant* field = CVS->getOperand(i);
1035 // Check if padding is needed and insert one or more 0s.
1036 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
1037 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
1038 - cvsLayout->getElementOffset(i)) - fieldSize;
1039 sizeSoFar += fieldSize + padSize;
1041 // Now print the actual field value.
1042 EmitGlobalConstant(field, AddrSpace);
1044 // Insert padding - this may include padding to increase the size of the
1045 // current field up to the ABI size (if the struct is not packed) as well
1046 // as padding to ensure that the next field starts at the right offset.
1047 EmitZeros(padSize, AddrSpace);
1049 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
1050 "Layout of constant struct may be incorrect!");
1053 void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP,
1054 unsigned AddrSpace) {
1055 // FP Constants are printed as integer constants to avoid losing
1057 const TargetData *TD = TM.getTargetData();
1058 if (CFP->getType() == Type::DoubleTy) {
1059 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
1060 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1061 if (TAI->getData64bitsDirective(AddrSpace)) {
1062 O << TAI->getData64bitsDirective(AddrSpace) << i;
1064 O << '\t' << TAI->getCommentString() << " double value: " << Val;
1066 } else if (TD->isBigEndian()) {
1067 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1069 O << '\t' << TAI->getCommentString()
1070 << " double most significant word " << Val;
1072 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1074 O << '\t' << TAI->getCommentString()
1075 << " double least significant word " << Val;
1078 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i);
1080 O << '\t' << TAI->getCommentString()
1081 << " double least significant word " << Val;
1083 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
1085 O << '\t' << TAI->getCommentString()
1086 << " double most significant word " << Val;
1090 } else if (CFP->getType() == Type::FloatTy) {
1091 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
1092 O << TAI->getData32bitsDirective(AddrSpace)
1093 << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1095 O << '\t' << TAI->getCommentString() << " float " << Val;
1098 } else if (CFP->getType() == Type::X86_FP80Ty) {
1099 // all long double variants are printed as hex
1100 // api needed to prevent premature destruction
1101 APInt api = CFP->getValueAPF().bitcastToAPInt();
1102 const uint64_t *p = api.getRawData();
1103 // Convert to double so we can print the approximate val as a comment.
1104 APFloat DoubleVal = CFP->getValueAPF();
1106 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1108 if (TD->isBigEndian()) {
1109 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1111 O << '\t' << TAI->getCommentString()
1112 << " long double most significant halfword of ~"
1113 << DoubleVal.convertToDouble();
1115 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1117 O << '\t' << TAI->getCommentString() << " long double next halfword";
1119 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1121 O << '\t' << TAI->getCommentString() << " long double next halfword";
1123 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1125 O << '\t' << TAI->getCommentString() << " long double next halfword";
1127 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1129 O << '\t' << TAI->getCommentString()
1130 << " long double least significant halfword";
1133 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
1135 O << '\t' << TAI->getCommentString()
1136 << " long double least significant halfword of ~"
1137 << DoubleVal.convertToDouble();
1139 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
1141 O << '\t' << TAI->getCommentString()
1142 << " long double next halfword";
1144 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
1146 O << '\t' << TAI->getCommentString()
1147 << " long double next halfword";
1149 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
1151 O << '\t' << TAI->getCommentString()
1152 << " long double next halfword";
1154 O << TAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
1156 O << '\t' << TAI->getCommentString()
1157 << " long double most significant halfword";
1160 EmitZeros(TD->getTypeAllocSize(Type::X86_FP80Ty) -
1161 TD->getTypeStoreSize(Type::X86_FP80Ty), AddrSpace);
1163 } else if (CFP->getType() == Type::PPC_FP128Ty) {
1164 // all long double variants are printed as hex
1165 // api needed to prevent premature destruction
1166 APInt api = CFP->getValueAPF().bitcastToAPInt();
1167 const uint64_t *p = api.getRawData();
1168 if (TD->isBigEndian()) {
1169 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1171 O << '\t' << TAI->getCommentString()
1172 << " long double most significant word";
1174 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1176 O << '\t' << TAI->getCommentString()
1177 << " long double next word";
1179 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1181 O << '\t' << TAI->getCommentString()
1182 << " long double next word";
1184 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1186 O << '\t' << TAI->getCommentString()
1187 << " long double least significant word";
1190 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
1192 O << '\t' << TAI->getCommentString()
1193 << " long double least significant word";
1195 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
1197 O << '\t' << TAI->getCommentString()
1198 << " long double next word";
1200 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
1202 O << '\t' << TAI->getCommentString()
1203 << " long double next word";
1205 O << TAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
1207 O << '\t' << TAI->getCommentString()
1208 << " long double most significant word";
1212 } else LLVM_UNREACHABLE("Floating point constant type not handled");
1215 void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
1216 unsigned AddrSpace) {
1217 const TargetData *TD = TM.getTargetData();
1218 unsigned BitWidth = CI->getBitWidth();
1219 assert(isPowerOf2_32(BitWidth) &&
1220 "Non-power-of-2-sized integers not handled!");
1222 // We don't expect assemblers to support integer data directives
1223 // for more than 64 bits, so we emit the data in at most 64-bit
1224 // quantities at a time.
1225 const uint64_t *RawData = CI->getValue().getRawData();
1226 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1228 if (TD->isBigEndian())
1229 Val = RawData[e - i - 1];
1233 if (TAI->getData64bitsDirective(AddrSpace))
1234 O << TAI->getData64bitsDirective(AddrSpace) << Val << '\n';
1235 else if (TD->isBigEndian()) {
1236 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1238 O << '\t' << TAI->getCommentString()
1239 << " Double-word most significant word " << Val;
1241 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1243 O << '\t' << TAI->getCommentString()
1244 << " Double-word least significant word " << Val;
1247 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val);
1249 O << '\t' << TAI->getCommentString()
1250 << " Double-word least significant word " << Val;
1252 O << TAI->getData32bitsDirective(AddrSpace) << unsigned(Val >> 32);
1254 O << '\t' << TAI->getCommentString()
1255 << " Double-word most significant word " << Val;
1261 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1262 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1263 const TargetData *TD = TM.getTargetData();
1264 const Type *type = CV->getType();
1265 unsigned Size = TD->getTypeAllocSize(type);
1267 if (CV->isNullValue() || isa<UndefValue>(CV)) {
1268 EmitZeros(Size, AddrSpace);
1270 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
1271 EmitGlobalConstantArray(CVA , AddrSpace);
1273 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
1274 EmitGlobalConstantStruct(CVS, AddrSpace);
1276 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1277 EmitGlobalConstantFP(CFP, AddrSpace);
1279 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1280 // Small integers are handled below; large integers are handled here.
1282 EmitGlobalConstantLargeInt(CI, AddrSpace);
1285 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1286 EmitGlobalConstantVector(CP);
1290 printDataDirective(type, AddrSpace);
1291 EmitConstantValueOnly(CV);
1293 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1295 CI->getValue().toStringUnsigned(S, 16);
1296 O << "\t\t\t" << TAI->getCommentString() << " 0x" << S.c_str();
1302 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1303 // Target doesn't support this yet!
1304 LLVM_UNREACHABLE("Target does not support EmitMachineConstantPoolValue");
1307 /// PrintSpecial - Print information related to the specified machine instr
1308 /// that is independent of the operand, and may be independent of the instr
1309 /// itself. This can be useful for portably encoding the comment character
1310 /// or other bits of target-specific knowledge into the asmstrings. The
1311 /// syntax used is ${:comment}. Targets can override this to add support
1312 /// for their own strange codes.
1313 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
1314 if (!strcmp(Code, "private")) {
1315 O << TAI->getPrivateGlobalPrefix();
1316 } else if (!strcmp(Code, "comment")) {
1318 O << TAI->getCommentString();
1319 } else if (!strcmp(Code, "uid")) {
1320 // Comparing the address of MI isn't sufficient, because machineinstrs may
1321 // be allocated to the same address across functions.
1322 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1324 // If this is a new LastFn instruction, bump the counter.
1325 if (LastMI != MI || LastFn != ThisF) {
1333 raw_string_ostream Msg(msg);
1334 Msg << "Unknown special formatter '" << Code
1335 << "' for machine instr: " << *MI;
1336 llvm_report_error(Msg.str());
1340 /// processDebugLoc - Processes the debug information of each machine
1341 /// instruction's DebugLoc.
1342 void AsmPrinter::processDebugLoc(DebugLoc DL) {
1343 if (TAI->doesSupportDebugInformation() && DW->ShouldEmitDwarfDebug()) {
1344 if (!DL.isUnknown()) {
1345 DebugLocTuple CurDLT = MF->getDebugLocTuple(DL);
1347 if (CurDLT.CompileUnit != 0 && PrevDLT != CurDLT)
1348 printLabel(DW->RecordSourceLine(CurDLT.Line, CurDLT.Col,
1349 DICompileUnit(CurDLT.CompileUnit)));
1356 /// printInlineAsm - This method formats and prints the specified machine
1357 /// instruction that is an inline asm.
1358 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1359 unsigned NumOperands = MI->getNumOperands();
1361 // Count the number of register definitions.
1362 unsigned NumDefs = 0;
1363 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
1365 assert(NumDefs != NumOperands-1 && "No asm string?");
1367 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
1369 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1370 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1372 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1373 // These are useful to see where empty asm's wound up.
1374 if (AsmStr[0] == 0) {
1375 O << TAI->getInlineAsmStart() << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1379 O << TAI->getInlineAsmStart() << "\n\t";
1381 // The variant of the current asmprinter.
1382 int AsmPrinterVariant = TAI->getAssemblerDialect();
1384 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1385 const char *LastEmitted = AsmStr; // One past the last character emitted.
1387 while (*LastEmitted) {
1388 switch (*LastEmitted) {
1390 // Not a special case, emit the string section literally.
1391 const char *LiteralEnd = LastEmitted+1;
1392 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1393 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1395 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1396 O.write(LastEmitted, LiteralEnd-LastEmitted);
1397 LastEmitted = LiteralEnd;
1401 ++LastEmitted; // Consume newline character.
1402 O << '\n'; // Indent code with newline.
1405 ++LastEmitted; // Consume '$' character.
1409 switch (*LastEmitted) {
1410 default: Done = false; break;
1411 case '$': // $$ -> $
1412 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1414 ++LastEmitted; // Consume second '$' character.
1416 case '(': // $( -> same as GCC's { character.
1417 ++LastEmitted; // Consume '(' character.
1418 if (CurVariant != -1) {
1419 llvm_report_error("Nested variants found in inline asm string: '"
1420 + std::string(AsmStr) + "'");
1422 CurVariant = 0; // We're in the first variant now.
1425 ++LastEmitted; // consume '|' character.
1426 if (CurVariant == -1)
1427 O << '|'; // this is gcc's behavior for | outside a variant
1429 ++CurVariant; // We're in the next variant.
1431 case ')': // $) -> same as GCC's } char.
1432 ++LastEmitted; // consume ')' character.
1433 if (CurVariant == -1)
1434 O << '}'; // this is gcc's behavior for } outside a variant
1441 bool HasCurlyBraces = false;
1442 if (*LastEmitted == '{') { // ${variable}
1443 ++LastEmitted; // Consume '{' character.
1444 HasCurlyBraces = true;
1447 // If we have ${:foo}, then this is not a real operand reference, it is a
1448 // "magic" string reference, just like in .td files. Arrange to call
1450 if (HasCurlyBraces && *LastEmitted == ':') {
1452 const char *StrStart = LastEmitted;
1453 const char *StrEnd = strchr(StrStart, '}');
1455 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1456 + std::string(AsmStr) + "'");
1459 std::string Val(StrStart, StrEnd);
1460 PrintSpecial(MI, Val.c_str());
1461 LastEmitted = StrEnd+1;
1465 const char *IDStart = LastEmitted;
1468 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1469 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1470 llvm_report_error("Bad $ operand number in inline asm string: '"
1471 + std::string(AsmStr) + "'");
1473 LastEmitted = IDEnd;
1475 char Modifier[2] = { 0, 0 };
1477 if (HasCurlyBraces) {
1478 // If we have curly braces, check for a modifier character. This
1479 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1480 if (*LastEmitted == ':') {
1481 ++LastEmitted; // Consume ':' character.
1482 if (*LastEmitted == 0) {
1483 llvm_report_error("Bad ${:} expression in inline asm string: '"
1484 + std::string(AsmStr) + "'");
1487 Modifier[0] = *LastEmitted;
1488 ++LastEmitted; // Consume modifier character.
1491 if (*LastEmitted != '}') {
1492 llvm_report_error("Bad ${} expression in inline asm string: '"
1493 + std::string(AsmStr) + "'");
1495 ++LastEmitted; // Consume '}' character.
1498 if ((unsigned)Val >= NumOperands-1) {
1499 llvm_report_error("Invalid $ operand number in inline asm string: '"
1500 + std::string(AsmStr) + "'");
1503 // Okay, we finally have a value number. Ask the target to print this
1505 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1510 // Scan to find the machine operand number for the operand.
1511 for (; Val; --Val) {
1512 if (OpNo >= MI->getNumOperands()) break;
1513 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1514 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
1517 if (OpNo >= MI->getNumOperands()) {
1520 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1521 ++OpNo; // Skip over the ID number.
1523 if (Modifier[0]=='l') // labels are target independent
1524 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1525 false, false, false);
1527 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1528 if ((OpFlags & 7) == 4) {
1529 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1530 Modifier[0] ? Modifier : 0);
1532 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1533 Modifier[0] ? Modifier : 0);
1539 raw_string_ostream Msg(msg);
1540 Msg << "Invalid operand found in inline asm: '"
1543 llvm_report_error(Msg.str());
1550 O << "\n\t" << TAI->getInlineAsmEnd() << '\n';
1553 /// printImplicitDef - This method prints the specified machine instruction
1554 /// that is an implicit def.
1555 void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
1557 O << '\t' << TAI->getCommentString() << " implicit-def: "
1558 << TRI->getAsmName(MI->getOperand(0).getReg()) << '\n';
1561 /// printLabel - This method prints a local label used by debug and
1562 /// exception handling tables.
1563 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1564 printLabel(MI->getOperand(0).getImm());
1567 void AsmPrinter::printLabel(unsigned Id) const {
1568 O << TAI->getPrivateGlobalPrefix() << "label" << Id << ":\n";
1571 /// printDeclare - This method prints a local variable declaration used by
1573 /// FIXME: It doesn't really print anything rather it inserts a DebugVariable
1574 /// entry into dwarf table.
1575 void AsmPrinter::printDeclare(const MachineInstr *MI) const {
1576 unsigned FI = MI->getOperand(0).getIndex();
1577 GlobalValue *GV = MI->getOperand(1).getGlobal();
1578 DW->RecordVariable(cast<GlobalVariable>(GV), FI, MI);
1581 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1582 /// instruction, using the specified assembler variant. Targets should
1583 /// overried this to format as appropriate.
1584 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1585 unsigned AsmVariant, const char *ExtraCode) {
1586 // Target doesn't support this yet!
1590 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1591 unsigned AsmVariant,
1592 const char *ExtraCode) {
1593 // Target doesn't support this yet!
1597 /// printBasicBlockLabel - This method prints the label for the specified
1598 /// MachineBasicBlock
1599 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1602 bool printComment) const {
1604 unsigned Align = MBB->getAlignment();
1606 EmitAlignment(Log2_32(Align));
1609 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << '_'
1610 << MBB->getNumber();
1613 if (printComment && MBB->getBasicBlock())
1614 O << '\t' << TAI->getCommentString() << ' '
1615 << MBB->getBasicBlock()->getNameStart();
1618 /// printPICJumpTableSetLabel - This method prints a set label for the
1619 /// specified MachineBasicBlock for a jumptable entry.
1620 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1621 const MachineBasicBlock *MBB) const {
1622 if (!TAI->getSetDirective())
1625 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1626 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1627 printBasicBlockLabel(MBB, false, false, false);
1628 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1629 << '_' << uid << '\n';
1632 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1633 const MachineBasicBlock *MBB) const {
1634 if (!TAI->getSetDirective())
1637 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1638 << getFunctionNumber() << '_' << uid << '_' << uid2
1639 << "_set_" << MBB->getNumber() << ',';
1640 printBasicBlockLabel(MBB, false, false, false);
1641 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1642 << '_' << uid << '_' << uid2 << '\n';
1645 /// printDataDirective - This method prints the asm directive for the
1647 void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
1648 const TargetData *TD = TM.getTargetData();
1649 switch (type->getTypeID()) {
1650 case Type::IntegerTyID: {
1651 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1653 O << TAI->getData8bitsDirective(AddrSpace);
1654 else if (BitWidth <= 16)
1655 O << TAI->getData16bitsDirective(AddrSpace);
1656 else if (BitWidth <= 32)
1657 O << TAI->getData32bitsDirective(AddrSpace);
1658 else if (BitWidth <= 64) {
1659 assert(TAI->getData64bitsDirective(AddrSpace) &&
1660 "Target cannot handle 64-bit constant exprs!");
1661 O << TAI->getData64bitsDirective(AddrSpace);
1663 LLVM_UNREACHABLE("Target cannot handle given data directive width!");
1667 case Type::PointerTyID:
1668 if (TD->getPointerSize() == 8) {
1669 assert(TAI->getData64bitsDirective(AddrSpace) &&
1670 "Target cannot handle 64-bit pointer exprs!");
1671 O << TAI->getData64bitsDirective(AddrSpace);
1672 } else if (TD->getPointerSize() == 2) {
1673 O << TAI->getData16bitsDirective(AddrSpace);
1674 } else if (TD->getPointerSize() == 1) {
1675 O << TAI->getData8bitsDirective(AddrSpace);
1677 O << TAI->getData32bitsDirective(AddrSpace);
1680 case Type::FloatTyID: case Type::DoubleTyID:
1681 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1682 assert (0 && "Should have already output floating point constant.");
1684 assert (0 && "Can't handle printing this type of thing");
1689 void AsmPrinter::printSuffixedName(const char *Name, const char *Suffix,
1690 const char *Prefix) {
1693 O << TAI->getPrivateGlobalPrefix();
1694 if (Prefix) O << Prefix;
1706 void AsmPrinter::printSuffixedName(const std::string &Name, const char* Suffix) {
1707 printSuffixedName(Name.c_str(), Suffix);
1710 void AsmPrinter::printVisibility(const std::string& Name,
1711 unsigned Visibility) const {
1712 if (Visibility == GlobalValue::HiddenVisibility) {
1713 if (const char *Directive = TAI->getHiddenDirective())
1714 O << Directive << Name << '\n';
1715 } else if (Visibility == GlobalValue::ProtectedVisibility) {
1716 if (const char *Directive = TAI->getProtectedDirective())
1717 O << Directive << Name << '\n';
1721 void AsmPrinter::printOffset(int64_t Offset) const {
1724 else if (Offset < 0)
1728 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1729 if (!S->usesMetadata())
1732 gcp_iterator GCPI = GCMetadataPrinters.find(S);
1733 if (GCPI != GCMetadataPrinters.end())
1734 return GCPI->second;
1736 const char *Name = S->getName().c_str();
1738 for (GCMetadataPrinterRegistry::iterator
1739 I = GCMetadataPrinterRegistry::begin(),
1740 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1741 if (strcmp(Name, I->getName()) == 0) {
1742 GCMetadataPrinter *GMP = I->instantiate();
1744 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1748 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";