1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file 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/Support/CommandLine.h"
22 #include "llvm/Support/Mangler.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/Streams.h"
25 #include "llvm/Target/TargetAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
33 AsmVerbose("asm-verbose", cl::Hidden, cl::desc("Add comments to directives."));
35 char AsmPrinter::ID = 0;
36 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
37 const TargetAsmInfo *T)
38 : MachineFunctionPass((intptr_t)&ID), FunctionNumber(0), O(o), TM(tm), TAI(T)
41 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
42 return TAI->getTextSection();
46 /// SwitchToTextSection - Switch to the specified text section of the executable
47 /// if we are not already in it!
49 void AsmPrinter::SwitchToTextSection(const char *NewSection,
50 const GlobalValue *GV) {
52 if (GV && GV->hasSection())
53 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
57 // If we're already in this section, we're done.
58 if (CurrentSection == NS) return;
60 // Close the current section, if applicable.
61 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
62 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
66 if (!CurrentSection.empty())
67 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
70 /// SwitchToDataSection - Switch to the specified data section of the executable
71 /// if we are not already in it!
73 void AsmPrinter::SwitchToDataSection(const char *NewSection,
74 const GlobalValue *GV) {
76 if (GV && GV->hasSection())
77 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
81 // If we're already in this section, we're done.
82 if (CurrentSection == NS) return;
84 // Close the current section, if applicable.
85 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
86 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
90 if (!CurrentSection.empty())
91 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
95 bool AsmPrinter::doInitialization(Module &M) {
96 Mang = new Mangler(M, TAI->getGlobalPrefix());
98 if (!M.getModuleInlineAsm().empty())
99 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
100 << M.getModuleInlineAsm()
101 << "\n" << TAI->getCommentString()
102 << " End of file scope inline assembly\n";
104 SwitchToDataSection(""); // Reset back to no section.
106 if (MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>()) {
107 MMI->AnalyzeModule(M);
113 bool AsmPrinter::doFinalization(Module &M) {
114 if (TAI->getWeakRefDirective()) {
115 if (!ExtWeakSymbols.empty())
116 SwitchToDataSection("");
118 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
119 e = ExtWeakSymbols.end(); i != e; ++i) {
120 const GlobalValue *GV = *i;
121 std::string Name = Mang->getValueName(GV);
122 O << TAI->getWeakRefDirective() << Name << "\n";
126 if (TAI->getSetDirective()) {
127 if (!M.alias_empty())
128 SwitchToTextSection(TAI->getTextSection());
131 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
133 std::string Name = Mang->getValueName(I);
136 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
137 Target = Mang->getValueName(GV);
139 if (I->hasExternalLinkage() || !TAI->getWeakRefDirective())
140 O << "\t.globl\t" << Name << "\n";
141 else if (I->hasWeakLinkage())
142 O << TAI->getWeakRefDirective() << Name << "\n";
143 else if (!I->hasInternalLinkage())
144 assert(0 && "Invalid alias linkage");
146 O << TAI->getSetDirective() << Name << ", " << Target << "\n";
148 // If the aliasee has external weak linkage it can be referenced only by
149 // alias itself. In this case it can be not in ExtWeakSymbols list. Emit
150 // weak reference in such case.
151 if (GV->hasExternalWeakLinkage())
152 if (TAI->getWeakRefDirective())
153 O << TAI->getWeakRefDirective() << Target << "\n";
155 O << "\t.globl\t" << Target << "\n";
159 delete Mang; Mang = 0;
164 AsmPrinter::getCurrentFunctionEHName(const MachineFunction *MF) {
165 assert(MF && "No machine function?");
166 if (CurrentFnEHName != "") return CurrentFnEHName;
167 return CurrentFnEHName =
168 Mang->makeNameProper(MF->getFunction()->getName() + ".eh",
169 TAI->getGlobalPrefix());
172 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
173 // What's my mangled name?
174 CurrentFnName = Mang->getValueName(MF.getFunction());
175 IncrementFunctionNumber();
178 /// EmitConstantPool - Print to the current output stream assembly
179 /// representations of the constants in the constant pool MCP. This is
180 /// used to print out constants which have been "spilled to memory" by
181 /// the code generator.
183 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
184 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
185 if (CP.empty()) return;
187 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
188 // in special sections.
189 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
190 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
191 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
192 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
193 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
194 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
195 MachineConstantPoolEntry CPE = CP[i];
196 const Type *Ty = CPE.getType();
197 if (TAI->getFourByteConstantSection() &&
198 TM.getTargetData()->getTypeSize(Ty) == 4)
199 FourByteCPs.push_back(std::make_pair(CPE, i));
200 else if (TAI->getEightByteConstantSection() &&
201 TM.getTargetData()->getTypeSize(Ty) == 8)
202 EightByteCPs.push_back(std::make_pair(CPE, i));
203 else if (TAI->getSixteenByteConstantSection() &&
204 TM.getTargetData()->getTypeSize(Ty) == 16)
205 SixteenByteCPs.push_back(std::make_pair(CPE, i));
207 OtherCPs.push_back(std::make_pair(CPE, i));
210 unsigned Alignment = MCP->getConstantPoolAlignment();
211 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
212 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
213 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
215 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
218 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
219 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
220 if (CP.empty()) return;
222 SwitchToDataSection(Section);
223 EmitAlignment(Alignment);
224 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
225 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
226 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
227 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
228 if (CP[i].first.isMachineConstantPoolEntry())
229 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
231 EmitGlobalConstant(CP[i].first.Val.ConstVal);
233 const Type *Ty = CP[i].first.getType();
235 TM.getTargetData()->getTypeSize(Ty);
236 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
237 // Emit inter-object padding for alignment.
238 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
243 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
244 /// by the current function to the current output stream.
246 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
247 MachineFunction &MF) {
248 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
249 if (JT.empty()) return;
250 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
252 // Use JumpTableDirective otherwise honor the entry size from the jump table
254 const char *JTEntryDirective = TAI->getJumpTableDirective();
255 bool HadJTEntryDirective = JTEntryDirective != NULL;
256 if (!HadJTEntryDirective) {
257 JTEntryDirective = MJTI->getEntrySize() == 4 ?
258 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
261 // Pick the directive to use to print the jump table entries, and switch to
262 // the appropriate section.
263 TargetLowering *LoweringInfo = TM.getTargetLowering();
265 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
266 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
267 !JumpTableDataSection) {
268 // In PIC mode, we need to emit the jump table to the same section as the
269 // function body itself, otherwise the label differences won't make sense.
270 // We should also do if the section name is NULL.
271 const Function *F = MF.getFunction();
272 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
274 SwitchToDataSection(JumpTableDataSection);
277 EmitAlignment(Log2_32(MJTI->getAlignment()));
279 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
280 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
282 // If this jump table was deleted, ignore it.
283 if (JTBBs.empty()) continue;
285 // For PIC codegen, if possible we want to use the SetDirective to reduce
286 // the number of relocations the assembler will generate for the jump table.
287 // Set directives are all printed before the jump table itself.
288 std::set<MachineBasicBlock*> EmittedSets;
289 if (TAI->getSetDirective() && IsPic)
290 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
291 if (EmittedSets.insert(JTBBs[ii]).second)
292 printSetLabel(i, JTBBs[ii]);
294 // On some targets (e.g. darwin) we want to emit two consequtive labels
295 // before each jump table. The first label is never referenced, but tells
296 // the assembler and linker the extents of the jump table object. The
297 // second label is actually referenced by the code.
298 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
299 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
301 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
302 << '_' << i << ":\n";
304 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
305 O << JTEntryDirective << ' ';
306 // If we have emitted set directives for the jump table entries, print
307 // them rather than the entries themselves. If we're emitting PIC, then
308 // emit the table entries as differences between two text section labels.
309 // If we're emitting non-PIC code, then emit the entries as direct
310 // references to the target basic blocks.
311 if (!EmittedSets.empty()) {
312 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
313 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
315 printBasicBlockLabel(JTBBs[ii], false, false);
316 // If the arch uses custom Jump Table directives, don't calc relative to
318 if (!HadJTEntryDirective)
319 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
320 << getFunctionNumber() << '_' << i;
322 printBasicBlockLabel(JTBBs[ii], false, false);
329 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
330 /// special global used by LLVM. If so, emit it and return true, otherwise
331 /// do nothing and return false.
332 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
333 if (GV->getName() == "llvm.used") {
334 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
335 EmitLLVMUsedList(GV->getInitializer());
339 // Ignore debug and non-emitted data.
340 if (GV->getSection() == "llvm.metadata") return true;
342 if (!GV->hasAppendingLinkage()) return false;
344 assert(GV->hasInitializer() && "Not a special LLVM global!");
346 const TargetData *TD = TM.getTargetData();
347 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
348 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
349 SwitchToDataSection(TAI->getStaticCtorsSection());
350 EmitAlignment(Align, 0);
351 EmitXXStructorList(GV->getInitializer());
355 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
356 SwitchToDataSection(TAI->getStaticDtorsSection());
357 EmitAlignment(Align, 0);
358 EmitXXStructorList(GV->getInitializer());
365 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
366 /// global in the specified llvm.used list as being used with this directive.
367 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
368 const char *Directive = TAI->getUsedDirective();
370 // Should be an array of 'sbyte*'.
371 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
372 if (InitList == 0) return;
374 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
376 EmitConstantValueOnly(InitList->getOperand(i));
381 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
382 /// function pointers, ignoring the init priority.
383 void AsmPrinter::EmitXXStructorList(Constant *List) {
384 // Should be an array of '{ int, void ()* }' structs. The first value is the
385 // init priority, which we ignore.
386 if (!isa<ConstantArray>(List)) return;
387 ConstantArray *InitList = cast<ConstantArray>(List);
388 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
389 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
390 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
392 if (CS->getOperand(1)->isNullValue())
393 return; // Found a null terminator, exit printing.
394 // Emit the function pointer.
395 EmitGlobalConstant(CS->getOperand(1));
399 /// getGlobalLinkName - Returns the asm/link name of of the specified
400 /// global variable. Should be overridden by each target asm printer to
401 /// generate the appropriate value.
402 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
403 std::string LinkName;
405 if (isa<Function>(GV)) {
406 LinkName += TAI->getFunctionAddrPrefix();
407 LinkName += Mang->getValueName(GV);
408 LinkName += TAI->getFunctionAddrSuffix();
410 LinkName += TAI->getGlobalVarAddrPrefix();
411 LinkName += Mang->getValueName(GV);
412 LinkName += TAI->getGlobalVarAddrSuffix();
418 /// EmitExternalGlobal - Emit the external reference to a global variable.
419 /// Should be overridden if an indirect reference should be used.
420 void AsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
421 O << getGlobalLinkName(GV);
426 //===----------------------------------------------------------------------===//
427 /// LEB 128 number encoding.
429 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
430 /// representing an unsigned leb128 value.
431 void AsmPrinter::PrintULEB128(unsigned Value) const {
433 unsigned Byte = Value & 0x7f;
435 if (Value) Byte |= 0x80;
436 O << "0x" << std::hex << Byte << std::dec;
437 if (Value) O << ", ";
441 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
443 unsigned AsmPrinter::SizeULEB128(unsigned Value) {
447 Size += sizeof(int8_t);
452 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
453 /// representing a signed leb128 value.
454 void AsmPrinter::PrintSLEB128(int Value) const {
455 int Sign = Value >> (8 * sizeof(Value) - 1);
459 unsigned Byte = Value & 0x7f;
461 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
462 if (IsMore) Byte |= 0x80;
463 O << "0x" << std::hex << Byte << std::dec;
464 if (IsMore) O << ", ";
468 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
470 unsigned AsmPrinter::SizeSLEB128(int Value) {
472 int Sign = Value >> (8 * sizeof(Value) - 1);
476 unsigned Byte = Value & 0x7f;
478 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
479 Size += sizeof(int8_t);
484 //===--------------------------------------------------------------------===//
485 // Emission and print routines
488 /// PrintHex - Print a value as a hexidecimal value.
490 void AsmPrinter::PrintHex(int Value) const {
491 O << "0x" << std::hex << Value << std::dec;
494 /// EOL - Print a newline character to asm stream. If a comment is present
495 /// then it will be printed first. Comments should not contain '\n'.
496 void AsmPrinter::EOL() const {
499 void AsmPrinter::EOL(const std::string &Comment) const {
500 if (AsmVerbose && !Comment.empty()) {
502 << TAI->getCommentString()
509 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
510 /// unsigned leb128 value.
511 void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
512 if (TAI->hasLEB128()) {
516 O << TAI->getData8bitsDirective();
521 /// EmitSLEB128Bytes - print an assembler byte data directive to compose a
522 /// signed leb128 value.
523 void AsmPrinter::EmitSLEB128Bytes(int Value) const {
524 if (TAI->hasLEB128()) {
528 O << TAI->getData8bitsDirective();
533 /// EmitInt8 - Emit a byte directive and value.
535 void AsmPrinter::EmitInt8(int Value) const {
536 O << TAI->getData8bitsDirective();
537 PrintHex(Value & 0xFF);
540 /// EmitInt16 - Emit a short directive and value.
542 void AsmPrinter::EmitInt16(int Value) const {
543 O << TAI->getData16bitsDirective();
544 PrintHex(Value & 0xFFFF);
547 /// EmitInt32 - Emit a long directive and value.
549 void AsmPrinter::EmitInt32(int Value) const {
550 O << TAI->getData32bitsDirective();
554 /// EmitInt64 - Emit a long long directive and value.
556 void AsmPrinter::EmitInt64(uint64_t Value) const {
557 if (TAI->getData64bitsDirective()) {
558 O << TAI->getData64bitsDirective();
561 if (TM.getTargetData()->isBigEndian()) {
562 EmitInt32(unsigned(Value >> 32)); O << "\n";
563 EmitInt32(unsigned(Value));
565 EmitInt32(unsigned(Value)); O << "\n";
566 EmitInt32(unsigned(Value >> 32));
571 /// toOctal - Convert the low order bits of X into an octal digit.
573 static inline char toOctal(int X) {
577 /// printStringChar - Print a char, escaped if necessary.
579 static void printStringChar(std::ostream &O, unsigned char C) {
582 } else if (C == '\\') {
584 } else if (isprint(C)) {
588 case '\b': O << "\\b"; break;
589 case '\f': O << "\\f"; break;
590 case '\n': O << "\\n"; break;
591 case '\r': O << "\\r"; break;
592 case '\t': O << "\\t"; break;
595 O << toOctal(C >> 6);
596 O << toOctal(C >> 3);
597 O << toOctal(C >> 0);
603 /// EmitString - Emit a string with quotes and a null terminator.
604 /// Special characters are emitted properly.
605 /// \literal (Eg. '\t') \endliteral
606 void AsmPrinter::EmitString(const std::string &String) const {
607 const char* AscizDirective = TAI->getAscizDirective();
611 O << TAI->getAsciiDirective();
613 for (unsigned i = 0, N = String.size(); i < N; ++i) {
614 unsigned char C = String[i];
615 printStringChar(O, C);
624 //===----------------------------------------------------------------------===//
626 // EmitAlignment - Emit an alignment directive to the specified power of
627 // two boundary. For example, if you pass in 3 here, you will get an 8
628 // byte alignment. If a global value is specified, and if that global has
629 // an explicit alignment requested, it will unconditionally override the
630 // alignment request. However, if ForcedAlignBits is specified, this value
631 // has final say: the ultimate alignment will be the max of ForcedAlignBits
632 // and the alignment computed with NumBits and the global.
636 // if (GV && GV->hasalignment) Align = GV->getalignment();
637 // Align = std::max(Align, ForcedAlignBits);
639 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
640 unsigned ForcedAlignBits, bool UseFillExpr,
641 unsigned FillValue) const {
642 if (GV && GV->getAlignment())
643 NumBits = Log2_32(GV->getAlignment());
644 NumBits = std::max(NumBits, ForcedAlignBits);
646 if (NumBits == 0) return; // No need to emit alignment.
647 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
648 O << TAI->getAlignDirective() << NumBits;
649 if (UseFillExpr) O << ",0x" << std::hex << FillValue << std::dec;
654 /// EmitZeros - Emit a block of zeros.
656 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
658 if (TAI->getZeroDirective()) {
659 O << TAI->getZeroDirective() << NumZeros;
660 if (TAI->getZeroDirectiveSuffix())
661 O << TAI->getZeroDirectiveSuffix();
664 for (; NumZeros; --NumZeros)
665 O << TAI->getData8bitsDirective() << "0\n";
670 // Print out the specified constant, without a storage class. Only the
671 // constants valid in constant expressions can occur here.
672 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
673 if (CV->isNullValue() || isa<UndefValue>(CV))
675 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
676 O << CI->getZExtValue();
677 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
678 // This is a constant address for a global variable or function. Use the
679 // name of the variable or function as the address value, possibly
680 // decorating it with GlobalVarAddrPrefix/Suffix or
681 // FunctionAddrPrefix/Suffix (these all default to "" )
682 if (isa<Function>(GV)) {
683 O << TAI->getFunctionAddrPrefix()
684 << Mang->getValueName(GV)
685 << TAI->getFunctionAddrSuffix();
687 O << TAI->getGlobalVarAddrPrefix()
688 << Mang->getValueName(GV)
689 << TAI->getGlobalVarAddrSuffix();
691 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
692 const TargetData *TD = TM.getTargetData();
693 unsigned Opcode = CE->getOpcode();
695 case Instruction::GetElementPtr: {
696 // generate a symbolic expression for the byte address
697 const Constant *ptrVal = CE->getOperand(0);
698 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
699 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
703 EmitConstantValueOnly(ptrVal);
705 O << ") + " << Offset;
707 O << ") - " << -Offset;
709 EmitConstantValueOnly(ptrVal);
713 case Instruction::Trunc:
714 case Instruction::ZExt:
715 case Instruction::SExt:
716 case Instruction::FPTrunc:
717 case Instruction::FPExt:
718 case Instruction::UIToFP:
719 case Instruction::SIToFP:
720 case Instruction::FPToUI:
721 case Instruction::FPToSI:
722 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
724 case Instruction::BitCast:
725 return EmitConstantValueOnly(CE->getOperand(0));
727 case Instruction::IntToPtr: {
728 // Handle casts to pointers by changing them into casts to the appropriate
729 // integer type. This promotes constant folding and simplifies this code.
730 Constant *Op = CE->getOperand(0);
731 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
732 return EmitConstantValueOnly(Op);
736 case Instruction::PtrToInt: {
737 // Support only foldable casts to/from pointers that can be eliminated by
738 // changing the pointer to the appropriately sized integer type.
739 Constant *Op = CE->getOperand(0);
740 const Type *Ty = CE->getType();
742 // We can emit the pointer value into this slot if the slot is an
743 // integer slot greater or equal to the size of the pointer.
744 if (Ty->isInteger() &&
745 TD->getTypeSize(Ty) >= TD->getTypeSize(Op->getType()))
746 return EmitConstantValueOnly(Op);
748 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
749 EmitConstantValueOnly(Op);
752 case Instruction::Add:
753 case Instruction::Sub:
755 EmitConstantValueOnly(CE->getOperand(0));
756 O << (Opcode==Instruction::Add ? ") + (" : ") - (");
757 EmitConstantValueOnly(CE->getOperand(1));
761 assert(0 && "Unsupported operator!");
764 assert(0 && "Unknown constant value!");
768 /// printAsCString - Print the specified array as a C compatible string, only if
769 /// the predicate isString is true.
771 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
773 assert(CVA->isString() && "Array is not string compatible!");
776 for (unsigned i = 0; i != LastElt; ++i) {
778 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
779 printStringChar(O, C);
784 /// EmitString - Emit a zero-byte-terminated string constant.
786 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
787 unsigned NumElts = CVA->getNumOperands();
788 if (TAI->getAscizDirective() && NumElts &&
789 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
790 O << TAI->getAscizDirective();
791 printAsCString(O, CVA, NumElts-1);
793 O << TAI->getAsciiDirective();
794 printAsCString(O, CVA, NumElts);
799 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
801 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
802 const TargetData *TD = TM.getTargetData();
804 if (CV->isNullValue() || isa<UndefValue>(CV)) {
805 EmitZeros(TD->getTypeSize(CV->getType()));
807 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
808 if (CVA->isString()) {
810 } else { // Not a string. Print the values in successive locations
811 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
812 EmitGlobalConstant(CVA->getOperand(i));
815 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
816 // Print the fields in successive locations. Pad to align if needed!
817 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
818 uint64_t sizeSoFar = 0;
819 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
820 const Constant* field = CVS->getOperand(i);
822 // Check if padding is needed and insert one or more 0s.
823 uint64_t fieldSize = TD->getTypeSize(field->getType());
824 uint64_t padSize = ((i == e-1? cvsLayout->getSizeInBytes()
825 : cvsLayout->getElementOffset(i+1))
826 - cvsLayout->getElementOffset(i)) - fieldSize;
827 sizeSoFar += fieldSize + padSize;
829 // Now print the actual field value
830 EmitGlobalConstant(field);
832 // Insert the field padding unless it's zero bytes...
835 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
836 "Layout of constant struct may be incorrect!");
838 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
839 // FP Constants are printed as integer constants to avoid losing
841 if (CFP->getType() == Type::DoubleTy) {
842 double Val = CFP->getValueAPF().convertToDouble(); // for comment only
843 uint64_t i = CFP->getValueAPF().convertToAPInt().getZExtValue();
844 if (TAI->getData64bitsDirective())
845 O << TAI->getData64bitsDirective() << i << "\t"
846 << TAI->getCommentString() << " double value: " << Val << "\n";
847 else if (TD->isBigEndian()) {
848 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
849 << "\t" << TAI->getCommentString()
850 << " double most significant word " << Val << "\n";
851 O << TAI->getData32bitsDirective() << unsigned(i)
852 << "\t" << TAI->getCommentString()
853 << " double least significant word " << Val << "\n";
855 O << TAI->getData32bitsDirective() << unsigned(i)
856 << "\t" << TAI->getCommentString()
857 << " double least significant word " << Val << "\n";
858 O << TAI->getData32bitsDirective() << unsigned(i >> 32)
859 << "\t" << TAI->getCommentString()
860 << " double most significant word " << Val << "\n";
863 } else if (CFP->getType() == Type::FloatTy) {
864 float Val = CFP->getValueAPF().convertToFloat(); // for comment only
865 O << TAI->getData32bitsDirective()
866 << CFP->getValueAPF().convertToAPInt().getZExtValue()
867 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
869 } else if (CFP->getType() == Type::X86_FP80Ty) {
870 // all long double variants are printed as hex
871 const uint64_t *p = CFP->getValueAPF().convertToAPInt().getRawData();
872 if (TD->isBigEndian()) {
873 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
874 << "\t" << TAI->getCommentString()
875 << " long double most significant halfword\n";
876 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
877 << "\t" << TAI->getCommentString()
878 << " long double next halfword\n";
879 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
880 << "\t" << TAI->getCommentString()
881 << " long double next halfword\n";
882 O << TAI->getData16bitsDirective() << uint16_t(p[0])
883 << "\t" << TAI->getCommentString()
884 << " long double next halfword\n";
885 O << TAI->getData16bitsDirective() << uint16_t(p[1])
886 << "\t" << TAI->getCommentString()
887 << " long double least significant halfword\n";
889 O << TAI->getData16bitsDirective() << uint16_t(p[1])
890 << "\t" << TAI->getCommentString()
891 << " long double least significant halfword\n";
892 O << TAI->getData16bitsDirective() << uint16_t(p[0])
893 << "\t" << TAI->getCommentString()
894 << " long double next halfword\n";
895 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 16)
896 << "\t" << TAI->getCommentString()
897 << " long double next halfword\n";
898 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 32)
899 << "\t" << TAI->getCommentString()
900 << " long double next halfword\n";
901 O << TAI->getData16bitsDirective() << uint16_t(p[0] >> 48)
902 << "\t" << TAI->getCommentString()
903 << " long double most significant halfword\n";
906 } else assert(0 && "Floating point constant type not handled");
907 } else if (CV->getType() == Type::Int64Ty) {
908 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
909 uint64_t Val = CI->getZExtValue();
911 if (TAI->getData64bitsDirective())
912 O << TAI->getData64bitsDirective() << Val << "\n";
913 else if (TD->isBigEndian()) {
914 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
915 << "\t" << TAI->getCommentString()
916 << " Double-word most significant word " << Val << "\n";
917 O << TAI->getData32bitsDirective() << unsigned(Val)
918 << "\t" << TAI->getCommentString()
919 << " Double-word least significant word " << Val << "\n";
921 O << TAI->getData32bitsDirective() << unsigned(Val)
922 << "\t" << TAI->getCommentString()
923 << " Double-word least significant word " << Val << "\n";
924 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
925 << "\t" << TAI->getCommentString()
926 << " Double-word most significant word " << Val << "\n";
930 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
931 const VectorType *PTy = CP->getType();
933 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
934 EmitGlobalConstant(CP->getOperand(I));
939 const Type *type = CV->getType();
940 printDataDirective(type);
941 EmitConstantValueOnly(CV);
946 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
947 // Target doesn't support this yet!
951 /// PrintSpecial - Print information related to the specified machine instr
952 /// that is independent of the operand, and may be independent of the instr
953 /// itself. This can be useful for portably encoding the comment character
954 /// or other bits of target-specific knowledge into the asmstrings. The
955 /// syntax used is ${:comment}. Targets can override this to add support
956 /// for their own strange codes.
957 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
958 if (!strcmp(Code, "private")) {
959 O << TAI->getPrivateGlobalPrefix();
960 } else if (!strcmp(Code, "comment")) {
961 O << TAI->getCommentString();
962 } else if (!strcmp(Code, "uid")) {
963 // Assign a unique ID to this machine instruction.
964 static const MachineInstr *LastMI = 0;
965 static const Function *F = 0;
966 static unsigned Counter = 0U-1;
968 // Comparing the address of MI isn't sufficient, because machineinstrs may
969 // be allocated to the same address across functions.
970 const Function *ThisF = MI->getParent()->getParent()->getFunction();
972 // If this is a new machine instruction, bump the counter.
973 if (LastMI != MI || F != ThisF) {
980 cerr << "Unknown special formatter '" << Code
981 << "' for machine instr: " << *MI;
987 /// printInlineAsm - This method formats and prints the specified machine
988 /// instruction that is an inline asm.
989 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
990 unsigned NumOperands = MI->getNumOperands();
992 // Count the number of register definitions.
993 unsigned NumDefs = 0;
994 for (; MI->getOperand(NumDefs).isRegister() && MI->getOperand(NumDefs).isDef();
996 assert(NumDefs != NumOperands-1 && "No asm string?");
998 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
1000 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1001 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1003 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
1004 if (AsmStr[0] == 0) {
1005 O << "\n"; // Tab already printed, avoid double indenting next instr.
1009 O << TAI->getInlineAsmStart() << "\n\t";
1011 // The variant of the current asmprinter.
1012 int AsmPrinterVariant = TAI->getAssemblerDialect();
1014 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1015 const char *LastEmitted = AsmStr; // One past the last character emitted.
1017 while (*LastEmitted) {
1018 switch (*LastEmitted) {
1020 // Not a special case, emit the string section literally.
1021 const char *LiteralEnd = LastEmitted+1;
1022 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1023 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1025 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1026 O.write(LastEmitted, LiteralEnd-LastEmitted);
1027 LastEmitted = LiteralEnd;
1031 ++LastEmitted; // Consume newline character.
1032 O << "\n"; // Indent code with newline.
1035 ++LastEmitted; // Consume '$' character.
1039 switch (*LastEmitted) {
1040 default: Done = false; break;
1041 case '$': // $$ -> $
1042 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1044 ++LastEmitted; // Consume second '$' character.
1046 case '(': // $( -> same as GCC's { character.
1047 ++LastEmitted; // Consume '(' character.
1048 if (CurVariant != -1) {
1049 cerr << "Nested variants found in inline asm string: '"
1053 CurVariant = 0; // We're in the first variant now.
1056 ++LastEmitted; // consume '|' character.
1057 if (CurVariant == -1) {
1058 cerr << "Found '|' character outside of variant in inline asm "
1059 << "string: '" << AsmStr << "'\n";
1062 ++CurVariant; // We're in the next variant.
1064 case ')': // $) -> same as GCC's } char.
1065 ++LastEmitted; // consume ')' character.
1066 if (CurVariant == -1) {
1067 cerr << "Found '}' character outside of variant in inline asm "
1068 << "string: '" << AsmStr << "'\n";
1076 bool HasCurlyBraces = false;
1077 if (*LastEmitted == '{') { // ${variable}
1078 ++LastEmitted; // Consume '{' character.
1079 HasCurlyBraces = true;
1082 const char *IDStart = LastEmitted;
1085 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1086 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
1087 cerr << "Bad $ operand number in inline asm string: '"
1091 LastEmitted = IDEnd;
1093 char Modifier[2] = { 0, 0 };
1095 if (HasCurlyBraces) {
1096 // If we have curly braces, check for a modifier character. This
1097 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1098 if (*LastEmitted == ':') {
1099 ++LastEmitted; // Consume ':' character.
1100 if (*LastEmitted == 0) {
1101 cerr << "Bad ${:} expression in inline asm string: '"
1106 Modifier[0] = *LastEmitted;
1107 ++LastEmitted; // Consume modifier character.
1110 if (*LastEmitted != '}') {
1111 cerr << "Bad ${} expression in inline asm string: '"
1115 ++LastEmitted; // Consume '}' character.
1118 if ((unsigned)Val >= NumOperands-1) {
1119 cerr << "Invalid $ operand number in inline asm string: '"
1124 // Okay, we finally have a value number. Ask the target to print this
1126 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1131 // Scan to find the machine operand number for the operand.
1132 for (; Val; --Val) {
1133 if (OpNo >= MI->getNumOperands()) break;
1134 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1135 OpNo += (OpFlags >> 3) + 1;
1138 if (OpNo >= MI->getNumOperands()) {
1141 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
1142 ++OpNo; // Skip over the ID number.
1144 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
1145 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
1146 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1147 Modifier[0] ? Modifier : 0);
1149 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1150 Modifier[0] ? Modifier : 0);
1154 cerr << "Invalid operand found in inline asm: '"
1164 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
1167 /// printLabel - This method prints a local label used by debug and
1168 /// exception handling tables.
1169 void AsmPrinter::printLabel(const MachineInstr *MI) const {
1171 << TAI->getPrivateGlobalPrefix()
1173 << MI->getOperand(0).getImmedValue()
1177 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1178 /// instruction, using the specified assembler variant. Targets should
1179 /// overried this to format as appropriate.
1180 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1181 unsigned AsmVariant, const char *ExtraCode) {
1182 // Target doesn't support this yet!
1186 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1187 unsigned AsmVariant,
1188 const char *ExtraCode) {
1189 // Target doesn't support this yet!
1193 /// printBasicBlockLabel - This method prints the label for the specified
1194 /// MachineBasicBlock
1195 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
1197 bool printComment) const {
1198 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
1199 << MBB->getNumber();
1202 if (printComment && MBB->getBasicBlock())
1203 O << '\t' << TAI->getCommentString() << ' '
1204 << MBB->getBasicBlock()->getName();
1207 /// printSetLabel - This method prints a set label for the specified
1208 /// MachineBasicBlock
1209 void AsmPrinter::printSetLabel(unsigned uid,
1210 const MachineBasicBlock *MBB) const {
1211 if (!TAI->getSetDirective())
1214 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1215 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
1216 printBasicBlockLabel(MBB, false, false);
1217 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1218 << '_' << uid << '\n';
1221 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
1222 const MachineBasicBlock *MBB) const {
1223 if (!TAI->getSetDirective())
1226 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
1227 << getFunctionNumber() << '_' << uid << '_' << uid2
1228 << "_set_" << MBB->getNumber() << ',';
1229 printBasicBlockLabel(MBB, false, false);
1230 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
1231 << '_' << uid << '_' << uid2 << '\n';
1234 /// printDataDirective - This method prints the asm directive for the
1236 void AsmPrinter::printDataDirective(const Type *type) {
1237 const TargetData *TD = TM.getTargetData();
1238 switch (type->getTypeID()) {
1239 case Type::IntegerTyID: {
1240 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
1242 O << TAI->getData8bitsDirective();
1243 else if (BitWidth <= 16)
1244 O << TAI->getData16bitsDirective();
1245 else if (BitWidth <= 32)
1246 O << TAI->getData32bitsDirective();
1247 else if (BitWidth <= 64) {
1248 assert(TAI->getData64bitsDirective() &&
1249 "Target cannot handle 64-bit constant exprs!");
1250 O << TAI->getData64bitsDirective();
1254 case Type::PointerTyID:
1255 if (TD->getPointerSize() == 8) {
1256 assert(TAI->getData64bitsDirective() &&
1257 "Target cannot handle 64-bit pointer exprs!");
1258 O << TAI->getData64bitsDirective();
1260 O << TAI->getData32bitsDirective();
1263 case Type::FloatTyID: case Type::DoubleTyID:
1264 assert (0 && "Should have already output floating point constant.");
1266 assert (0 && "Can't handle printing this type of thing");