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 delete Mang; Mang = 0;
113 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
114 // What's my mangled name?
115 CurrentFnName = Mang->getValueName(MF.getFunction());
116 IncrementFunctionNumber();
119 /// EmitConstantPool - Print to the current output stream assembly
120 /// representations of the constants in the constant pool MCP. This is
121 /// used to print out constants which have been "spilled to memory" by
122 /// the code generator.
124 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
125 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
126 if (CP.empty()) return;
128 // Some targets require 4-, 8-, and 16- byte constant literals to be placed
129 // in special sections.
130 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > FourByteCPs;
131 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > EightByteCPs;
132 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > SixteenByteCPs;
133 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > OtherCPs;
134 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > TargetCPs;
135 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
136 MachineConstantPoolEntry CPE = CP[i];
137 const Type *Ty = CPE.getType();
138 if (TAI->getFourByteConstantSection() &&
139 TM.getTargetData()->getTypeSize(Ty) == 4)
140 FourByteCPs.push_back(std::make_pair(CPE, i));
141 else if (TAI->getEightByteConstantSection() &&
142 TM.getTargetData()->getTypeSize(Ty) == 8)
143 EightByteCPs.push_back(std::make_pair(CPE, i));
144 else if (TAI->getSixteenByteConstantSection() &&
145 TM.getTargetData()->getTypeSize(Ty) == 16)
146 SixteenByteCPs.push_back(std::make_pair(CPE, i));
148 OtherCPs.push_back(std::make_pair(CPE, i));
151 unsigned Alignment = MCP->getConstantPoolAlignment();
152 EmitConstantPool(Alignment, TAI->getFourByteConstantSection(), FourByteCPs);
153 EmitConstantPool(Alignment, TAI->getEightByteConstantSection(), EightByteCPs);
154 EmitConstantPool(Alignment, TAI->getSixteenByteConstantSection(),
156 EmitConstantPool(Alignment, TAI->getConstantPoolSection(), OtherCPs);
159 void AsmPrinter::EmitConstantPool(unsigned Alignment, const char *Section,
160 std::vector<std::pair<MachineConstantPoolEntry,unsigned> > &CP) {
161 if (CP.empty()) return;
163 SwitchToDataSection(Section);
164 EmitAlignment(Alignment);
165 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
166 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
167 << CP[i].second << ":\t\t\t\t\t" << TAI->getCommentString() << " ";
168 WriteTypeSymbolic(O, CP[i].first.getType(), 0) << '\n';
169 if (CP[i].first.isMachineConstantPoolEntry())
170 EmitMachineConstantPoolValue(CP[i].first.Val.MachineCPVal);
172 EmitGlobalConstant(CP[i].first.Val.ConstVal);
174 const Type *Ty = CP[i].first.getType();
176 TM.getTargetData()->getTypeSize(Ty);
177 unsigned ValEnd = CP[i].first.getOffset() + EntSize;
178 // Emit inter-object padding for alignment.
179 EmitZeros(CP[i+1].first.getOffset()-ValEnd);
184 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
185 /// by the current function to the current output stream.
187 void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
188 MachineFunction &MF) {
189 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
190 if (JT.empty()) return;
191 const TargetData *TD = TM.getTargetData();
193 // JTEntryDirective is a string to print sizeof(ptr) for non-PIC jump tables,
194 // and 32 bits for PIC since PIC jump table entries are differences, not
195 // pointers to blocks.
196 // Use the architecture specific relocation directive, if it is set
197 const char *JTEntryDirective = TAI->getJumpTableDirective();
198 if (!JTEntryDirective)
199 JTEntryDirective = TAI->getData32bitsDirective();
201 // Pick the directive to use to print the jump table entries, and switch to
202 // the appropriate section.
203 if (TM.getRelocationModel() == Reloc::PIC_) {
204 TargetLowering *LoweringInfo = TM.getTargetLowering();
205 if (LoweringInfo && LoweringInfo->usesGlobalOffsetTable()) {
206 SwitchToDataSection(TAI->getJumpTableDataSection());
207 if (TD->getPointerSize() == 8 && !JTEntryDirective)
208 JTEntryDirective = TAI->getData64bitsDirective();
210 // In PIC mode, we need to emit the jump table to the same section as the
211 // function body itself, otherwise the label differences won't make sense.
212 const Function *F = MF.getFunction();
213 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
216 SwitchToDataSection(TAI->getJumpTableDataSection());
217 if (TD->getPointerSize() == 8)
218 JTEntryDirective = TAI->getData64bitsDirective();
220 EmitAlignment(Log2_32(TD->getPointerAlignment()));
222 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
223 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
225 // If this jump table was deleted, ignore it.
226 if (JTBBs.empty()) continue;
228 // For PIC codegen, if possible we want to use the SetDirective to reduce
229 // the number of relocations the assembler will generate for the jump table.
230 // Set directives are all printed before the jump table itself.
231 std::set<MachineBasicBlock*> EmittedSets;
232 if (TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_)
233 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
234 if (EmittedSets.insert(JTBBs[ii]).second)
235 printSetLabel(i, JTBBs[ii]);
237 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
238 << '_' << i << ":\n";
240 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
241 O << JTEntryDirective << ' ';
242 // If we have emitted set directives for the jump table entries, print
243 // them rather than the entries themselves. If we're emitting PIC, then
244 // emit the table entries as differences between two text section labels.
245 // If we're emitting non-PIC code, then emit the entries as direct
246 // references to the target basic blocks.
247 if (!EmittedSets.empty()) {
248 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
249 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
250 } else if (TM.getRelocationModel() == Reloc::PIC_) {
251 printBasicBlockLabel(JTBBs[ii], false, false);
252 //If the arch uses custom Jump Table directives, don't calc relative to JT
253 if (!TAI->getJumpTableDirective())
254 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
255 << getFunctionNumber() << '_' << i;
257 printBasicBlockLabel(JTBBs[ii], false, false);
264 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
265 /// special global used by LLVM. If so, emit it and return true, otherwise
266 /// do nothing and return false.
267 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
268 // Ignore debug and non-emitted data.
269 if (GV->getSection() == "llvm.metadata") return true;
271 if (!GV->hasAppendingLinkage()) return false;
273 assert(GV->hasInitializer() && "Not a special LLVM global!");
275 if (GV->getName() == "llvm.used") {
276 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
277 EmitLLVMUsedList(GV->getInitializer());
281 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
282 SwitchToDataSection(TAI->getStaticCtorsSection());
284 EmitXXStructorList(GV->getInitializer());
288 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
289 SwitchToDataSection(TAI->getStaticDtorsSection());
291 EmitXXStructorList(GV->getInitializer());
298 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
299 /// global in the specified llvm.used list as being used with this directive.
300 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
301 const char *Directive = TAI->getUsedDirective();
303 // Should be an array of 'sbyte*'.
304 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
305 if (InitList == 0) return;
307 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
309 EmitConstantValueOnly(InitList->getOperand(i));
314 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
315 /// function pointers, ignoring the init priority.
316 void AsmPrinter::EmitXXStructorList(Constant *List) {
317 // Should be an array of '{ int, void ()* }' structs. The first value is the
318 // init priority, which we ignore.
319 if (!isa<ConstantArray>(List)) return;
320 ConstantArray *InitList = cast<ConstantArray>(List);
321 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
322 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
323 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
325 if (CS->getOperand(1)->isNullValue())
326 return; // Found a null terminator, exit printing.
327 // Emit the function pointer.
328 EmitGlobalConstant(CS->getOperand(1));
332 /// getGlobalLinkName - Returns the asm/link name of of the specified
333 /// global variable. Should be overridden by each target asm printer to
334 /// generate the appropriate value.
335 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
336 std::string LinkName;
338 if (isa<Function>(GV)) {
339 LinkName += TAI->getFunctionAddrPrefix();
340 LinkName += Mang->getValueName(GV);
341 LinkName += TAI->getFunctionAddrSuffix();
343 LinkName += TAI->getGlobalVarAddrPrefix();
344 LinkName += Mang->getValueName(GV);
345 LinkName += TAI->getGlobalVarAddrSuffix();
351 // EmitAlignment - Emit an alignment directive to the specified power of two.
352 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
353 if (GV && GV->getAlignment())
354 NumBits = Log2_32(GV->getAlignment());
355 if (NumBits == 0) return; // No need to emit alignment.
356 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
357 O << TAI->getAlignDirective() << NumBits << "\n";
360 /// EmitZeros - Emit a block of zeros.
362 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
364 if (TAI->getZeroDirective()) {
365 O << TAI->getZeroDirective() << NumZeros;
366 if (TAI->getZeroDirectiveSuffix())
367 O << TAI->getZeroDirectiveSuffix();
370 for (; NumZeros; --NumZeros)
371 O << TAI->getData8bitsDirective() << "0\n";
376 // Print out the specified constant, without a storage class. Only the
377 // constants valid in constant expressions can occur here.
378 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
379 if (CV->isNullValue() || isa<UndefValue>(CV))
381 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
382 assert(CB->getValue());
384 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
385 if (CI->getType()->isSigned()) {
386 if (((CI->getSExtValue() << 32) >> 32) == CI->getSExtValue())
387 O << CI->getSExtValue();
389 O << (uint64_t)CI->getSExtValue();
391 O << CI->getZExtValue();
392 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
393 // This is a constant address for a global variable or function. Use the
394 // name of the variable or function as the address value, possibly
395 // decorating it with GlobalVarAddrPrefix/Suffix or
396 // FunctionAddrPrefix/Suffix (these all default to "" )
397 if (isa<Function>(GV)) {
398 O << TAI->getFunctionAddrPrefix()
399 << Mang->getValueName(GV)
400 << TAI->getFunctionAddrSuffix();
402 O << TAI->getGlobalVarAddrPrefix()
403 << Mang->getValueName(GV)
404 << TAI->getGlobalVarAddrSuffix();
406 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
407 const TargetData *TD = TM.getTargetData();
408 switch(CE->getOpcode()) {
409 case Instruction::GetElementPtr: {
410 // generate a symbolic expression for the byte address
411 const Constant *ptrVal = CE->getOperand(0);
412 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
413 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
416 EmitConstantValueOnly(ptrVal);
418 O << ") + " << Offset;
420 O << ") - " << -Offset;
422 EmitConstantValueOnly(ptrVal);
426 case Instruction::Trunc:
427 case Instruction::ZExt:
428 case Instruction::SExt:
429 case Instruction::FPTrunc:
430 case Instruction::FPExt:
431 case Instruction::UIToFP:
432 case Instruction::SIToFP:
433 case Instruction::FPToUI:
434 case Instruction::FPToSI:
435 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
437 case Instruction::BitCast:
438 return EmitConstantValueOnly(CE->getOperand(0));
440 case Instruction::IntToPtr: {
441 // Handle casts to pointers by changing them into casts to the appropriate
442 // integer type. This promotes constant folding and simplifies this code.
443 Constant *Op = CE->getOperand(0);
444 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
445 return EmitConstantValueOnly(Op);
449 case Instruction::PtrToInt: {
450 // Support only foldable casts to/from pointers that can be eliminated by
451 // changing the pointer to the appropriately sized integer type.
452 Constant *Op = CE->getOperand(0);
453 const Type *Ty = CE->getType();
455 // We can emit the pointer value into this slot if the slot is an
456 // integer slot greater or equal to the size of the pointer.
457 if (Ty->isIntegral() &&
458 Ty->getPrimitiveSize() >= TD->getTypeSize(Op->getType()))
459 return EmitConstantValueOnly(Op);
461 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
462 EmitConstantValueOnly(Op);
465 case Instruction::Add:
467 EmitConstantValueOnly(CE->getOperand(0));
469 EmitConstantValueOnly(CE->getOperand(1));
473 assert(0 && "Unsupported operator!");
476 assert(0 && "Unknown constant value!");
480 /// toOctal - Convert the low order bits of X into an octal digit.
482 static inline char toOctal(int X) {
486 /// printAsCString - Print the specified array as a C compatible string, only if
487 /// the predicate isString is true.
489 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
491 assert(CVA->isString() && "Array is not string compatible!");
494 for (unsigned i = 0; i != LastElt; ++i) {
496 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
500 } else if (C == '\\') {
502 } else if (isprint(C)) {
506 case '\b': O << "\\b"; break;
507 case '\f': O << "\\f"; break;
508 case '\n': O << "\\n"; break;
509 case '\r': O << "\\r"; break;
510 case '\t': O << "\\t"; break;
513 O << toOctal(C >> 6);
514 O << toOctal(C >> 3);
515 O << toOctal(C >> 0);
523 /// EmitString - Emit a zero-byte-terminated string constant.
525 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
526 unsigned NumElts = CVA->getNumOperands();
527 if (TAI->getAscizDirective() && NumElts &&
528 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
529 O << TAI->getAscizDirective();
530 printAsCString(O, CVA, NumElts-1);
532 O << TAI->getAsciiDirective();
533 printAsCString(O, CVA, NumElts);
538 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
540 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
541 const TargetData *TD = TM.getTargetData();
543 if (CV->isNullValue() || isa<UndefValue>(CV)) {
544 EmitZeros(TD->getTypeSize(CV->getType()));
546 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
547 if (CVA->isString()) {
549 } else { // Not a string. Print the values in successive locations
550 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
551 EmitGlobalConstant(CVA->getOperand(i));
554 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
555 // Print the fields in successive locations. Pad to align if needed!
556 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
557 uint64_t sizeSoFar = 0;
558 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
559 const Constant* field = CVS->getOperand(i);
561 // Check if padding is needed and insert one or more 0s.
562 uint64_t fieldSize = TD->getTypeSize(field->getType());
563 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
564 : cvsLayout->MemberOffsets[i+1])
565 - cvsLayout->MemberOffsets[i]) - fieldSize;
566 sizeSoFar += fieldSize + padSize;
568 // Now print the actual field value
569 EmitGlobalConstant(field);
571 // Insert the field padding unless it's zero bytes...
574 assert(sizeSoFar == cvsLayout->StructSize &&
575 "Layout of constant struct may be incorrect!");
577 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
578 // FP Constants are printed as integer constants to avoid losing
580 double Val = CFP->getValue();
581 if (CFP->getType() == Type::DoubleTy) {
582 if (TAI->getData64bitsDirective())
583 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
584 << TAI->getCommentString() << " double value: " << Val << "\n";
585 else if (TD->isBigEndian()) {
586 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
587 << "\t" << TAI->getCommentString()
588 << " double most significant word " << Val << "\n";
589 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
590 << "\t" << TAI->getCommentString()
591 << " double least significant word " << Val << "\n";
593 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
594 << "\t" << TAI->getCommentString()
595 << " double least significant word " << Val << "\n";
596 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
597 << "\t" << TAI->getCommentString()
598 << " double most significant word " << Val << "\n";
602 O << TAI->getData32bitsDirective() << FloatToBits(Val)
603 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
606 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
607 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
608 uint64_t Val = CI->getZExtValue();
610 if (TAI->getData64bitsDirective())
611 O << TAI->getData64bitsDirective() << Val << "\n";
612 else if (TD->isBigEndian()) {
613 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
614 << "\t" << TAI->getCommentString()
615 << " Double-word most significant word " << Val << "\n";
616 O << TAI->getData32bitsDirective() << unsigned(Val)
617 << "\t" << TAI->getCommentString()
618 << " Double-word least significant word " << Val << "\n";
620 O << TAI->getData32bitsDirective() << unsigned(Val)
621 << "\t" << TAI->getCommentString()
622 << " Double-word least significant word " << Val << "\n";
623 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
624 << "\t" << TAI->getCommentString()
625 << " Double-word most significant word " << Val << "\n";
629 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
630 const PackedType *PTy = CP->getType();
632 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
633 EmitGlobalConstant(CP->getOperand(I));
638 const Type *type = CV->getType();
639 printDataDirective(type);
640 EmitConstantValueOnly(CV);
645 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
646 // Target doesn't support this yet!
650 /// PrintSpecial - Print information related to the specified machine instr
651 /// that is independent of the operand, and may be independent of the instr
652 /// itself. This can be useful for portably encoding the comment character
653 /// or other bits of target-specific knowledge into the asmstrings. The
654 /// syntax used is ${:comment}. Targets can override this to add support
655 /// for their own strange codes.
656 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
657 if (!strcmp(Code, "private")) {
658 O << TAI->getPrivateGlobalPrefix();
659 } else if (!strcmp(Code, "comment")) {
660 O << TAI->getCommentString();
661 } else if (!strcmp(Code, "uid")) {
662 // Assign a unique ID to this machine instruction.
663 static const MachineInstr *LastMI = 0;
664 static unsigned Counter = 0U-1;
665 // If this is a new machine instruction, bump the counter.
666 if (LastMI != MI) { ++Counter; LastMI = MI; }
669 cerr << "Unknown special formatter '" << Code
670 << "' for machine instr: " << *MI;
676 /// printInlineAsm - This method formats and prints the specified machine
677 /// instruction that is an inline asm.
678 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
679 unsigned NumOperands = MI->getNumOperands();
681 // Count the number of register definitions.
682 unsigned NumDefs = 0;
683 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
685 assert(NumDefs != NumOperands-1 && "No asm string?");
687 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
689 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
690 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
692 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
693 if (AsmStr[0] == 0) {
694 O << "\n"; // Tab already printed, avoid double indenting next instr.
698 O << TAI->getInlineAsmStart() << "\n\t";
700 // The variant of the current asmprinter: FIXME: change.
701 int AsmPrinterVariant = 0;
703 int CurVariant = -1; // The number of the {.|.|.} region we are in.
704 const char *LastEmitted = AsmStr; // One past the last character emitted.
706 while (*LastEmitted) {
707 switch (*LastEmitted) {
709 // Not a special case, emit the string section literally.
710 const char *LiteralEnd = LastEmitted+1;
711 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
712 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
714 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
715 O.write(LastEmitted, LiteralEnd-LastEmitted);
716 LastEmitted = LiteralEnd;
720 ++LastEmitted; // Consume newline character.
721 O << "\n\t"; // Indent code with newline.
724 ++LastEmitted; // Consume '$' character.
728 switch (*LastEmitted) {
729 default: Done = false; break;
731 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
733 ++LastEmitted; // Consume second '$' character.
735 case '(': // $( -> same as GCC's { character.
736 ++LastEmitted; // Consume '(' character.
737 if (CurVariant != -1) {
738 cerr << "Nested variants found in inline asm string: '"
742 CurVariant = 0; // We're in the first variant now.
745 ++LastEmitted; // consume '|' character.
746 if (CurVariant == -1) {
747 cerr << "Found '|' character outside of variant in inline asm "
748 << "string: '" << AsmStr << "'\n";
751 ++CurVariant; // We're in the next variant.
753 case ')': // $) -> same as GCC's } char.
754 ++LastEmitted; // consume ')' character.
755 if (CurVariant == -1) {
756 cerr << "Found '}' character outside of variant in inline asm "
757 << "string: '" << AsmStr << "'\n";
765 bool HasCurlyBraces = false;
766 if (*LastEmitted == '{') { // ${variable}
767 ++LastEmitted; // Consume '{' character.
768 HasCurlyBraces = true;
771 const char *IDStart = LastEmitted;
773 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
774 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
775 cerr << "Bad $ operand number in inline asm string: '"
781 char Modifier[2] = { 0, 0 };
783 if (HasCurlyBraces) {
784 // If we have curly braces, check for a modifier character. This
785 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
786 if (*LastEmitted == ':') {
787 ++LastEmitted; // Consume ':' character.
788 if (*LastEmitted == 0) {
789 cerr << "Bad ${:} expression in inline asm string: '"
794 Modifier[0] = *LastEmitted;
795 ++LastEmitted; // Consume modifier character.
798 if (*LastEmitted != '}') {
799 cerr << "Bad ${} expression in inline asm string: '"
803 ++LastEmitted; // Consume '}' character.
806 if ((unsigned)Val >= NumOperands-1) {
807 cerr << "Invalid $ operand number in inline asm string: '"
812 // Okay, we finally have a value number. Ask the target to print this
814 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
819 // Scan to find the machine operand number for the operand.
821 if (OpNo >= MI->getNumOperands()) break;
822 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
823 OpNo += (OpFlags >> 3) + 1;
826 if (OpNo >= MI->getNumOperands()) {
829 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
830 ++OpNo; // Skip over the ID number.
832 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
833 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
834 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
835 Modifier[0] ? Modifier : 0);
837 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
838 Modifier[0] ? Modifier : 0);
842 cerr << "Invalid operand found in inline asm: '"
852 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
855 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
856 /// instruction, using the specified assembler variant. Targets should
857 /// overried this to format as appropriate.
858 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
859 unsigned AsmVariant, const char *ExtraCode) {
860 // Target doesn't support this yet!
864 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
866 const char *ExtraCode) {
867 // Target doesn't support this yet!
871 /// printBasicBlockLabel - This method prints the label for the specified
872 /// MachineBasicBlock
873 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
875 bool printComment) const {
876 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
880 if (printComment && MBB->getBasicBlock())
881 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
884 /// printSetLabel - This method prints a set label for the specified
885 /// MachineBasicBlock
886 void AsmPrinter::printSetLabel(unsigned uid,
887 const MachineBasicBlock *MBB) const {
888 if (!TAI->getSetDirective())
891 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
892 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
893 printBasicBlockLabel(MBB, false, false);
894 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
895 << '_' << uid << '\n';
898 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
899 const MachineBasicBlock *MBB) const {
900 if (!TAI->getSetDirective())
903 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
904 << getFunctionNumber() << '_' << uid << '_' << uid2
905 << "_set_" << MBB->getNumber() << ',';
906 printBasicBlockLabel(MBB, false, false);
907 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
908 << '_' << uid << '_' << uid2 << '\n';
911 /// printDataDirective - This method prints the asm directive for the
913 void AsmPrinter::printDataDirective(const Type *type) {
914 const TargetData *TD = TM.getTargetData();
915 switch (type->getTypeID()) {
917 case Type::UByteTyID: case Type::SByteTyID:
918 O << TAI->getData8bitsDirective();
920 case Type::UShortTyID: case Type::ShortTyID:
921 O << TAI->getData16bitsDirective();
923 case Type::PointerTyID:
924 if (TD->getPointerSize() == 8) {
925 assert(TAI->getData64bitsDirective() &&
926 "Target cannot handle 64-bit pointer exprs!");
927 O << TAI->getData64bitsDirective();
930 //Fall through for pointer size == int size
931 case Type::UIntTyID: case Type::IntTyID:
932 O << TAI->getData32bitsDirective();
934 case Type::ULongTyID: case Type::LongTyID:
935 assert(TAI->getData64bitsDirective() &&
936 "Target cannot handle 64-bit constant exprs!");
937 O << TAI->getData64bitsDirective();
939 case Type::FloatTyID: case Type::DoubleTyID:
940 assert (0 && "Should have already output floating point constant.");
942 assert (0 && "Can't handle printing this type of thing");