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/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/Streams.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/ADT/SmallPtrSet.h"
35 AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
37 char AsmPrinter::ID = 0;
38 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
39 const TargetAsmInfo *T)
40 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
43 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
44 return TAI->getTextSection();
48 /// SwitchToTextSection - Switch to the specified text section of the executable
49 /// if we are not already in it!
51 void AsmPrinter::SwitchToTextSection(const char *NewSection,
52 const GlobalValue *GV) {
54 if (GV && GV->hasSection())
55 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
59 // If we're already in this section, we're done.
60 if (CurrentSection == NS) return;
62 // Close the current section, if applicable.
63 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
64 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
68 if (!CurrentSection.empty())
69 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
72 /// SwitchToDataSection - Switch to the specified data section of the executable
73 /// if we are not already in it!
75 void AsmPrinter::SwitchToDataSection(const char *NewSection,
76 const GlobalValue *GV) {
78 if (GV && GV->hasSection())
79 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
83 // If we're already in this section, we're done.
84 if (CurrentSection == NS) return;
86 // Close the current section, if applicable.
87 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
88 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
92 if (!CurrentSection.empty())
93 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
97 bool AsmPrinter::doInitialization(Module &M) {
98 Mang = new Mangler(M, TAI->getGlobalPrefix());
100 if (!M.getModuleInlineAsm().empty())
101 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
102 << M.getModuleInlineAsm()
103 << "\n" << TAI->getCommentString()
104 << " End of file scope inline assembly\n";
106 SwitchToDataSection(""); // Reset back to no section.
108 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
109 MMI->AnalyzeModule(M);
115 bool AsmPrinter::doFinalization(Module &M) {
116 if (TAI->getWeakRefDirective()) {
117 if (!ExtWeakSymbols.empty())
118 SwitchToDataSection("");
120 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
121 e = ExtWeakSymbols.end(); i != e; ++i) {
122 const GlobalValue *GV = *i;
123 std::string Name = Mang->getValueName(GV);
124 O << TAI->getWeakRefDirective() << Name << "\n";
128 if (TAI->getSetDirective()) {
129 if (!M.alias_empty())
130 SwitchToTextSection(TAI->getTextSection());
133 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
135 std::string Name = Mang->getValueName(I);
138 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
139 Target = Mang->getValueName(GV);
141 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
142 O << "\t.globl\t" << Name << "\n";
143 else if (I->hasWeakLinkage())
144 O << TAI->getWeakRefDirective() << Name << "\n";
145 else if (!I->hasInternalLinkage())
146 assert(0 && "Invalid alias linkage");
148 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
150 // If the aliasee has external weak linkage it can be referenced only by
151 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
152 // weak reference in such case.
153 if (GV->hasExternalWeakLinkage())
154 if (TAI->getWeakRefDirective())
155 O << TAI->getWeakRefDirective() << Target << "\n";
157 O << "\t.globl\t" << Target << "\n";
161 delete Mang; Mang = 0;
165 std::string AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
166 assert(MF && "No machine function?");
167 return Mang->makeNameProper(MF->getFunction()->getName() + ".eh",
168 TAI->getGlobalPrefix());
171 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
172 // What's my mangled name?
173 CurrentFnName = Mang->getValueName(MF.getFunction());
174 IncrementFunctionNumber();
177 /// EmitConstantPool - Print to the current output stream assembly
178 /// representations of the constants in the constant pool MCP. This is
179 /// used to print out constants which have been "spilled to memory" by
180 /// the code generator.
182 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
183 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
184 if (CP.empty()) return;
186 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
187 // in special sections.
188 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
189 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
190 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
191 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
192 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
193 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
194 MachineConstantPoolEntry CPE = CP[i];
195 const Type *Ty = CPE.getType();
196 if (TAI->getFourByteConstantSection() &&
197 TM.getTargetData()->getABITypeSize(Ty) == 4)
198 FourByteCPs.push_back(std::make_pair(CPE, i));
199 else if (TAI->getEightByteConstantSection() &&
200 TM.getTargetData()->getABITypeSize(Ty) == 8)
201 EightByteCPs.push_back(std::make_pair(CPE, i));
202 else if (TAI->getSixteenByteConstantSection() &&
203 TM.getTargetData()->getABITypeSize(Ty) == 16)
204 SixteenByteCPs.push_back(std::make_pair(CPE, i));
206 OtherCPs.push_back(std::make_pair(CPE, i));
209 unsigned Alignment = MCP->getConstantPoolAlignment();
210 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
211 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
212 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
214 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
217 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
218 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
219 if (CP.empty()) return;
221 SwitchToDataSection(Section);
222 EmitAlignment(Alignment);
223 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
224 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
225 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
226 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
227 if (CP[i].first.isMachineConstantPoolEntry())
228 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
230 EmitGlobalConstant(CP[i].first.Val.ConstVal);
232 const Type *Ty = CP[i].first.getType();
234 TM.getTargetData()->getABITypeSize(Ty);
235 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
236 // Emit inter-object padding for alignment.
237 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
242 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
243 /// by the current function to the current output stream.
245 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
246 MachineFunction &MF) {
247 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
248 if (JT.empty()) return;
250 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
252 // Pick the directive to use to print the jump table entries, and switch to
253 // the appropriate section.
254 TargetLowering *LoweringInfo = TM.getTargetLowering();
256 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
257 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
258 !JumpTableDataSection) {
259 // In PIC mode, we need to emit the jump table to the same section as the
260 // function body itself, otherwise the label differences won't make sense.
261 // We should also do if the section name is NULL.
262 const Function *F = MF.getFunction();
263 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
265 SwitchToDataSection(JumpTableDataSection);
268 EmitAlignment(Log2_32(MJTI->getAlignment()));
270 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
271 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
273 // If this jump table was deleted, ignore it.
274 if (JTBBs.empty()) continue;
276 // For PIC codegen, if possible we want to use the SetDirective to reduce
277 // the number of relocations the assembler will generate for the jump table.
278 // Set directives are all printed before the jump table itself.
279 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
280 if (TAI->getSetDirective() && IsPic)
281 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
282 if (EmittedSets.insert(JTBBs[ii]))
283 printPICJumpTableSetLabel(i, JTBBs[ii]);
285 // On some targets (e.g. darwin) we want to emit two consequtive labels
286 // before each jump table. The first label is never referenced, but tells
287 // the assembler and linker the extents of the jump table object. The
288 // second label is actually referenced by the code.
289 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
290 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
292 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
293 << '_' << i << ":\n";
295 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
296 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
302 void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
303 const MachineBasicBlock *MBB,
304 unsigned uid) const {
305 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
307 // Use JumpTableDirective otherwise honor the entry size from the jump table
309 const char *JTEntryDirective = TAI->getJumpTableDirective();
310 bool HadJTEntryDirective = JTEntryDirective != NULL;
311 if (!HadJTEntryDirective) {
312 JTEntryDirective = MJTI->getEntrySize() == 4 ?
313 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
316 O << JTEntryDirective << ' ';
318 // If we have emitted set directives for the jump table entries, print
319 // them rather than the entries themselves. If we're emitting PIC, then
320 // emit the table entries as differences between two text section labels.
321 // If we're emitting non-PIC code, then emit the entries as direct
322 // references to the target basic blocks.
324 if (TAI->getSetDirective()) {
325 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
326 << '_' << uid << "_set_" << MBB->getNumber();
328 printBasicBlockLabel(MBB, false, false);
329 // If the arch uses custom Jump Table directives, don't calc relative to
331 if (!HadJTEntryDirective)
332 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
333 << getFunctionNumber() << '_' << uid;
336 printBasicBlockLabel(MBB, false, false);
341 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
342 /// special global used by LLVM. If so, emit it and return true, otherwise
343 /// do nothing and return false.
344 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
345 if (GV->getName() == "llvm.used") {
346 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
347 EmitLLVMUsedList(GV->getInitializer());
351 // Ignore debug and non-emitted data.
352 if (GV->getSection() == "llvm.metadata") return true;
354 if (!GV->hasAppendingLinkage()) return false;
356 assert(GV->hasInitializer() && "Not a special LLVM global!");
358 const TargetData *TD = TM.getTargetData();
359 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
360 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
361 SwitchToDataSection(TAI->getStaticCtorsSection());
362 EmitAlignment(Align, 0);
363 EmitXXStructorList(GV->getInitializer());
367 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
368 SwitchToDataSection(TAI->getStaticDtorsSection());
369 EmitAlignment(Align, 0);
370 EmitXXStructorList(GV->getInitializer());
377 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
378 /// global in the specified llvm.used list as being used with this directive.
379 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
380 const char *Directive = TAI->getUsedDirective();
382 // Should be an array of 'sbyte*'.
383 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
384 if (InitList == 0) return;
386 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
388 EmitConstantValueOnly(InitList->getOperand(i));
393 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
394 /// function pointers, ignoring the init priority.
395 void AsmPrinter::EmitXXStructorList(Constant *List) {
396 // Should be an array of '{ int, void ()* }' structs. The first value is the
397 // init priority, which we ignore.
398 if (!isa<ConstantArray>(List)) return;
399 ConstantArray *InitList = cast<ConstantArray>(List);
400 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
401 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
402 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
404 if (CS->getOperand(1)->isNullValue())
405 return; // Found a null terminator, exit printing.
406 // Emit the function pointer.
407 EmitGlobalConstant(CS->getOperand(1));
411 /// getGlobalLinkName - Returns the asm/link name of of the specified
412 /// global variable. Should be overridden by each target asm printer to
413 /// generate the appropriate value.
414 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
415 std::string LinkName;
417 if (isa<Function>(GV)) {
418 LinkName += TAI->getFunctionAddrPrefix();
419 LinkName += Mang->getValueName(GV);
420 LinkName += TAI->getFunctionAddrSuffix();
422 LinkName += TAI->getGlobalVarAddrPrefix();
423 LinkName += Mang->getValueName(GV);
424 LinkName += TAI->getGlobalVarAddrSuffix();
430 /// EmitExternalGlobal - Emit the external reference to a global variable.
431 /// Should be overridden if an indirect reference should be used.
432 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
433 O << getGlobalLinkName(GV);
438 //===----------------------------------------------------------------------===//
439 /// LEB 128 number encoding.
441 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
442 /// representing an unsigned leb128 value.
443 void AsmPrinter::PrintULEB128(unsigned Value) const {
445 unsigned Byte = Value & 0x7f;
447 if (Value) Byte |= 0x80;
448 O << "0x" << std::hex << Byte << std::dec;
449 if (Value) O << ", ";
453 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
455 unsigned AsmPrinter::SizeULEB128(unsigned Value) {
459 Size += sizeof(int8_t);
464 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
465 /// representing a signed leb128 value.
466 void AsmPrinter::PrintSLEB128(int Value) const {
467 int Sign = Value >> (8 * sizeof(Value) - 1);
471 unsigned Byte = Value & 0x7f;
473 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
474 if (IsMore) Byte |= 0x80;
475 O << "0x" << std::hex << Byte << std::dec;
476 if (IsMore) O << ", ";
480 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
482 unsigned AsmPrinter::SizeSLEB128(int Value) {
484 int Sign = Value >> (8 * sizeof(Value) - 1);
488 unsigned Byte = Value & 0x7f;
490 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
491 Size += sizeof(int8_t);
496 //===--------------------------------------------------------------------===//
497 // Emission and print routines
500 /// PrintHex - Print a value as a hexidecimal value.
502 void AsmPrinter::PrintHex(int Value) const {
503 O << "0x" << std::hex << Value << std::dec;
506 /// EOL - Print a newline character to asm stream. If a comment is present
507 /// then it will be printed first. Comments should not contain '\n'.
508 void AsmPrinter::EOL() const {
511 void AsmPrinter::EOL(const std::string &Comment) const {
512 if (AsmVerbose && !Comment.empty()) {
514 << TAI->getCommentString()
521 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
522 /// unsigned leb128 value.
523 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
524 if (TAI->hasLEB128()) {
528 O << TAI->getData8bitsDirective();
533 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
534 /// signed leb128 value.
535 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
536 if (TAI->hasLEB128()) {
540 O << TAI->getData8bitsDirective();
545 /// EmitInt8 - Emit a byte directive and value.
547 void AsmPrinter::EmitInt8(int Value) const {
548 O << TAI->getData8bitsDirective();
549 PrintHex(Value & 0xFF);
552 /// EmitInt16 - Emit a short directive and value.
554 void AsmPrinter::EmitInt16(int Value) const {
555 O << TAI->getData16bitsDirective();
556 PrintHex(Value & 0xFFFF);
559 /// EmitInt32 - Emit a long directive and value.
561 void AsmPrinter::EmitInt32(int Value) const {
562 O << TAI->getData32bitsDirective();
566 /// EmitInt64 - Emit a long long directive and value.
568 void AsmPrinter::EmitInt64(uint64_t Value) const {
569 if (TAI->getData64bitsDirective()) {
570 O << TAI->getData64bitsDirective();
573 if (TM.getTargetData()->isBigEndian()) {
574 EmitInt32(unsigned(Value >> 32)); O << "\n";
575 EmitInt32(unsigned(Value));
577 EmitInt32(unsigned(Value)); O << "\n";
578 EmitInt32(unsigned(Value >> 32));
583 /// toOctal - Convert the low order bits of X into an octal digit.
585 static inline char toOctal(int X) {
589 /// printStringChar - Print a char, escaped if necessary.
591 static void printStringChar(std::ostream &O, unsigned char C) {
594 } else if (C == '\\') {
596 } else if (isprint(C)) {
600 case '\b': O << "\\b"; break;
601 case '\f': O << "\\f"; break;
602 case '\n': O << "\\n"; break;
603 case '\r': O << "\\r"; break;
604 case '\t': O << "\\t"; break;
607 O << toOctal(C >> 6);
608 O << toOctal(C >> 3);
609 O << toOctal(C >> 0);
615 /// EmitString - Emit a string with quotes and a null terminator.
616 /// Special characters are emitted properly.
617 /// \literal (Eg. '\t') \endliteral
618 void AsmPrinter::EmitString(const std::string &String) const {
619 const char* AscizDirective = TAI->getAscizDirective();
623 O << TAI->getAsciiDirective();
625 for (unsigned i = 0, N = String.size(); i < N; ++i) {
626 unsigned char C = String[i];
627 printStringChar(O, C);
636 /// EmitFile - Emit a .file directive.
637 void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const {
638 O << "\t.file\t" << Number << " \"";
639 for (unsigned i = 0, N = Name.size(); i < N; ++i) {
640 unsigned char C = Name[i];
641 printStringChar(O, C);
647 //===----------------------------------------------------------------------===//
649 // EmitAlignment - Emit an alignment directive to the specified power of
650 // two boundary. For example, if you pass in 3 here, you will get an 8
651 // byte alignment. If a global value is specified, and if that global has
652 // an explicit alignment requested, it will unconditionally override the
653 // alignment request. However, if ForcedAlignBits is specified, this value
654 // has final say: the ultimate alignment will be the max of ForcedAlignBits
655 // and the alignment computed with NumBits and the global.
659 // if (GV && GV->hasalignment) Align = GV->getalignment();
660 // Align = std::max(Align, ForcedAlignBits);
662 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
663 unsigned ForcedAlignBits, bool UseFillExpr,
664 unsigned FillValue) const {
665 if (GV && GV->getAlignment())
666 NumBits = Log2_32(GV->getAlignment());
667 NumBits = std::max(NumBits, ForcedAlignBits);
669 if (NumBits == 0) return; // No need to emit alignment.
670 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
671 O << TAI->getAlignDirective() << NumBits;
672 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
677 /// EmitZeros - Emit a block of zeros.
679 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
681 if (TAI->getZeroDirective()) {
682 O << TAI->getZeroDirective() << NumZeros;
683 if (TAI->getZeroDirectiveSuffix())
684 O << TAI->getZeroDirectiveSuffix();
687 for (; NumZeros; --NumZeros)
688 O << TAI->getData8bitsDirective() << "0\n";
693 // Print out the specified constant, without a storage class. Only the
694 // constants valid in constant expressions can occur here.
695 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
696 if (CV->isNullValue() || isa<UndefValue>(CV))
698 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
699 O << CI->getZExtValue();
700 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
701 // This is a constant address for a global variable or function. Use the
702 // name of the variable or function as the address value, possibly
703 // decorating it with GlobalVarAddrPrefix/Suffix or
704 // FunctionAddrPrefix/Suffix (these all default to "" )
705 if (isa<Function>(GV)) {
706 O << TAI->getFunctionAddrPrefix()
707 << Mang->getValueName(GV)
708 << TAI->getFunctionAddrSuffix();
710 O << TAI->getGlobalVarAddrPrefix()
711 << Mang->getValueName(GV)
712 << TAI->getGlobalVarAddrSuffix();
714 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
715 const TargetData *TD = TM.getTargetData();
716 unsigned Opcode = CE->getOpcode();
718 case Instruction::GetElementPtr: {
719 // generate a symbolic expression for the byte address
720 const Constant *ptrVal = CE->getOperand(0);
721 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
722 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
726 EmitConstantValueOnly(ptrVal);
728 O << ") + " << Offset;
730 O << ") - " << -Offset;
732 EmitConstantValueOnly(ptrVal);
736 case Instruction::Trunc:
737 case Instruction::ZExt:
738 case Instruction::SExt:
739 case Instruction::FPTrunc:
740 case Instruction::FPExt:
741 case Instruction::UIToFP:
742 case Instruction::SIToFP:
743 case Instruction::FPToUI:
744 case Instruction::FPToSI:
745 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
747 case Instruction::BitCast:
748 return EmitConstantValueOnly(CE->getOperand(0));
750 case Instruction::IntToPtr: {
751 // Handle casts to pointers by changing them into casts to the appropriate
752 // integer type. This promotes constant folding and simplifies this code.
753 Constant *Op = CE->getOperand(0);
754 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
755 return EmitConstantValueOnly(Op);
759 case Instruction::PtrToInt: {
760 // Support only foldable casts to/from pointers that can be eliminated by
761 // changing the pointer to the appropriately sized integer type.
762 Constant *Op = CE->getOperand(0);
763 const Type *Ty = CE->getType();
765 // We can emit the pointer value into this slot if the slot is an
766 // integer slot greater or equal to the size of the pointer.
767 if (Ty->isInteger() &&
768 TD->getABITypeSize(Ty) >= TD->getABITypeSize(Op->getType()))
769 return EmitConstantValueOnly(Op);
771 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
772 EmitConstantValueOnly(Op);
775 case Instruction::Add:
776 case Instruction::Sub:
777 case Instruction::And:
778 case Instruction::Or:
779 case Instruction::Xor:
781 EmitConstantValueOnly(CE->getOperand(0));
784 case Instruction::Add:
787 case Instruction::Sub:
790 case Instruction::And:
793 case Instruction::Or:
796 case Instruction::Xor:
803 EmitConstantValueOnly(CE->getOperand(1));
807 assert(0 && "Unsupported operator!");
810 assert(0 && "Unknown constant value!");
814 /// printAsCString - Print the specified array as a C compatible string, only if
815 /// the predicate isString is true.
817 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
819 assert(CVA->isString() && "Array is not string compatible!");
822 for (unsigned i = 0; i != LastElt; ++i) {
824 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
825 printStringChar(O, C);
830 /// EmitString - Emit a zero-byte-terminated string constant.
832 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
833 unsigned NumElts = CVA->getNumOperands();
834 if (TAI->getAscizDirective() && NumElts &&
835 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
836 O << TAI->getAscizDirective();
837 printAsCString(O, CVA, NumElts-1);
839 O << TAI->getAsciiDirective();
840 printAsCString(O, CVA, NumElts);
845 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
846 /// If Packed is false, pad to the ABI size.
847 void AsmPrinter::EmitGlobalConstant(const Constant *CV, bool Packed) {
848 const TargetData *TD = TM.getTargetData();
849 unsigned Size = Packed ?
850 TD->getTypeStoreSize(CV->getType()) : TD->getABITypeSize(CV->getType());
852 if (CV->isNullValue() || isa<UndefValue>(CV)) {
855 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
856 if (CVA->isString()) {
858 } else { // Not a string. Print the values in successive locations
859 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
860 EmitGlobalConstant(CVA->getOperand(i), false);
863 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
864 // Print the fields in successive locations. Pad to align if needed!
865 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
866 uint64_t sizeSoFar = 0;
867 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
868 const Constant* field = CVS->getOperand(i);
870 // Check if padding is needed and insert one or more 0s.
871 uint64_t fieldSize = TD->getTypeStoreSize(field->getType());
872 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
873 - cvsLayout->getElementOffset(i)) - fieldSize;
874 sizeSoFar += fieldSize + padSize;
876 // Now print the actual field value without ABI size padding.
877 EmitGlobalConstant(field, true);
879 // Insert padding - this may include padding to increase the size of the
880 // current field up to the ABI size (if the struct is not packed) as well
881 // as padding to ensure that the next field starts at the right offset.
884 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
885 "Layout of constant struct may be incorrect!");
887 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
888 // FP Constants are printed as integer constants to avoid losing
890 if (CFP->getType() == Type::DoubleTy) {
891 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
892 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
893 if (TAI->getData64bitsDirective())
894 O << TAI->getData64bitsDirective() << i << "\t"
895 << TAI->getCommentString() << " double value: " << Val << "\n";
896 else if (TD->isBigEndian()) {
897 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
898 << "\t" << TAI->getCommentString()
899 << " double most significant word " << Val << "\n";
900 O << TAI->getData32bitsDirective() << unsigned(i)
901 << "\t" << TAI->getCommentString()
902 << " double least significant word " << Val << "\n";
904 O << TAI->getData32bitsDirective() << unsigned(i)
905 << "\t" << TAI->getCommentString()
906 << " double least significant word " << Val << "\n";
907 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
908 << "\t" << TAI->getCommentString()
909 << " double most significant word " << Val << "\n";
912 } else if (CFP->getType() == Type::FloatTy) {
913 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
914 O << TAI->getData32bitsDirective()
915 << CFP->getValueAPF().convertToAPInt().getZExtValue()
916 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
918 } else if (CFP->getType() == Type::X86_FP80Ty) {
919 // all long double variants are printed as hex
920 // api needed to prevent premature destruction
921 APInt api = CFP->getValueAPF().convertToAPInt();
922 const uint64_t *p = api.getRawData();
923 if (TD->isBigEndian()) {
924 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
925 << "\t" << TAI->getCommentString()
926 << " long double most significant halfword\n";
927 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
928 << "\t" << TAI->getCommentString()
929 << " long double next halfword\n";
930 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
931 << "\t" << TAI->getCommentString()
932 << " long double next halfword\n";
933 O << TAI->getData16bitsDirective() << uint16_t(p[0])
934 << "\t" << TAI->getCommentString()
935 << " long double next halfword\n";
936 O << TAI->getData16bitsDirective() << uint16_t(p[1])
937 << "\t" << TAI->getCommentString()
938 << " long double least significant halfword\n";
940 O << TAI->getData16bitsDirective() << uint16_t(p[1])
941 << "\t" << TAI->getCommentString()
942 << " long double least significant halfword\n";
943 O << TAI->getData16bitsDirective() << uint16_t(p[0])
944 << "\t" << TAI->getCommentString()
945 << " long double next halfword\n";
946 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
947 << "\t" << TAI->getCommentString()
948 << " long double next halfword\n";
949 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
950 << "\t" << TAI->getCommentString()
951 << " long double next halfword\n";
952 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
953 << "\t" << TAI->getCommentString()
954 << " long double most significant halfword\n";
956 EmitZeros(Size - TD->getTypeStoreSize(Type::X86_FP80Ty));
958 } else if (CFP->getType() == Type::PPC_FP128Ty) {
959 // all long double variants are printed as hex
960 // api needed to prevent premature destruction
961 APInt api = CFP->getValueAPF().convertToAPInt();
962 const uint64_t *p = api.getRawData();
963 if (TD->isBigEndian()) {
964 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
965 << "\t" << TAI->getCommentString()
966 << " long double most significant word\n";
967 O << TAI->getData32bitsDirective() << uint32_t(p[0])
968 << "\t" << TAI->getCommentString()
969 << " long double next word\n";
970 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
971 << "\t" << TAI->getCommentString()
972 << " long double next word\n";
973 O << TAI->getData32bitsDirective() << uint32_t(p[1])
974 << "\t" << TAI->getCommentString()
975 << " long double least significant word\n";
977 O << TAI->getData32bitsDirective() << uint32_t(p[1])
978 << "\t" << TAI->getCommentString()
979 << " long double least significant word\n";
980 O << TAI->getData32bitsDirective() << uint32_t(p[1] >> 32)
981 << "\t" << TAI->getCommentString()
982 << " long double next word\n";
983 O << TAI->getData32bitsDirective() << uint32_t(p[0])
984 << "\t" << TAI->getCommentString()
985 << " long double next word\n";
986 O << TAI->getData32bitsDirective() << uint32_t(p[0] >> 32)
987 << "\t" << TAI->getCommentString()
988 << " long double most significant word\n";
991 } else assert(0 && "Floating point constant type not handled");
992 } else if (CV->getType() == Type::Int64Ty) {
993 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
994 uint64_t Val = CI->getZExtValue();
996 if (TAI->getData64bitsDirective())
997 O << TAI->getData64bitsDirective() << Val << "\n";
998 else if (TD->isBigEndian()) {
999 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1000 << "\t" << TAI->getCommentString()
1001 << " Double-word most significant word " << Val << "\n";
1002 O << TAI->getData32bitsDirective() << unsigned(Val)
1003 << "\t" << TAI->getCommentString()
1004 << " Double-word least significant word " << Val << "\n";
1006 O << TAI->getData32bitsDirective() << unsigned(Val)
1007 << "\t" << TAI->getCommentString()
1008 << " Double-word least significant word " << Val << "\n";
1009 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
1010 << "\t" << TAI->getCommentString()
1011 << " Double-word most significant word " << Val << "\n";
1015 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1016 const VectorType *PTy = CP->getType();
1018 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
1019 EmitGlobalConstant(CP->getOperand(I), false);
1024 const Type *type = CV->getType();
1025 printDataDirective(type);
1026 EmitConstantValueOnly(CV);
1031 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1032 // Target doesn't support this yet!
1036 /// PrintSpecial - Print information related to the specified machine instr
1037 /// that is independent of the operand, and may be independent of the instr
1038 /// itself. This can be useful for portably encoding the comment character
1039 /// or other bits of target-specific knowledge into the asmstrings. The
1040 /// syntax used is ${:comment}. Targets can override this to add support
1041 /// for their own strange codes.
1042 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
1043 if (!strcmp(Code, "private")) {
1044 O << TAI->getPrivateGlobalPrefix();
1045 } else if (!strcmp(Code, "comment")) {
1046 O << TAI->getCommentString();
1047 } else if (!strcmp(Code, "uid")) {
1048 // Assign a unique ID to this machine instruction.
1049 static const MachineInstr *LastMI = 0;
1050 static const Function *F = 0;
1051 static unsigned Counter = 0U-1;
1053 // Comparing the address of MI isn't sufficient, because machineinstrs may
1054 // be allocated to the same address across functions.
1055 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1057 // If this is a new machine instruction, bump the counter.
1058 if (LastMI != MI || F != ThisF) {
1065 cerr << "Unknown special formatter '" << Code
1066 << "' for machine instr: " << *MI;
1072 /// printInlineAsm - This method formats and prints the specified machine
1073 /// instruction that is an inline asm.
1074 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1075 unsigned NumOperands = MI->getNumOperands();
1077 // Count the number of register definitions.
1078 unsigned NumDefs = 0;
1079 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
1081 assert(NumDefs != NumOperands-1 && "No asm string?");
1083 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1085 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1086 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1088 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
1089 if (AsmStr[0] == 0) {
1090 O << "\n"; // Tab already printed, avoid double indenting next instr.
1094 O << TAI->getInlineAsmStart() << "\n\t";
1096 // The variant of the current asmprinter.
1097 int AsmPrinterVariant = TAI->getAssemblerDialect();
1099 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1100 const char *LastEmitted = AsmStr; // One past the last character emitted.
1102 while (*LastEmitted) {
1103 switch (*LastEmitted) {
1105 // Not a special case, emit the string section literally.
1106 const char *LiteralEnd = LastEmitted+1;
1107 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1108 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1110 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1111 O.write(LastEmitted, LiteralEnd-LastEmitted);
1112 LastEmitted = LiteralEnd;
1116 ++LastEmitted; // Consume newline character.
1117 O << "\n"; // Indent code with newline.
1120 ++LastEmitted; // Consume '$' character.
1124 switch (*LastEmitted) {
1125 default: Done = false; break;
1126 case '$': // $$ -> $
1127 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1129 ++LastEmitted; // Consume second '$' character.
1131 case '(': // $( -> same as GCC's { character.
1132 ++LastEmitted; // Consume '(' character.
1133 if (CurVariant != -1) {
1134 cerr << "Nested variants found in inline asm string: '"
1138 CurVariant = 0; // We're in the first variant now.
1141 ++LastEmitted; // consume '|' character.
1142 if (CurVariant == -1) {
1143 cerr << "Found '|' character outside of variant in inline asm "
1144 << "string: '" << AsmStr << "'\n";
1147 ++CurVariant; // We're in the next variant.
1149 case ')': // $) -> same as GCC's } char.
1150 ++LastEmitted; // consume ')' character.
1151 if (CurVariant == -1) {
1152 cerr << "Found '}' character outside of variant in inline asm "
1153 << "string: '" << AsmStr << "'\n";
1161 bool HasCurlyBraces = false;
1162 if (*LastEmitted == '{') { // ${variable}
1163 ++LastEmitted; // Consume '{' character.
1164 HasCurlyBraces = true;
1167 const char *IDStart = LastEmitted;
1170 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1171 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1172 cerr << "Bad $ operand number in inline asm string: '"
1176 LastEmitted = IDEnd;
1178 char Modifier[2] = { 0, 0 };
1180 if (HasCurlyBraces) {
1181 // If we have curly braces, check for a modifier character. This
1182 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1183 if (*LastEmitted == ':') {
1184 ++LastEmitted; // Consume ':' character.
1185 if (*LastEmitted == 0) {
1186 cerr << "Bad ${:} expression in inline asm string: '"
1191 Modifier[0] = *LastEmitted;
1192 ++LastEmitted; // Consume modifier character.
1195 if (*LastEmitted != '}') {
1196 cerr << "Bad ${} expression in inline asm string: '"
1200 ++LastEmitted; // Consume '}' character.
1203 if ((unsigned)Val >= NumOperands-1) {
1204 cerr << "Invalid $ operand number in inline asm string: '"
1209 // Okay, we finally have a value number. Ask the target to print this
1211 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1216 // Scan to find the machine operand number for the operand.
1217 for (; Val; --Val) {
1218 if (OpNo >= MI->getNumOperands()) break;
1219 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1220 OpNo += (OpFlags >> 3) + 1;
1223 if (OpNo >= MI->getNumOperands()) {
1226 unsigned OpFlags = MI->getOperand(OpNo).getImm();
1227 ++OpNo; // Skip over the ID number.
1229 if (Modifier[0]=='l') // labels are target independent
1230 printBasicBlockLabel(MI->getOperand(OpNo).getMBB(),
1233 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1234 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1235 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1236 Modifier[0] ? Modifier : 0);
1238 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1239 Modifier[0] ? Modifier : 0);
1244 cerr << "Invalid operand found in inline asm: '"
1254 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1257 /// printLabel - This method prints a local label used by debug and
1258 /// exception handling tables.
1259 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1260 O << "\n" << TAI->getPrivateGlobalPrefix()
1261 << "label" << MI->getOperand(0).getImm() << ":\n";
1264 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1265 /// instruction, using the specified assembler variant. Targets should
1266 /// overried this to format as appropriate.
1267 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1268 unsigned AsmVariant, const char *ExtraCode) {
1269 // Target doesn't support this yet!
1273 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1274 unsigned AsmVariant,
1275 const char *ExtraCode) {
1276 // Target doesn't support this yet!
1280 /// printBasicBlockLabel - This method prints the label for the specified
1281 /// MachineBasicBlock
1282 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1284 bool printComment) const {
1285 O << TAI->getPrivateGlobalPrefix() << "BB" << getFunctionNumber() << "_"
1286 << MBB->getNumber();
1289 if (printComment && MBB->getBasicBlock())
1290 O << '\t' << TAI->getCommentString() << ' '
1291 << MBB->getBasicBlock()->getName();
1294 /// printPICJumpTableSetLabel - This method prints a set label for the
1295 /// specified MachineBasicBlock for a jumptable entry.
1296 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1297 const MachineBasicBlock *MBB) const {
1298 if (!TAI->getSetDirective())
1301 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1302 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1303 printBasicBlockLabel(MBB, false, false);
1304 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1305 << '_' << uid << '\n';
1308 void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1309 const MachineBasicBlock *MBB) const {
1310 if (!TAI->getSetDirective())
1313 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1314 << getFunctionNumber() << '_' << uid << '_' << uid2
1315 << "_set_" << MBB->getNumber() << ',';
1316 printBasicBlockLabel(MBB, false, false);
1317 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1318 << '_' << uid << '_' << uid2 << '\n';
1321 /// printDataDirective - This method prints the asm directive for the
1323 void AsmPrinter::printDataDirective(const Type *type) {
1324 const TargetData *TD = TM.getTargetData();
1325 switch (type->getTypeID()) {
1326 case Type::IntegerTyID: {
1327 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1329 O << TAI->getData8bitsDirective();
1330 else if (BitWidth <= 16)
1331 O << TAI->getData16bitsDirective();
1332 else if (BitWidth <= 32)
1333 O << TAI->getData32bitsDirective();
1334 else if (BitWidth <= 64) {
1335 assert(TAI->getData64bitsDirective() &&
1336 "Target cannot handle 64-bit constant exprs!");
1337 O << TAI->getData64bitsDirective();
1341 case Type::PointerTyID:
1342 if (TD->getPointerSize() == 8) {
1343 assert(TAI->getData64bitsDirective() &&
1344 "Target cannot handle 64-bit pointer exprs!");
1345 O << TAI->getData64bitsDirective();
1347 O << TAI->getData32bitsDirective();
1350 case Type::FloatTyID: case Type::DoubleTyID:
1351 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
1352 assert (0 && "Should have already output floating point constant.");
1354 assert (0 && "Can't handle printing this type of thing");