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 if (IsPic && !(LoweringInfo && LoweringInfo->usesGlobalOffsetTable())) {
219 // In PIC mode, we need to emit the jump table to the same section as the
220 // function body itself, otherwise the label differences won't make sense.
221 const Function *F = MF.getFunction();
222 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
224 SwitchToDataSection(TAI->getJumpTableDataSection());
227 EmitAlignment(Log2_32(MJTI->getAlignment()));
229 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
230 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
232 // If this jump table was deleted, ignore it.
233 if (JTBBs.empty()) continue;
235 // For PIC codegen, if possible we want to use the SetDirective to reduce
236 // the number of relocations the assembler will generate for the jump table.
237 // Set directives are all printed before the jump table itself.
238 std::set<MachineBasicBlock*> EmittedSets;
239 if (TAI->getSetDirective() && IsPic)
240 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
241 if (EmittedSets.insert(JTBBs[ii]).second)
242 printSetLabel(i, JTBBs[ii]);
244 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
245 << '_' << i << ":\n";
247 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
248 O << JTEntryDirective << ' ';
249 // If we have emitted set directives for the jump table entries, print
250 // them rather than the entries themselves. If we're emitting PIC, then
251 // emit the table entries as differences between two text section labels.
252 // If we're emitting non-PIC code, then emit the entries as direct
253 // references to the target basic blocks.
254 if (!EmittedSets.empty()) {
255 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
256 << '_' << i << "_set_" << JTBBs[ii]->getNumber();
258 printBasicBlockLabel(JTBBs[ii], false, false);
259 //If the arch uses custom Jump Table directives, don't calc relative to JT
260 if (!HadJTEntryDirective)
261 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
262 << getFunctionNumber() << '_' << i;
264 printBasicBlockLabel(JTBBs[ii], false, false);
271 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
272 /// special global used by LLVM. If so, emit it and return true, otherwise
273 /// do nothing and return false.
274 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
275 // Ignore debug and non-emitted data.
276 if (GV->getSection() == "llvm.metadata") return true;
278 if (!GV->hasAppendingLinkage()) return false;
280 assert(GV->hasInitializer() && "Not a special LLVM global!");
282 if (GV->getName() == "llvm.used") {
283 if (TAI->getUsedDirective() != 0) // No need to emit this at all.
284 EmitLLVMUsedList(GV->getInitializer());
288 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
289 SwitchToDataSection(TAI->getStaticCtorsSection());
291 EmitXXStructorList(GV->getInitializer());
295 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
296 SwitchToDataSection(TAI->getStaticDtorsSection());
298 EmitXXStructorList(GV->getInitializer());
305 /// EmitLLVMUsedList - For targets that define a TAI::UsedDirective, mark each
306 /// global in the specified llvm.used list as being used with this directive.
307 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
308 const char *Directive = TAI->getUsedDirective();
310 // Should be an array of 'sbyte*'.
311 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
312 if (InitList == 0) return;
314 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
316 EmitConstantValueOnly(InitList->getOperand(i));
321 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
322 /// function pointers, ignoring the init priority.
323 void AsmPrinter::EmitXXStructorList(Constant *List) {
324 // Should be an array of '{ int, void ()* }' structs. The first value is the
325 // init priority, which we ignore.
326 if (!isa<ConstantArray>(List)) return;
327 ConstantArray *InitList = cast<ConstantArray>(List);
328 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
329 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
330 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
332 if (CS->getOperand(1)->isNullValue())
333 return; // Found a null terminator, exit printing.
334 // Emit the function pointer.
335 EmitGlobalConstant(CS->getOperand(1));
339 /// getGlobalLinkName - Returns the asm/link name of of the specified
340 /// global variable. Should be overridden by each target asm printer to
341 /// generate the appropriate value.
342 const std::string AsmPrinter::getGlobalLinkName(const GlobalVariable *GV) const{
343 std::string LinkName;
345 if (isa<Function>(GV)) {
346 LinkName += TAI->getFunctionAddrPrefix();
347 LinkName += Mang->getValueName(GV);
348 LinkName += TAI->getFunctionAddrSuffix();
350 LinkName += TAI->getGlobalVarAddrPrefix();
351 LinkName += Mang->getValueName(GV);
352 LinkName += TAI->getGlobalVarAddrSuffix();
358 // EmitAlignment - Emit an alignment directive to the specified power of two.
359 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
360 if (GV && GV->getAlignment())
361 NumBits = Log2_32(GV->getAlignment());
362 if (NumBits == 0) return; // No need to emit alignment.
363 if (TAI->getAlignmentIsInBytes()) NumBits = 1 << NumBits;
364 O << TAI->getAlignDirective() << NumBits << "\n";
367 /// EmitZeros - Emit a block of zeros.
369 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
371 if (TAI->getZeroDirective()) {
372 O << TAI->getZeroDirective() << NumZeros;
373 if (TAI->getZeroDirectiveSuffix())
374 O << TAI->getZeroDirectiveSuffix();
377 for (; NumZeros; --NumZeros)
378 O << TAI->getData8bitsDirective() << "0\n";
383 // Print out the specified constant, without a storage class. Only the
384 // constants valid in constant expressions can occur here.
385 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
386 if (CV->isNullValue() || isa<UndefValue>(CV))
388 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
389 assert(CB->getValue());
391 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
392 if (CI->getType()->isSigned()) {
393 if (((CI->getSExtValue() << 32) >> 32) == CI->getSExtValue())
394 O << CI->getSExtValue();
396 O << (uint64_t)CI->getSExtValue();
398 O << CI->getZExtValue();
399 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
400 // This is a constant address for a global variable or function. Use the
401 // name of the variable or function as the address value, possibly
402 // decorating it with GlobalVarAddrPrefix/Suffix or
403 // FunctionAddrPrefix/Suffix (these all default to "" )
404 if (isa<Function>(GV)) {
405 O << TAI->getFunctionAddrPrefix()
406 << Mang->getValueName(GV)
407 << TAI->getFunctionAddrSuffix();
409 O << TAI->getGlobalVarAddrPrefix()
410 << Mang->getValueName(GV)
411 << TAI->getGlobalVarAddrSuffix();
413 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
414 const TargetData *TD = TM.getTargetData();
415 switch(CE->getOpcode()) {
416 case Instruction::GetElementPtr: {
417 // generate a symbolic expression for the byte address
418 const Constant *ptrVal = CE->getOperand(0);
419 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
420 if (int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec)) {
423 EmitConstantValueOnly(ptrVal);
425 O << ") + " << Offset;
427 O << ") - " << -Offset;
429 EmitConstantValueOnly(ptrVal);
433 case Instruction::Trunc:
434 case Instruction::ZExt:
435 case Instruction::SExt:
436 case Instruction::FPTrunc:
437 case Instruction::FPExt:
438 case Instruction::UIToFP:
439 case Instruction::SIToFP:
440 case Instruction::FPToUI:
441 case Instruction::FPToSI:
442 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
444 case Instruction::BitCast:
445 return EmitConstantValueOnly(CE->getOperand(0));
447 case Instruction::IntToPtr: {
448 // Handle casts to pointers by changing them into casts to the appropriate
449 // integer type. This promotes constant folding and simplifies this code.
450 Constant *Op = CE->getOperand(0);
451 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
452 return EmitConstantValueOnly(Op);
456 case Instruction::PtrToInt: {
457 // Support only foldable casts to/from pointers that can be eliminated by
458 // changing the pointer to the appropriately sized integer type.
459 Constant *Op = CE->getOperand(0);
460 const Type *Ty = CE->getType();
462 // We can emit the pointer value into this slot if the slot is an
463 // integer slot greater or equal to the size of the pointer.
464 if (Ty->isIntegral() &&
465 Ty->getPrimitiveSize() >= TD->getTypeSize(Op->getType()))
466 return EmitConstantValueOnly(Op);
468 assert(0 && "FIXME: Don't yet support this kind of constant cast expr");
469 EmitConstantValueOnly(Op);
472 case Instruction::Add:
474 EmitConstantValueOnly(CE->getOperand(0));
476 EmitConstantValueOnly(CE->getOperand(1));
480 assert(0 && "Unsupported operator!");
483 assert(0 && "Unknown constant value!");
487 /// toOctal - Convert the low order bits of X into an octal digit.
489 static inline char toOctal(int X) {
493 /// printAsCString - Print the specified array as a C compatible string, only if
494 /// the predicate isString is true.
496 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
498 assert(CVA->isString() && "Array is not string compatible!");
501 for (unsigned i = 0; i != LastElt; ++i) {
503 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
507 } else if (C == '\\') {
509 } else if (isprint(C)) {
513 case '\b': O << "\\b"; break;
514 case '\f': O << "\\f"; break;
515 case '\n': O << "\\n"; break;
516 case '\r': O << "\\r"; break;
517 case '\t': O << "\\t"; break;
520 O << toOctal(C >> 6);
521 O << toOctal(C >> 3);
522 O << toOctal(C >> 0);
530 /// EmitString - Emit a zero-byte-terminated string constant.
532 void AsmPrinter::EmitString(const ConstantArray *CVA) const {
533 unsigned NumElts = CVA->getNumOperands();
534 if (TAI->getAscizDirective() && NumElts &&
535 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
536 O << TAI->getAscizDirective();
537 printAsCString(O, CVA, NumElts-1);
539 O << TAI->getAsciiDirective();
540 printAsCString(O, CVA, NumElts);
545 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
547 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
548 const TargetData *TD = TM.getTargetData();
550 if (CV->isNullValue() || isa<UndefValue>(CV)) {
551 EmitZeros(TD->getTypeSize(CV->getType()));
553 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
554 if (CVA->isString()) {
556 } else { // Not a string. Print the values in successive locations
557 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
558 EmitGlobalConstant(CVA->getOperand(i));
561 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
562 // Print the fields in successive locations. Pad to align if needed!
563 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
564 uint64_t sizeSoFar = 0;
565 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
566 const Constant* field = CVS->getOperand(i);
568 // Check if padding is needed and insert one or more 0s.
569 uint64_t fieldSize = TD->getTypeSize(field->getType());
570 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
571 : cvsLayout->MemberOffsets[i+1])
572 - cvsLayout->MemberOffsets[i]) - fieldSize;
573 sizeSoFar += fieldSize + padSize;
575 // Now print the actual field value
576 EmitGlobalConstant(field);
578 // Insert the field padding unless it's zero bytes...
581 assert(sizeSoFar == cvsLayout->StructSize &&
582 "Layout of constant struct may be incorrect!");
584 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
585 // FP Constants are printed as integer constants to avoid losing
587 double Val = CFP->getValue();
588 if (CFP->getType() == Type::DoubleTy) {
589 if (TAI->getData64bitsDirective())
590 O << TAI->getData64bitsDirective() << DoubleToBits(Val) << "\t"
591 << TAI->getCommentString() << " double value: " << Val << "\n";
592 else if (TD->isBigEndian()) {
593 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
594 << "\t" << TAI->getCommentString()
595 << " double most significant word " << Val << "\n";
596 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
597 << "\t" << TAI->getCommentString()
598 << " double least significant word " << Val << "\n";
600 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val))
601 << "\t" << TAI->getCommentString()
602 << " double least significant word " << Val << "\n";
603 O << TAI->getData32bitsDirective() << unsigned(DoubleToBits(Val) >> 32)
604 << "\t" << TAI->getCommentString()
605 << " double most significant word " << Val << "\n";
609 O << TAI->getData32bitsDirective() << FloatToBits(Val)
610 << "\t" << TAI->getCommentString() << " float " << Val << "\n";
613 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
614 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
615 uint64_t Val = CI->getZExtValue();
617 if (TAI->getData64bitsDirective())
618 O << TAI->getData64bitsDirective() << Val << "\n";
619 else if (TD->isBigEndian()) {
620 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
621 << "\t" << TAI->getCommentString()
622 << " Double-word most significant word " << Val << "\n";
623 O << TAI->getData32bitsDirective() << unsigned(Val)
624 << "\t" << TAI->getCommentString()
625 << " Double-word least significant word " << Val << "\n";
627 O << TAI->getData32bitsDirective() << unsigned(Val)
628 << "\t" << TAI->getCommentString()
629 << " Double-word least significant word " << Val << "\n";
630 O << TAI->getData32bitsDirective() << unsigned(Val >> 32)
631 << "\t" << TAI->getCommentString()
632 << " Double-word most significant word " << Val << "\n";
636 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
637 const PackedType *PTy = CP->getType();
639 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
640 EmitGlobalConstant(CP->getOperand(I));
645 const Type *type = CV->getType();
646 printDataDirective(type);
647 EmitConstantValueOnly(CV);
652 AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
653 // Target doesn't support this yet!
657 /// PrintSpecial - Print information related to the specified machine instr
658 /// that is independent of the operand, and may be independent of the instr
659 /// itself. This can be useful for portably encoding the comment character
660 /// or other bits of target-specific knowledge into the asmstrings. The
661 /// syntax used is ${:comment}. Targets can override this to add support
662 /// for their own strange codes.
663 void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) {
664 if (!strcmp(Code, "private")) {
665 O << TAI->getPrivateGlobalPrefix();
666 } else if (!strcmp(Code, "comment")) {
667 O << TAI->getCommentString();
668 } else if (!strcmp(Code, "uid")) {
669 // Assign a unique ID to this machine instruction.
670 static const MachineInstr *LastMI = 0;
671 static unsigned Counter = 0U-1;
672 // If this is a new machine instruction, bump the counter.
673 if (LastMI != MI) { ++Counter; LastMI = MI; }
676 cerr << "Unknown special formatter '" << Code
677 << "' for machine instr: " << *MI;
683 /// printInlineAsm - This method formats and prints the specified machine
684 /// instruction that is an inline asm.
685 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
686 unsigned NumOperands = MI->getNumOperands();
688 // Count the number of register definitions.
689 unsigned NumDefs = 0;
690 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
692 assert(NumDefs != NumOperands-1 && "No asm string?");
694 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
696 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
697 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
699 // If this asmstr is empty, don't bother printing the #APP/#NOAPP markers.
700 if (AsmStr[0] == 0) {
701 O << "\n"; // Tab already printed, avoid double indenting next instr.
705 O << TAI->getInlineAsmStart() << "\n\t";
707 // The variant of the current asmprinter: FIXME: change.
708 int AsmPrinterVariant = 0;
710 int CurVariant = -1; // The number of the {.|.|.} region we are in.
711 const char *LastEmitted = AsmStr; // One past the last character emitted.
713 while (*LastEmitted) {
714 switch (*LastEmitted) {
716 // Not a special case, emit the string section literally.
717 const char *LiteralEnd = LastEmitted+1;
718 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
719 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
721 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
722 O.write(LastEmitted, LiteralEnd-LastEmitted);
723 LastEmitted = LiteralEnd;
727 ++LastEmitted; // Consume newline character.
728 O << "\n\t"; // Indent code with newline.
731 ++LastEmitted; // Consume '$' character.
735 switch (*LastEmitted) {
736 default: Done = false; break;
738 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
740 ++LastEmitted; // Consume second '$' character.
742 case '(': // $( -> same as GCC's { character.
743 ++LastEmitted; // Consume '(' character.
744 if (CurVariant != -1) {
745 cerr << "Nested variants found in inline asm string: '"
749 CurVariant = 0; // We're in the first variant now.
752 ++LastEmitted; // consume '|' character.
753 if (CurVariant == -1) {
754 cerr << "Found '|' character outside of variant in inline asm "
755 << "string: '" << AsmStr << "'\n";
758 ++CurVariant; // We're in the next variant.
760 case ')': // $) -> same as GCC's } char.
761 ++LastEmitted; // consume ')' character.
762 if (CurVariant == -1) {
763 cerr << "Found '}' character outside of variant in inline asm "
764 << "string: '" << AsmStr << "'\n";
772 bool HasCurlyBraces = false;
773 if (*LastEmitted == '{') { // ${variable}
774 ++LastEmitted; // Consume '{' character.
775 HasCurlyBraces = true;
778 const char *IDStart = LastEmitted;
780 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
781 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
782 cerr << "Bad $ operand number in inline asm string: '"
788 char Modifier[2] = { 0, 0 };
790 if (HasCurlyBraces) {
791 // If we have curly braces, check for a modifier character. This
792 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
793 if (*LastEmitted == ':') {
794 ++LastEmitted; // Consume ':' character.
795 if (*LastEmitted == 0) {
796 cerr << "Bad ${:} expression in inline asm string: '"
801 Modifier[0] = *LastEmitted;
802 ++LastEmitted; // Consume modifier character.
805 if (*LastEmitted != '}') {
806 cerr << "Bad ${} expression in inline asm string: '"
810 ++LastEmitted; // Consume '}' character.
813 if ((unsigned)Val >= NumOperands-1) {
814 cerr << "Invalid $ operand number in inline asm string: '"
819 // Okay, we finally have a value number. Ask the target to print this
821 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
826 // Scan to find the machine operand number for the operand.
828 if (OpNo >= MI->getNumOperands()) break;
829 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
830 OpNo += (OpFlags >> 3) + 1;
833 if (OpNo >= MI->getNumOperands()) {
836 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
837 ++OpNo; // Skip over the ID number.
839 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
840 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
841 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
842 Modifier[0] ? Modifier : 0);
844 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
845 Modifier[0] ? Modifier : 0);
849 cerr << "Invalid operand found in inline asm: '"
859 O << "\n\t" << TAI->getInlineAsmEnd() << "\n";
862 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
863 /// instruction, using the specified assembler variant. Targets should
864 /// overried this to format as appropriate.
865 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
866 unsigned AsmVariant, const char *ExtraCode) {
867 // Target doesn't support this yet!
871 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
873 const char *ExtraCode) {
874 // Target doesn't support this yet!
878 /// printBasicBlockLabel - This method prints the label for the specified
879 /// MachineBasicBlock
880 void AsmPrinter::printBasicBlockLabel(const MachineBasicBlock *MBB,
882 bool printComment) const {
883 O << TAI->getPrivateGlobalPrefix() << "BB" << FunctionNumber << "_"
887 if (printComment && MBB->getBasicBlock())
888 O << '\t' << TAI->getCommentString() << MBB->getBasicBlock()->getName();
891 /// printSetLabel - This method prints a set label for the specified
892 /// MachineBasicBlock
893 void AsmPrinter::printSetLabel(unsigned uid,
894 const MachineBasicBlock *MBB) const {
895 if (!TAI->getSetDirective())
898 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
899 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
900 printBasicBlockLabel(MBB, false, false);
901 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
902 << '_' << uid << '\n';
905 void AsmPrinter::printSetLabel(unsigned uid, unsigned uid2,
906 const MachineBasicBlock *MBB) const {
907 if (!TAI->getSetDirective())
910 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
911 << getFunctionNumber() << '_' << uid << '_' << uid2
912 << "_set_" << MBB->getNumber() << ',';
913 printBasicBlockLabel(MBB, false, false);
914 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
915 << '_' << uid << '_' << uid2 << '\n';
918 /// printDataDirective - This method prints the asm directive for the
920 void AsmPrinter::printDataDirective(const Type *type) {
921 const TargetData *TD = TM.getTargetData();
922 switch (type->getTypeID()) {
924 case Type::UByteTyID: case Type::SByteTyID:
925 O << TAI->getData8bitsDirective();
927 case Type::UShortTyID: case Type::ShortTyID:
928 O << TAI->getData16bitsDirective();
930 case Type::PointerTyID:
931 if (TD->getPointerSize() == 8) {
932 assert(TAI->getData64bitsDirective() &&
933 "Target cannot handle 64-bit pointer exprs!");
934 O << TAI->getData64bitsDirective();
937 //Fall through for pointer size == int size
938 case Type::UIntTyID: case Type::IntTyID:
939 O << TAI->getData32bitsDirective();
941 case Type::ULongTyID: case Type::LongTyID:
942 assert(TAI->getData64bitsDirective() &&
943 "Target cannot handle 64-bit constant exprs!");
944 O << TAI->getData64bitsDirective();
946 case Type::FloatTyID: case Type::DoubleTyID:
947 assert (0 && "Should have already output floating point constant.");
949 assert (0 && "Can't handle printing this type of thing");