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/Target/TargetAsmInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
30 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm,
31 const TargetAsmInfo *T)
32 : FunctionNumber(0), O(o), TM(tm), TAI(T)
35 std::string AsmPrinter::getSectionForFunction(const Function &F) const {
36 return TAI->getTextSection();
40 /// SwitchToTextSection - Switch to the specified text section of the executable
41 /// if we are not already in it!
43 void AsmPrinter::SwitchToTextSection(const char *NewSection,
44 const GlobalValue *GV) {
46 if (GV && GV->hasSection())
47 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
51 // If we're already in this section, we're done.
52 if (CurrentSection == NS) return;
54 // Close the current section, if applicable.
55 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
56 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
60 if (!CurrentSection.empty())
61 O << CurrentSection << TAI->getTextSectionStartSuffix() << '\n';
64 /// SwitchToDataSection - Switch to the specified data section of the executable
65 /// if we are not already in it!
67 void AsmPrinter::SwitchToDataSection(const char *NewSection,
68 const GlobalValue *GV) {
70 if (GV && GV->hasSection())
71 NS = TAI->getSwitchToSectionDirective() + GV->getSection();
75 // If we're already in this section, we're done.
76 if (CurrentSection == NS) return;
78 // Close the current section, if applicable.
79 if (TAI->getSectionEndDirectiveSuffix() && !CurrentSection.empty())
80 O << CurrentSection << TAI->getSectionEndDirectiveSuffix() << "\n";
84 if (!CurrentSection.empty())
85 O << CurrentSection << TAI->getDataSectionStartSuffix() << '\n';
89 bool AsmPrinter::doInitialization(Module &M) {
90 Mang = new Mangler(M, TAI->getGlobalPrefix());
92 if (!M.getModuleInlineAsm().empty())
93 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
94 << M.getModuleInlineAsm()
95 << "\n" << TAI->getCommentString()
96 << " End of file scope inline assembly\n";
98 SwitchToDataSection("", 0); // Reset back to no section.
100 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
101 DebugInfo->AnalyzeModule(M);
107 bool AsmPrinter::doFinalization(Module &M) {
108 delete Mang; Mang = 0;
112 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
113 // What's my mangled name?
114 CurrentFnName = Mang->getValueName(MF.getFunction());
115 IncrementFunctionNumber();
118 /// EmitConstantPool - Print to the current output stream assembly
119 /// representations of the constants in the constant pool MCP. This is
120 /// used to print out constants which have been "spilled to memory" by
121 /// the code generator.
123 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
124 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
125 if (CP.empty()) return;
127 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
128 // in special sections.
129 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
130 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
131 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
132 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
133 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
134 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
135 MachineConstantPoolEntry CPE = CP[i];
136 const Type *Ty = CPE.getType();
137 if (TAI->getFourByteConstantSection() &&
138 TM.getTargetData()->getTypeSize(Ty) == 4)
139 FourByteCPs.push_back(std::make_pair(CPE, i));
140 else if (TAI->getEightByteConstantSection() &&
141 TM.getTargetData()->getTypeSize(Ty) == 8)
142 EightByteCPs.push_back(std::make_pair(CPE, i));
143 else if (TAI->getSixteenByteConstantSection() &&
144 TM.getTargetData()->getTypeSize(Ty) == 16)
145 SixteenByteCPs.push_back(std::make_pair(CPE, i));
147 OtherCPs.push_back(std::make_pair(CPE, i));
150 unsigned Alignment = MCP->getConstantPoolAlignment();
151 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
152 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
153 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
155 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
158 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
159 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
160 if (CP.empty()) return;
162 SwitchToDataSection(Section, 0);
163 EmitAlignment(Alignment);
164 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
165 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
166 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
167 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
168 if (CP[i].first.isMachineConstantPoolEntry())
169 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
171 EmitGlobalConstant(CP[i].first.Val.ConstVal);
173 const Type *Ty = CP[i].first.getType();
175 TM.getTargetData()->getTypeSize(Ty);
176 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
177 // Emit inter-object padding for alignment.
178 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
183 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
184 /// by the current function to the current output stream.
186 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
187 MachineFunction &MF) {
188 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
189 if (JT.empty()) return;
190 const TargetData *TD = TM.getTargetData();
192 // JTEntryDirective is a string to print sizeof(ptr) for non-PIC jump tables,
193 // and 32 bits for PIC since PIC jump table entries are differences, not
194 // pointers to blocks.
195 // Use the architecture specific relocation directive, if it is set
196 const char *JTEntryDirective = TAI->getJumpTableDirective();
197 if (!JTEntryDirective)
198 JTEntryDirective = TAI->getData32bitsDirective();
200 // Pick the directive to use to print the jump table entries, and switch to
201 // the appropriate section.
202 if (TM.getRelocationModel() == Reloc::PIC_) {
203 SwitchToTextSection(TAI->getJumpTableTextSection(), 0);
205 SwitchToDataSection(TAI->getJumpTableDataSection(), 0);
206 if (TD->getPointerSize() == 8)
207 JTEntryDirective = TAI->getData64bitsDirective();
209 EmitAlignment(Log2_32(TD->getPointerAlignment()));
211 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
212 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
214 // For PIC codegen, if possible we want to use the SetDirective to reduce
215 // the number of relocations the assembler will generate for the jump table.
216 // Set directives are all printed before the jump table itself.
217 std::set<MachineBasicBlock*> EmittedSets;
218 if (TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_)
219 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
220 if (EmittedSets.insert(JTBBs[ii]).second)
221 printSetLabel(i, JTBBs[ii]);
223 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
224 << '_' << i << ":\n";
226 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
227 O << JTEntryDirective << ' ';
228 // If we have emitted set directives for the jump table entries, print
229 // them rather than the entries themselves. If we're emitting PIC, then
230 // emit the table entries as differences between two text section labels.
231 // If we're emitting non-PIC code, then emit the entries as direct
232 // references to the target basic blocks.
233 if (!EmittedSets.empty()) {
234 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
235 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
236 } else if (TM.getRelocationModel() == Reloc::PIC_) {
237 printBasicBlockLabel(JTBBs[ii], false, false);
238 //If the arch uses custom Jump Table directives, don't calc relative to JT
239 if (!TAI->getJumpTableDirective())
240 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
241 << getFunctionNumber() << '_' << i;
243 printBasicBlockLabel(JTBBs[ii], false, false);
250 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
251 /// special global used by LLVM. If so, emit it and return true, otherwise
252 /// do nothing and return false.
253 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
254 // Ignore debug and non-emitted data.
255 if (GV->getSection() == "llvm.metadata") return true;
257 if (!GV->hasAppendingLinkage()) return false;
259 assert(GV->hasInitializer() && "Not a special LLVM global!");
261 if (GV->getName() == "llvm.used") {
262 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
263 EmitLLVMUsedList(GV->getInitializer());
267 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
268 SwitchToDataSection(TAI->getStaticCtorsSection(), 0);
270 EmitXXStructorList(GV->getInitializer());
274 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
275 SwitchToDataSection(TAI->getStaticDtorsSection(), 0);
277 EmitXXStructorList(GV->getInitializer());
284 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
285 /// global in the specified llvm.used list as being used with this directive.
286 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
287 const char *Directive = TAI->getUsedDirective();
289 // Should be an array of 'sbyte*'.
290 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
291 if (InitList == 0) return;
293 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
295 EmitConstantValueOnly(InitList->getOperand(i));
300 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
301 /// function pointers, ignoring the init priority.
302 void AsmPrinter::EmitXXStructorList(Constant *List) {
303 // Should be an array of '{ int, void ()* }' structs. The first value is the
304 // init priority, which we ignore.
305 if (!isa<ConstantArray>(List)) return;
306 ConstantArray *InitList = cast<ConstantArray>(List);
307 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
308 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
309 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
311 if (CS->getOperand(1)->isNullValue())
312 return; // Found a null terminator, exit printing.
313 // Emit the function pointer.
314 EmitGlobalConstant(CS->getOperand(1));
318 /// getPreferredAlignmentLog - Return the preferred alignment of the
319 /// specified global, returned in log form. This includes an explicitly
320 /// requested alignment (if the global has one).
321 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
322 const Type *ElemType = GV->getType()->getElementType();
323 unsigned Alignment = TM.getTargetData()->getTypeAlignmentShift(ElemType);
324 if (GV->getAlignment() > (1U << Alignment))
325 Alignment = Log2_32(GV->getAlignment());
327 if (GV->hasInitializer()) {
328 // Always round up alignment of global doubles to 8 bytes.
329 if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
332 // If the global is not external, see if it is large. If so, give it a
334 if (TM.getTargetData()->getTypeSize(ElemType) > 128)
335 Alignment = 4; // 16-byte alignment.
341 // EmitAlignment - Emit an alignment directive to the specified power of two.
342 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
343 if (GV && GV->getAlignment())
344 NumBits = Log2_32(GV->getAlignment());
345 if (NumBits == 0) return; // No need to emit alignment.
346 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
347 O << TAI->getAlignDirective() << NumBits << "\n";
350 /// EmitZeros - Emit a block of zeros.
352 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
354 if (TAI->getZeroDirective()) {
355 O << TAI->getZeroDirective() << NumZeros;
356 if (TAI->getZeroDirectiveSuffix())
357 O << TAI->getZeroDirectiveSuffix();
360 for (; NumZeros; --NumZeros)
361 O << TAI->getData8bitsDirective() << "0\n";
366 // Print out the specified constant, without a storage class. Only the
367 // constants valid in constant expressions can occur here.
368 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
369 if (CV->isNullValue() || isa<UndefValue>(CV))
371 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
372 assert(CB->getValue());
374 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
375 if (((CI->getValue() << 32) >> 32) == CI->getValue())
378 O << (uint64_t)CI->getValue();
379 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
381 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
382 // This is a constant address for a global variable or function. Use the
383 // name of the variable or function as the address value, possibly
384 // decorating it with GlobalVarAddrPrefix/Suffix or
385 // FunctionAddrPrefix/Suffix (these all default to "" )
386 if (isa<Function>(GV)) {
387 O << TAI->getFunctionAddrPrefix()
388 << Mang->getValueName(GV)
389 << TAI->getFunctionAddrSuffix();
391 O << TAI->getGlobalVarAddrPrefix()
392 << Mang->getValueName(GV)
393 << TAI->getGlobalVarAddrSuffix();
395 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
396 const TargetData *TD = TM.getTargetData();
397 switch(CE->getOpcode()) {
398 case Instruction::GetElementPtr: {
399 // generate a symbolic expression for the byte address
400 const Constant *ptrVal = CE->getOperand(0);
401 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
402 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
405 EmitConstantValueOnly(ptrVal);
407 O << ") + " << Offset;
409 O << ") - " << -Offset;
411 EmitConstantValueOnly(ptrVal);
415 case Instruction::Cast: {
416 // Support only foldable casts to/from pointers that can be eliminated by
417 // changing the pointer to the appropriately sized integer type.
418 Constant *Op = CE->getOperand(0);
419 const Type *OpTy = Op->getType(), *Ty = CE->getType();
421 // Handle casts to pointers by changing them into casts to the appropriate
422 // integer type. This promotes constant folding and simplifies this code.
423 if (isa<PointerType>(Ty)) {
424 const Type *IntPtrTy = TD->getIntPtrType();
425 Op = ConstantExpr::getCast(Op, IntPtrTy);
426 return EmitConstantValueOnly(Op);
429 // We know the dest type is not a pointer. Is the src value a pointer or
431 if (isa<PointerType>(OpTy) || OpTy->isIntegral()) {
432 // We can emit the pointer value into this slot if the slot is an
433 // integer slot greater or equal to the size of the pointer.
434 if (Ty->isIntegral() && TD->getTypeSize(Ty) >= TD->getTypeSize(OpTy))
435 return EmitConstantValueOnly(Op);
438 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
439 EmitConstantValueOnly(Op);
442 case Instruction::Add:
444 EmitConstantValueOnly(CE->getOperand(0));
446 EmitConstantValueOnly(CE->getOperand(1));
450 assert(0 && "Unsupported operator!");
453 assert(0 && "Unknown constant value!");
457 /// toOctal - Convert the low order bits of X into an octal digit.
459 static inline char toOctal(int X) {
463 /// printAsCString - Print the specified array as a C compatible string, only if
464 /// the predicate isString is true.
466 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
468 assert(CVA->isString() && "Array is not string compatible!");
471 for (unsigned i = 0; i != LastElt; ++i) {
473 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
477 } else if (C == '\\') {
479 } else if (isprint(C)) {
483 case '\b': O << "\\b"; break;
484 case '\f': O << "\\f"; break;
485 case '\n': O << "\\n"; break;
486 case '\r': O << "\\r"; break;
487 case '\t': O << "\\t"; break;
490 O << toOctal(C >> 6);
491 O << toOctal(C >> 3);
492 O << toOctal(C >> 0);
500 /// EmitString - Emit a zero-byte-terminated string constant.
502 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
503 unsigned NumElts = CVA->getNumOperands();
504 if (TAI->getAscizDirective() && NumElts &&
505 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
506 O << TAI->getAscizDirective();
507 printAsCString(O, CVA, NumElts-1);
509 O << TAI->getAsciiDirective();
510 printAsCString(O, CVA, NumElts);
515 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
517 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
518 const TargetData *TD = TM.getTargetData();
520 if (CV->isNullValue() || isa<UndefValue>(CV)) {
521 EmitZeros(TD->getTypeSize(CV->getType()));
523 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
524 if (CVA->isString()) {
526 } else { // Not a string. Print the values in successive locations
527 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
528 EmitGlobalConstant(CVA->getOperand(i));
531 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
532 // Print the fields in successive locations. Pad to align if needed!
533 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
534 uint64_t sizeSoFar = 0;
535 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
536 const Constant* field = CVS->getOperand(i);
538 // Check if padding is needed and insert one or more 0s.
539 uint64_t fieldSize = TD->getTypeSize(field->getType());
540 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
541 : cvsLayout->MemberOffsets[i+1])
542 - cvsLayout->MemberOffsets[i]) - fieldSize;
543 sizeSoFar += fieldSize + padSize;
545 // Now print the actual field value
546 EmitGlobalConstant(field);
548 // Insert the field padding unless it's zero bytes...
551 assert(sizeSoFar == cvsLayout->StructSize &&
552 "Layout of constant struct may be incorrect!");
554 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
555 // FP Constants are printed as integer constants to avoid losing
557 double Val = CFP->getValue();
558 if (CFP->getType() == Type::DoubleTy) {
559 if (TAI->getData64bitsDirective())
560 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
561 << TAI->getCommentString() << " double value: " << Val << "\n";
562 else if (TD->isBigEndian()) {
563 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
564 << "\t" << TAI->getCommentString()
565 << " double most significant word " << Val << "\n";
566 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
567 << "\t" << TAI->getCommentString()
568 << " double least significant word " << Val << "\n";
570 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
571 << "\t" << TAI->getCommentString()
572 << " double least significant word " << Val << "\n";
573 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
574 << "\t" << TAI->getCommentString()
575 << " double most significant word " << Val << "\n";
579 O << TAI->getData32bitsDirective() << FloatToBits(Val)
580 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
583 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
584 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
585 uint64_t Val = CI->getRawValue();
587 if (TAI->getData64bitsDirective())
588 O << TAI->getData64bitsDirective() << Val << "\n";
589 else if (TD->isBigEndian()) {
590 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
591 << "\t" << TAI->getCommentString()
592 << " Double-word most significant word " << Val << "\n";
593 O << TAI->getData32bitsDirective() << unsigned(Val)
594 << "\t" << TAI->getCommentString()
595 << " Double-word least significant word " << Val << "\n";
597 O << TAI->getData32bitsDirective() << unsigned(Val)
598 << "\t" << TAI->getCommentString()
599 << " Double-word least significant word " << Val << "\n";
600 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
601 << "\t" << TAI->getCommentString()
602 << " Double-word most significant word " << Val << "\n";
606 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
607 const PackedType *PTy = CP->getType();
609 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
610 EmitGlobalConstant(CP->getOperand(I));
615 const Type *type = CV->getType();
616 printDataDirective(type);
617 EmitConstantValueOnly(CV);
622 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
623 // Target doesn't support this yet!
627 /// PrintSpecial - Print information related to the specified machine instr
628 /// that is independent of the operand, and may be independent of the instr
629 /// itself. This can be useful for portably encoding the comment character
630 /// or other bits of target-specific knowledge into the asmstrings. The
631 /// syntax used is ${:comment}. Targets can override this to add support
632 /// for their own strange codes.
633 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
634 if (!strcmp(Code, "private")) {
635 O << TAI->getPrivateGlobalPrefix();
636 } else if (!strcmp(Code, "comment")) {
637 O << TAI->getCommentString();
638 } else if (!strcmp(Code, "uid")) {
639 // Assign a unique ID to this machine instruction.
640 static const MachineInstr *LastMI = 0;
641 static unsigned Counter = 0U-1;
642 // If this is a new machine instruction, bump the counter.
643 if (LastMI != MI) { ++Counter; LastMI = MI; }
646 std::cerr << "Unknown special formatter '" << Code
647 << "' for machine instr: " << *MI;
653 /// printInlineAsm - This method formats and prints the specified machine
654 /// instruction that is an inline asm.
655 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
656 unsigned NumOperands = MI->getNumOperands();
658 // Count the number of register definitions.
659 unsigned NumDefs = 0;
660 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
662 assert(NumDefs != NumOperands-1 && "No asm string?");
664 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
666 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
667 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
669 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
670 if (AsmStr[0] == 0) {
671 O << "\n"; // Tab already printed, avoid double indenting next instr.
675 O << TAI->getInlineAsmStart() << "\n\t";
677 // The variant of the current asmprinter: FIXME: change.
678 int AsmPrinterVariant = 0;
680 int CurVariant = -1; // The number of the {.|.|.} region we are in.
681 const char *LastEmitted = AsmStr; // One past the last character emitted.
683 while (*LastEmitted) {
684 switch (*LastEmitted) {
686 // Not a special case, emit the string section literally.
687 const char *LiteralEnd = LastEmitted+1;
688 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
689 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
691 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
692 O.write(LastEmitted, LiteralEnd-LastEmitted);
693 LastEmitted = LiteralEnd;
697 ++LastEmitted; // Consume newline character.
698 O << "\n\t"; // Indent code with newline.
701 ++LastEmitted; // Consume '$' character.
705 switch (*LastEmitted) {
706 default: Done = false; break;
708 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
710 ++LastEmitted; // Consume second '$' character.
712 case '(': // $( -> same as GCC's { character.
713 ++LastEmitted; // Consume '(' character.
714 if (CurVariant != -1) {
715 std::cerr << "Nested variants found in inline asm string: '"
719 CurVariant = 0; // We're in the first variant now.
722 ++LastEmitted; // consume '|' character.
723 if (CurVariant == -1) {
724 std::cerr << "Found '|' character outside of variant in inline asm "
725 << "string: '" << AsmStr << "'\n";
728 ++CurVariant; // We're in the next variant.
730 case ')': // $) -> same as GCC's } char.
731 ++LastEmitted; // consume ')' character.
732 if (CurVariant == -1) {
733 std::cerr << "Found '}' character outside of variant in inline asm "
734 << "string: '" << AsmStr << "'\n";
742 bool HasCurlyBraces = false;
743 if (*LastEmitted == '{') { // ${variable}
744 ++LastEmitted; // Consume '{' character.
745 HasCurlyBraces = true;
748 const char *IDStart = LastEmitted;
750 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
751 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
752 std::cerr << "Bad $ operand number in inline asm string: '"
758 char Modifier[2] = { 0, 0 };
760 if (HasCurlyBraces) {
761 // If we have curly braces, check for a modifier character. This
762 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
763 if (*LastEmitted == ':') {
764 ++LastEmitted; // Consume ':' character.
765 if (*LastEmitted == 0) {
766 std::cerr << "Bad ${:} expression in inline asm string: '"
771 Modifier[0] = *LastEmitted;
772 ++LastEmitted; // Consume modifier character.
775 if (*LastEmitted != '}') {
776 std::cerr << "Bad ${} expression in inline asm string: '"
780 ++LastEmitted; // Consume '}' character.
783 if ((unsigned)Val >= NumOperands-1) {
784 std::cerr << "Invalid $ operand number in inline asm string: '"
789 // Okay, we finally have a value number. Ask the target to print this
791 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
796 // Scan to find the machine operand number for the operand.
798 if (OpNo >= MI->getNumOperands()) break;
799 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
800 OpNo += (OpFlags >> 3) + 1;
803 if (OpNo >= MI->getNumOperands()) {
806 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
807 ++OpNo; // Skip over the ID number.
809 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
810 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
811 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
812 Modifier[0] ? Modifier : 0);
814 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
815 Modifier[0] ? Modifier : 0);
819 std::cerr << "Invalid operand found in inline asm: '"
829 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
832 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
833 /// instruction, using the specified assembler variant. Targets should
834 /// overried this to format as appropriate.
835 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
836 unsigned AsmVariant, const char *ExtraCode) {
837 // Target doesn't support this yet!
841 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
843 const char *ExtraCode) {
844 // Target doesn't support this yet!
848 /// printBasicBlockLabel - This method prints the label for the specified
849 /// MachineBasicBlock
850 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
852 bool printComment) const {
853 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
858 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
861 /// printSetLabel - This method prints a set label for the specified
862 /// MachineBasicBlock
863 void AsmPrinter::printSetLabel(unsigned uid,
864 const MachineBasicBlock *MBB) const {
865 if (!TAI->getSetDirective())
868 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
869 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
870 printBasicBlockLabel(MBB, false, false);
871 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
872 << '_' << uid << '\n';
875 /// printDataDirective - This method prints the asm directive for the
877 void AsmPrinter::printDataDirective(const Type *type) {
878 const TargetData *TD = TM.getTargetData();
879 switch (type->getTypeID()) {
881 case Type::UByteTyID: case Type::SByteTyID:
882 O << TAI->getData8bitsDirective();
884 case Type::UShortTyID: case Type::ShortTyID:
885 O << TAI->getData16bitsDirective();
887 case Type::PointerTyID:
888 if (TD->getPointerSize() == 8) {
889 assert(TAI->getData64bitsDirective() &&
890 "Target cannot handle 64-bit pointer exprs!");
891 O << TAI->getData64bitsDirective();
894 //Fall through for pointer size == int size
895 case Type::UIntTyID: case Type::IntTyID:
896 O << TAI->getData32bitsDirective();
898 case Type::ULongTyID: case Type::LongTyID:
899 assert(TAI->getData64bitsDirective() &&
900 "Target cannot handle 64-bit constant exprs!");
901 O << TAI->getData64bitsDirective();
903 case Type::FloatTyID: case Type::DoubleTyID:
904 assert (0 && "Should have already output floating point constant.");
906 assert (0 && "Can't handle printing this type of thing");