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/Mangler.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Streams.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetMachine.h"
31 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
32 const TargetAsmInfo *T)
33 : FunctionNumber(0), O(o), TM(tm), TAI(T)
36 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
37 return TAI->getTextSection();
41 /// SwitchToTextSection - Switch to the specified text section of the executable
42 /// if we are not already in it!
44 void AsmPrinter::SwitchToTextSection(const char *NewSection,
45 const GlobalValue *GV) {
47 if (GV && GV->hasSection())
48 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
52 // If we're already in this section, we're done.
53 if (CurrentSection == NS) return;
55 // Close the current section, if applicable.
56 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
57 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
61 if (!CurrentSection.empty())
62 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
65 /// SwitchToDataSection - Switch to the specified data section of the executable
66 /// if we are not already in it!
68 void AsmPrinter::SwitchToDataSection(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->getDataSectionStartSuffix() << '\n';
90 bool AsmPrinter::doInitialization(Module &M) {
91 Mang = new Mangler(M, TAI->getGlobalPrefix());
93 if (!M.getModuleInlineAsm().empty())
94 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
95 << M.getModuleInlineAsm()
96 << "\n" << TAI->getCommentString()
97 << " End of file scope inline assembly\n";
99 SwitchToDataSection(""); // Reset back to no section.
101 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
102 DebugInfo->AnalyzeModule(M);
108 bool AsmPrinter::doFinalization(Module &M) {
109 if (TAI->getWeakRefDirective()) {
110 if (ExtWeakSymbols.begin() != ExtWeakSymbols.end())
111 SwitchToDataSection("");
113 for (std::set<const GlobalValue*>::iterator i = ExtWeakSymbols.begin(),
114 e = ExtWeakSymbols.end(); i != e; ++i) {
115 const GlobalValue *GV = *i;
116 std::string Name = Mang->getValueName(GV);
117 O << TAI->getWeakRefDirective() << Name << "\n";
121 delete Mang; Mang = 0;
125 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
126 // What's my mangled name?
127 CurrentFnName = Mang->getValueName(MF.getFunction());
128 IncrementFunctionNumber();
131 /// EmitConstantPool - Print to the current output stream assembly
132 /// representations of the constants in the constant pool MCP. This is
133 /// used to print out constants which have been "spilled to memory" by
134 /// the code generator.
136 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
137 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
138 if (CP.empty()) return;
140 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
141 // in special sections.
142 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
143 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
144 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
145 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
146 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
147 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
148 MachineConstantPoolEntry CPE = CP[i];
149 const Type *Ty = CPE.getType();
150 if (TAI->getFourByteConstantSection() &&
151 TM.getTargetData()->getTypeSize(Ty) == 4)
152 FourByteCPs.push_back(std::make_pair(CPE, i));
153 else if (TAI->getEightByteConstantSection() &&
154 TM.getTargetData()->getTypeSize(Ty) == 8)
155 EightByteCPs.push_back(std::make_pair(CPE, i));
156 else if (TAI->getSixteenByteConstantSection() &&
157 TM.getTargetData()->getTypeSize(Ty) == 16)
158 SixteenByteCPs.push_back(std::make_pair(CPE, i));
160 OtherCPs.push_back(std::make_pair(CPE, i));
163 unsigned Alignment = MCP->getConstantPoolAlignment();
164 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
165 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
166 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
168 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
171 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
172 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
173 if (CP.empty()) return;
175 SwitchToDataSection(Section);
176 EmitAlignment(Alignment);
177 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
178 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
179 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
180 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
181 if (CP[i].first.isMachineConstantPoolEntry())
182 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
184 EmitGlobalConstant(CP[i].first.Val.ConstVal);
186 const Type *Ty = CP[i].first.getType();
188 TM.getTargetData()->getTypeSize(Ty);
189 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
190 // Emit inter-object padding for alignment.
191 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
196 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
197 /// by the current function to the current output stream.
199 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
200 MachineFunction &MF) {
201 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
202 if (JT.empty()) return;
203 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
205 // Use JumpTableDirective otherwise honor the entry size from the jump table
207 const char *JTEntryDirective = TAI->getJumpTableDirective();
208 bool HadJTEntryDirective = JTEntryDirective != NULL;
209 if (!HadJTEntryDirective) {
210 JTEntryDirective = MJTI->getEntrySize() == 4 ?
211 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
214 // Pick the directive to use to print the jump table entries, and switch to
215 // the appropriate section.
216 TargetLowering *LoweringInfo = TM.getTargetLowering();
218 const char* JumpTableDataSection = TAI->getJumpTableDataSection();
219 if ((IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) ||
220 !JumpTableDataSection) {
221 // In PIC mode, we need to emit the jump table to the same section as the
222 // function body itself, otherwise the label differences won't make sense.
223 // We should also do if the section name is NULL.
224 const Function *F = MF.getFunction();
225 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
227 SwitchToDataSection(JumpTableDataSection);
230 EmitAlignment(Log2_32(MJTI->getAlignment()));
232 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
233 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
235 // If this jump table was deleted, ignore it.
236 if (JTBBs.empty()) continue;
238 // For PIC codegen, if possible we want to use the SetDirective to reduce
239 // the number of relocations the assembler will generate for the jump table.
240 // Set directives are all printed before the jump table itself.
241 std::set<MachineBasicBlock*> EmittedSets;
242 if (TAI->getSetDirective() && IsPic)
243 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
244 if (EmittedSets.insert(JTBBs[ii]).second)
245 printSetLabel(i, JTBBs[ii]);
247 // On some targets (e.g. darwin) we want to emit two consequtive labels
248 // before each jump table. The first label is never referenced, but tells
249 // the assembler and linker the extents of the jump table object. The
250 // second label is actually referenced by the code.
251 if (const char *JTLabelPrefix = TAI->getJumpTableSpecialLabelPrefix())
252 O << JTLabelPrefix << "JTI" << getFunctionNumber() << '_' << i << ":\n";
254 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
255 << '_' << i << ":\n";
257 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
258 O << JTEntryDirective << ' ';
259 // If we have emitted set directives for the jump table entries, print
260 // them rather than the entries themselves. If we're emitting PIC, then
261 // emit the table entries as differences between two text section labels.
262 // If we're emitting non-PIC code, then emit the entries as direct
263 // references to the target basic blocks.
264 if (!EmittedSets.empty()) {
265 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
266 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
268 printBasicBlockLabel(JTBBs[ii], false, false);
269 // If the arch uses custom Jump Table directives, don't calc relative to
271 if (!HadJTEntryDirective)
272 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
273 << getFunctionNumber() << '_' << i;
275 printBasicBlockLabel(JTBBs[ii], false, false);
282 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
283 /// special global used by LLVM. If so, emit it and return true, otherwise
284 /// do nothing and return false.
285 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
286 // Ignore debug and non-emitted data.
287 if (GV->getSection() == "llvm.metadata") return true;
289 if (!GV->hasAppendingLinkage()) return false;
291 assert(GV->hasInitializer() && "Not a special LLVM global!");
293 if (GV->getName() == "llvm.used") {
294 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
295 EmitLLVMUsedList(GV->getInitializer());
299 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
300 SwitchToDataSection(TAI->getStaticCtorsSection());
302 EmitXXStructorList(GV->getInitializer());
306 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
307 SwitchToDataSection(TAI->getStaticDtorsSection());
309 EmitXXStructorList(GV->getInitializer());
316 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
317 /// global in the specified llvm.used list as being used with this directive.
318 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
319 const char *Directive = TAI->getUsedDirective();
321 // Should be an array of 'sbyte*'.
322 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
323 if (InitList == 0) return;
325 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
327 EmitConstantValueOnly(InitList->getOperand(i));
332 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
333 /// function pointers, ignoring the init priority.
334 void AsmPrinter::EmitXXStructorList(Constant *List) {
335 // Should be an array of '{ int, void ()* }' structs. The first value is the
336 // init priority, which we ignore.
337 if (!isa<ConstantArray>(List)) return;
338 ConstantArray *InitList = cast<ConstantArray>(List);
339 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
340 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
341 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
343 if (CS->getOperand(1)->isNullValue())
344 return; // Found a null terminator, exit printing.
345 // Emit the function pointer.
346 EmitGlobalConstant(CS->getOperand(1));
350 /// getGlobalLinkName - Returns the asm/link name of of the specified
351 /// global variable. Should be overridden by each target asm printer to
352 /// generate the appropriate value.
353 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
354 std::string LinkName;
356 if (isa<Function>(GV)) {
357 LinkName += TAI->getFunctionAddrPrefix();
358 LinkName += Mang->getValueName(GV);
359 LinkName += TAI->getFunctionAddrSuffix();
361 LinkName += TAI->getGlobalVarAddrPrefix();
362 LinkName += Mang->getValueName(GV);
363 LinkName += TAI->getGlobalVarAddrSuffix();
369 // EmitAlignment - Emit an alignment directive to the specified power of two.
370 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
371 if (GV && GV->getAlignment())
372 NumBits = Log2_32(GV->getAlignment());
373 if (NumBits == 0) return; // No need to emit alignment.
374 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
375 O << TAI->getAlignDirective() << NumBits << "\n";
378 /// EmitZeros - Emit a block of zeros.
380 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
382 if (TAI->getZeroDirective()) {
383 O << TAI->getZeroDirective() << NumZeros;
384 if (TAI->getZeroDirectiveSuffix())
385 O << TAI->getZeroDirectiveSuffix();
388 for (; NumZeros; --NumZeros)
389 O << TAI->getData8bitsDirective() << "0\n";
394 // Print out the specified constant, without a storage class. Only the
395 // constants valid in constant expressions can occur here.
396 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
397 if (CV->isNullValue() || isa<UndefValue>(CV))
399 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
400 O << CI->getZExtValue();
401 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
402 // This is a constant address for a global variable or function. Use the
403 // name of the variable or function as the address value, possibly
404 // decorating it with GlobalVarAddrPrefix/Suffix or
405 // FunctionAddrPrefix/Suffix (these all default to "" )
406 if (isa<Function>(GV)) {
407 O << TAI->getFunctionAddrPrefix()
408 << Mang->getValueName(GV)
409 << TAI->getFunctionAddrSuffix();
411 O << TAI->getGlobalVarAddrPrefix()
412 << Mang->getValueName(GV)
413 << TAI->getGlobalVarAddrSuffix();
415 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
416 const TargetData *TD = TM.getTargetData();
417 switch(CE->getOpcode()) {
418 case Instruction::GetElementPtr: {
419 // generate a symbolic expression for the byte address
420 const Constant *ptrVal = CE->getOperand(0);
421 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
422 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
425 EmitConstantValueOnly(ptrVal);
427 O << ") + " << Offset;
429 O << ") - " << -Offset;
431 EmitConstantValueOnly(ptrVal);
435 case Instruction::Trunc:
436 case Instruction::ZExt:
437 case Instruction::SExt:
438 case Instruction::FPTrunc:
439 case Instruction::FPExt:
440 case Instruction::UIToFP:
441 case Instruction::SIToFP:
442 case Instruction::FPToUI:
443 case Instruction::FPToSI:
444 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
446 case Instruction::BitCast:
447 return EmitConstantValueOnly(CE->getOperand(0));
449 case Instruction::IntToPtr: {
450 // Handle casts to pointers by changing them into casts to the appropriate
451 // integer type. This promotes constant folding and simplifies this code.
452 Constant *Op = CE->getOperand(0);
453 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
454 return EmitConstantValueOnly(Op);
458 case Instruction::PtrToInt: {
459 // Support only foldable casts to/from pointers that can be eliminated by
460 // changing the pointer to the appropriately sized integer type.
461 Constant *Op = CE->getOperand(0);
462 const Type *Ty = CE->getType();
464 // We can emit the pointer value into this slot if the slot is an
465 // integer slot greater or equal to the size of the pointer.
466 if (Ty->isInteger() &&
467 TD->getTypeSize(Ty) >= TD->getTypeSize(Op->getType()))
468 return EmitConstantValueOnly(Op);
470 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
471 EmitConstantValueOnly(Op);
474 case Instruction::Add:
476 EmitConstantValueOnly(CE->getOperand(0));
478 EmitConstantValueOnly(CE->getOperand(1));
482 assert(0 && "Unsupported operator!");
485 assert(0 && "Unknown constant value!");
489 /// toOctal - Convert the low order bits of X into an octal digit.
491 static inline char toOctal(int X) {
495 /// printAsCString - Print the specified array as a C compatible string, only if
496 /// the predicate isString is true.
498 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
500 assert(CVA->isString() && "Array is not string compatible!");
503 for (unsigned i = 0; i != LastElt; ++i) {
505 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
509 } else if (C == '\\') {
511 } else if (isprint(C)) {
515 case '\b': O << "\\b"; break;
516 case '\f': O << "\\f"; break;
517 case '\n': O << "\\n"; break;
518 case '\r': O << "\\r"; break;
519 case '\t': O << "\\t"; break;
522 O << toOctal(C >> 6);
523 O << toOctal(C >> 3);
524 O << toOctal(C >> 0);
532 /// EmitString - Emit a zero-byte-terminated string constant.
534 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
535 unsigned NumElts = CVA->getNumOperands();
536 if (TAI->getAscizDirective() && NumElts &&
537 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
538 O << TAI->getAscizDirective();
539 printAsCString(O, CVA, NumElts-1);
541 O << TAI->getAsciiDirective();
542 printAsCString(O, CVA, NumElts);
547 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
549 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
550 const TargetData *TD = TM.getTargetData();
552 if (CV->isNullValue() || isa<UndefValue>(CV)) {
553 EmitZeros(TD->getTypeSize(CV->getType()));
555 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
556 if (CVA->isString()) {
558 } else { // Not a string. Print the values in successive locations
559 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
560 EmitGlobalConstant(CVA->getOperand(i));
563 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
564 // Print the fields in successive locations. Pad to align if needed!
565 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
566 uint64_t sizeSoFar = 0;
567 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
568 const Constant* field = CVS->getOperand(i);
570 // Check if padding is needed and insert one or more 0s.
571 uint64_t fieldSize = TD->getTypeSize(field->getType());
572 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
573 : cvsLayout->MemberOffsets[i+1])
574 - cvsLayout->MemberOffsets[i]) - fieldSize;
575 sizeSoFar += fieldSize + padSize;
577 // Now print the actual field value
578 EmitGlobalConstant(field);
580 // Insert the field padding unless it's zero bytes...
583 assert(sizeSoFar == cvsLayout->StructSize &&
584 "Layout of constant struct may be incorrect!");
586 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
587 // FP Constants are printed as integer constants to avoid losing
589 double Val = CFP->getValue();
590 if (CFP->getType() == Type::DoubleTy) {
591 if (TAI->getData64bitsDirective())
592 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
593 << TAI->getCommentString() << " double value: " << Val << "\n";
594 else if (TD->isBigEndian()) {
595 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
596 << "\t" << TAI->getCommentString()
597 << " double most significant word " << Val << "\n";
598 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
599 << "\t" << TAI->getCommentString()
600 << " double least significant word " << Val << "\n";
602 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
603 << "\t" << TAI->getCommentString()
604 << " double least significant word " << Val << "\n";
605 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
606 << "\t" << TAI->getCommentString()
607 << " double most significant word " << Val << "\n";
611 O << TAI->getData32bitsDirective() << FloatToBits(Val)
612 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
615 } else if (CV->getType() == Type::Int64Ty) {
616 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
617 uint64_t Val = CI->getZExtValue();
619 if (TAI->getData64bitsDirective())
620 O << TAI->getData64bitsDirective() << Val << "\n";
621 else if (TD->isBigEndian()) {
622 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
623 << "\t" << TAI->getCommentString()
624 << " Double-word most significant word " << Val << "\n";
625 O << TAI->getData32bitsDirective() << unsigned(Val)
626 << "\t" << TAI->getCommentString()
627 << " Double-word least significant word " << Val << "\n";
629 O << TAI->getData32bitsDirective() << unsigned(Val)
630 << "\t" << TAI->getCommentString()
631 << " Double-word least significant word " << Val << "\n";
632 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
633 << "\t" << TAI->getCommentString()
634 << " Double-word most significant word " << Val << "\n";
638 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
639 const PackedType *PTy = CP->getType();
641 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
642 EmitGlobalConstant(CP->getOperand(I));
647 const Type *type = CV->getType();
648 printDataDirective(type);
649 EmitConstantValueOnly(CV);
654 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
655 // Target doesn't support this yet!
659 /// PrintSpecial - Print information related to the specified machine instr
660 /// that is independent of the operand, and may be independent of the instr
661 /// itself. This can be useful for portably encoding the comment character
662 /// or other bits of target-specific knowledge into the asmstrings. The
663 /// syntax used is ${:comment}. Targets can override this to add support
664 /// for their own strange codes.
665 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
666 if (!strcmp(Code, "private")) {
667 O << TAI->getPrivateGlobalPrefix();
668 } else if (!strcmp(Code, "comment")) {
669 O << TAI->getCommentString();
670 } else if (!strcmp(Code, "uid")) {
671 // Assign a unique ID to this machine instruction.
672 static const MachineInstr *LastMI = 0;
673 static unsigned Counter = 0U-1;
674 // If this is a new machine instruction, bump the counter.
675 if (LastMI != MI) { ++Counter; LastMI = MI; }
678 cerr << "Unknown special formatter '" << Code
679 << "' for machine instr: " << *MI;
685 /// printInlineAsm - This method formats and prints the specified machine
686 /// instruction that is an inline asm.
687 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
688 unsigned NumOperands = MI->getNumOperands();
690 // Count the number of register definitions.
691 unsigned NumDefs = 0;
692 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
694 assert(NumDefs != NumOperands-1 && "No asm string?");
696 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
698 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
699 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
701 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
702 if (AsmStr[0] == 0) {
703 O << "\n"; // Tab already printed, avoid double indenting next instr.
707 O << TAI->getInlineAsmStart() << "\n\t";
709 // The variant of the current asmprinter.
710 int AsmPrinterVariant = TAI->getAssemblerDialect();
712 int CurVariant = -1; // The number of the {.|.|.} region we are in.
713 const char *LastEmitted = AsmStr; // One past the last character emitted.
715 while (*LastEmitted) {
716 switch (*LastEmitted) {
718 // Not a special case, emit the string section literally.
719 const char *LiteralEnd = LastEmitted+1;
720 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
721 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
723 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
724 O.write(LastEmitted, LiteralEnd-LastEmitted);
725 LastEmitted = LiteralEnd;
729 ++LastEmitted; // Consume newline character.
730 O << "\n\t"; // Indent code with newline.
733 ++LastEmitted; // Consume '$' character.
737 switch (*LastEmitted) {
738 default: Done = false; break;
740 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
742 ++LastEmitted; // Consume second '$' character.
744 case '(': // $( -> same as GCC's { character.
745 ++LastEmitted; // Consume '(' character.
746 if (CurVariant != -1) {
747 cerr << "Nested variants found in inline asm string: '"
751 CurVariant = 0; // We're in the first variant now.
754 ++LastEmitted; // consume '|' character.
755 if (CurVariant == -1) {
756 cerr << "Found '|' character outside of variant in inline asm "
757 << "string: '" << AsmStr << "'\n";
760 ++CurVariant; // We're in the next variant.
762 case ')': // $) -> same as GCC's } char.
763 ++LastEmitted; // consume ')' character.
764 if (CurVariant == -1) {
765 cerr << "Found '}' character outside of variant in inline asm "
766 << "string: '" << AsmStr << "'\n";
774 bool HasCurlyBraces = false;
775 if (*LastEmitted == '{') { // ${variable}
776 ++LastEmitted; // Consume '{' character.
777 HasCurlyBraces = true;
780 const char *IDStart = LastEmitted;
783 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
784 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
785 cerr << "Bad $ operand number in inline asm string: '"
791 char Modifier[2] = { 0, 0 };
793 if (HasCurlyBraces) {
794 // If we have curly braces, check for a modifier character. This
795 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
796 if (*LastEmitted == ':') {
797 ++LastEmitted; // Consume ':' character.
798 if (*LastEmitted == 0) {
799 cerr << "Bad ${:} expression in inline asm string: '"
804 Modifier[0] = *LastEmitted;
805 ++LastEmitted; // Consume modifier character.
808 if (*LastEmitted != '}') {
809 cerr << "Bad ${} expression in inline asm string: '"
813 ++LastEmitted; // Consume '}' character.
816 if ((unsigned)Val >= NumOperands-1) {
817 cerr << "Invalid $ operand number in inline asm string: '"
822 // Okay, we finally have a value number. Ask the target to print this
824 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
829 // Scan to find the machine operand number for the operand.
831 if (OpNo >= MI->getNumOperands()) break;
832 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
833 OpNo += (OpFlags >> 3) + 1;
836 if (OpNo >= MI->getNumOperands()) {
839 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
840 ++OpNo; // Skip over the ID number.
842 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
843 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
844 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
845 Modifier[0] ? Modifier : 0);
847 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
848 Modifier[0] ? Modifier : 0);
852 cerr << "Invalid operand found in inline asm: '"
862 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
865 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
866 /// instruction, using the specified assembler variant. Targets should
867 /// overried this to format as appropriate.
868 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
869 unsigned AsmVariant, const char *ExtraCode) {
870 // Target doesn't support this yet!
874 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
876 const char *ExtraCode) {
877 // Target doesn't support this yet!
881 /// printBasicBlockLabel - This method prints the label for the specified
882 /// MachineBasicBlock
883 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
885 bool printComment) const {
886 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
890 if (printComment && MBB->getBasicBlock())
891 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
894 /// printSetLabel - This method prints a set label for the specified
895 /// MachineBasicBlock
896 void AsmPrinter::printSetLabel(unsigned uid,
897 const MachineBasicBlock *MBB) const {
898 if (!TAI->getSetDirective())
901 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
902 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
903 printBasicBlockLabel(MBB, false, false);
904 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
905 << '_' << uid << '\n';
908 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
909 const MachineBasicBlock *MBB) const {
910 if (!TAI->getSetDirective())
913 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
914 << getFunctionNumber() << '_' << uid << '_' << uid2
915 << "_set_" << MBB->getNumber() << ',';
916 printBasicBlockLabel(MBB, false, false);
917 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
918 << '_' << uid << '_' << uid2 << '\n';
921 /// printDataDirective - This method prints the asm directive for the
923 void AsmPrinter::printDataDirective(const Type *type) {
924 const TargetData *TD = TM.getTargetData();
925 switch (type->getTypeID()) {
926 case Type::IntegerTyID: {
927 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
929 O << TAI->getData8bitsDirective();
930 else if (BitWidth <= 16)
931 O << TAI->getData16bitsDirective();
932 else if (BitWidth <= 32)
933 O << TAI->getData32bitsDirective();
934 else if (BitWidth <= 64) {
935 assert(TAI->getData64bitsDirective() &&
936 "Target cannot handle 64-bit constant exprs!");
937 O << TAI->getData64bitsDirective();
941 case Type::PointerTyID:
942 if (TD->getPointerSize() == 8) {
943 assert(TAI->getData64bitsDirective() &&
944 "Target cannot handle 64-bit pointer exprs!");
945 O << TAI->getData64bitsDirective();
947 O << TAI->getData32bitsDirective();
950 case Type::FloatTyID: case Type::DoubleTyID:
951 assert (0 && "Should have already output floating point constant.");
953 assert (0 && "Can't handle printing this type of thing");