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/DerivedTypes.h"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Module.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/Support/Mangler.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Target/TargetMachine.h"
26 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
27 : FunctionNumber(0), O(o), TM(tm),
30 PrivateGlobalPrefix("."),
31 GlobalVarAddrPrefix(""),
32 GlobalVarAddrSuffix(""),
33 FunctionAddrPrefix(""),
34 FunctionAddrSuffix(""),
35 ZeroDirective("\t.zero\t"),
36 AsciiDirective("\t.ascii\t"),
37 AscizDirective("\t.asciz\t"),
38 Data8bitsDirective("\t.byte\t"),
39 Data16bitsDirective("\t.short\t"),
40 Data32bitsDirective("\t.long\t"),
41 Data64bitsDirective("\t.quad\t"),
42 AlignDirective("\t.align\t"),
43 AlignmentIsInBytes(true),
44 SwitchToSectionDirective("\t.section\t"),
45 ConstantPoolSection("\t.section .rodata\n"),
46 StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
47 StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
49 COMMDirective("\t.comm\t"),
50 COMMDirectiveTakesAlignment(true),
51 HasDotTypeDotSizeDirective(true) {
55 /// SwitchSection - Switch to the specified section of the executable if we
56 /// are not already in it!
58 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
61 if (GV && GV->hasSection())
62 NS = SwitchToSectionDirective + GV->getSection();
64 NS = std::string("\t")+NewSection;
66 if (CurrentSection != NS) {
68 if (!CurrentSection.empty())
69 O << CurrentSection << '\n';
73 bool AsmPrinter::doInitialization(Module &M) {
74 Mang = new Mangler(M, GlobalPrefix);
76 if (!M.getModuleInlineAsm().empty())
77 O << CommentString << " Start of file scope inline assembly\n"
78 << M.getModuleInlineAsm()
79 << "\n" << CommentString << " End of file scope inline assembly\n";
81 SwitchSection("", 0); // Reset back to no section.
83 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
84 DebugInfo->AnalyzeModule(M);
90 bool AsmPrinter::doFinalization(Module &M) {
91 delete Mang; Mang = 0;
95 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
96 // What's my mangled name?
97 CurrentFnName = Mang->getValueName(MF.getFunction());
98 IncrementFunctionNumber();
101 /// EmitConstantPool - Print to the current output stream assembly
102 /// representations of the constants in the constant pool MCP. This is
103 /// used to print out constants which have been "spilled to memory" by
104 /// the code generator.
106 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
107 const std::vector<std::pair<Constant*, unsigned> > &CP = MCP->getConstants();
108 if (CP.empty()) return;
109 const TargetData &TD = TM.getTargetData();
111 SwitchSection(ConstantPoolSection, 0);
112 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
113 // FIXME: force doubles to be naturally aligned. We should handle this
114 // more correctly in the future.
115 unsigned Alignment = CP[i].second;
116 if (Alignment == 0) {
117 Alignment = TD.getTypeAlignmentShift(CP[i].first->getType());
118 if (CP[i].first->getType() == Type::DoubleTy && Alignment < 3)
122 EmitAlignment(Alignment);
123 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
124 << ":\t\t\t\t\t" << CommentString << *CP[i].first << '\n';
125 EmitGlobalConstant(CP[i].first);
129 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
130 /// special global used by LLVM. If so, emit it and return true, otherwise
131 /// do nothing and return false.
132 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
133 assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
134 "Not a special LLVM global!");
136 if (GV->getName() == "llvm.used")
137 return true; // No need to emit this at all.
139 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
140 SwitchSection(StaticCtorsSection, 0);
142 EmitXXStructorList(GV->getInitializer());
146 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
147 SwitchSection(StaticDtorsSection, 0);
149 EmitXXStructorList(GV->getInitializer());
156 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
157 /// function pointers, ignoring the init priority.
158 void AsmPrinter::EmitXXStructorList(Constant *List) {
159 // Should be an array of '{ int, void ()* }' structs. The first value is the
160 // init priority, which we ignore.
161 if (!isa<ConstantArray>(List)) return;
162 ConstantArray *InitList = cast<ConstantArray>(List);
163 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
164 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
165 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
167 if (CS->getOperand(1)->isNullValue())
168 return; // Found a null terminator, exit printing.
169 // Emit the function pointer.
170 EmitGlobalConstant(CS->getOperand(1));
174 /// getPreferredAlignmentLog - Return the preferred alignment of the
175 /// specified global, returned in log form. This includes an explicitly
176 /// requested alignment (if the global has one).
177 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
178 unsigned Alignment = TM.getTargetData().getTypeAlignmentShift(GV->getType());
179 if (GV->getAlignment() > (1U << Alignment))
180 Alignment = Log2_32(GV->getAlignment());
182 if (GV->hasInitializer()) {
183 // Always round up alignment of global doubles to 8 bytes.
184 if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
187 // If the global is not external, see if it is large. If so, give it a
189 if (TM.getTargetData().getTypeSize(GV->getType()->getElementType()) > 128)
190 Alignment = 4; // 16-byte alignment.
196 // EmitAlignment - Emit an alignment directive to the specified power of two.
197 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
198 if (GV && GV->getAlignment())
199 NumBits = Log2_32(GV->getAlignment());
200 if (NumBits == 0) return; // No need to emit alignment.
201 if (AlignmentIsInBytes) NumBits = 1 << NumBits;
202 O << AlignDirective << NumBits << "\n";
205 /// EmitZeros - Emit a block of zeros.
207 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
210 O << ZeroDirective << NumZeros << "\n";
212 for (; NumZeros; --NumZeros)
213 O << Data8bitsDirective << "0\n";
218 // Print out the specified constant, without a storage class. Only the
219 // constants valid in constant expressions can occur here.
220 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
221 if (CV->isNullValue() || isa<UndefValue>(CV))
223 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
224 assert(CB == ConstantBool::True);
226 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
227 if (((CI->getValue() << 32) >> 32) == CI->getValue())
230 O << (uint64_t)CI->getValue();
231 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
233 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
234 // This is a constant address for a global variable or function. Use the
235 // name of the variable or function as the address value, possibly
236 // decorating it with GlobalVarAddrPrefix/Suffix or
237 // FunctionAddrPrefix/Suffix (these all default to "" )
238 if (isa<Function>(GV))
239 O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
241 O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
242 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
243 const TargetData &TD = TM.getTargetData();
244 switch(CE->getOpcode()) {
245 case Instruction::GetElementPtr: {
246 // generate a symbolic expression for the byte address
247 const Constant *ptrVal = CE->getOperand(0);
248 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
249 if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
252 EmitConstantValueOnly(ptrVal);
254 O << ") + " << Offset;
256 O << ") - " << -Offset;
258 EmitConstantValueOnly(ptrVal);
262 case Instruction::Cast: {
263 // Support only non-converting or widening casts for now, that is, ones
264 // that do not involve a change in value. This assertion is really gross,
265 // and may not even be a complete check.
266 Constant *Op = CE->getOperand(0);
267 const Type *OpTy = Op->getType(), *Ty = CE->getType();
269 // Remember, kids, pointers can be losslessly converted back and forth
270 // into 32-bit or wider integers, regardless of signedness. :-P
271 assert(((isa<PointerType>(OpTy)
272 && (Ty == Type::LongTy || Ty == Type::ULongTy
273 || Ty == Type::IntTy || Ty == Type::UIntTy))
274 || (isa<PointerType>(Ty)
275 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
276 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
277 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
278 && OpTy->isLosslesslyConvertibleTo(Ty))))
279 && "FIXME: Don't yet support this kind of constant cast expr");
280 EmitConstantValueOnly(Op);
283 case Instruction::Add:
285 EmitConstantValueOnly(CE->getOperand(0));
287 EmitConstantValueOnly(CE->getOperand(1));
291 assert(0 && "Unsupported operator!");
294 assert(0 && "Unknown constant value!");
298 /// toOctal - Convert the low order bits of X into an octal digit.
300 static inline char toOctal(int X) {
304 /// printAsCString - Print the specified array as a C compatible string, only if
305 /// the predicate isString is true.
307 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
309 assert(CVA->isString() && "Array is not string compatible!");
312 for (unsigned i = 0; i != LastElt; ++i) {
314 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
318 } else if (C == '\\') {
320 } else if (isprint(C)) {
324 case '\b': O << "\\b"; break;
325 case '\f': O << "\\f"; break;
326 case '\n': O << "\\n"; break;
327 case '\r': O << "\\r"; break;
328 case '\t': O << "\\t"; break;
331 O << toOctal(C >> 6);
332 O << toOctal(C >> 3);
333 O << toOctal(C >> 0);
341 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
343 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
344 const TargetData &TD = TM.getTargetData();
346 if (CV->isNullValue() || isa<UndefValue>(CV)) {
347 EmitZeros(TD.getTypeSize(CV->getType()));
349 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
350 if (CVA->isString()) {
351 unsigned NumElts = CVA->getNumOperands();
352 if (AscizDirective && NumElts &&
353 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
355 printAsCString(O, CVA, NumElts-1);
358 printAsCString(O, CVA, NumElts);
361 } else { // Not a string. Print the values in successive locations
362 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
363 EmitGlobalConstant(CVA->getOperand(i));
366 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
367 // Print the fields in successive locations. Pad to align if needed!
368 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
369 uint64_t sizeSoFar = 0;
370 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
371 const Constant* field = CVS->getOperand(i);
373 // Check if padding is needed and insert one or more 0s.
374 uint64_t fieldSize = TD.getTypeSize(field->getType());
375 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
376 : cvsLayout->MemberOffsets[i+1])
377 - cvsLayout->MemberOffsets[i]) - fieldSize;
378 sizeSoFar += fieldSize + padSize;
380 // Now print the actual field value
381 EmitGlobalConstant(field);
383 // Insert the field padding unless it's zero bytes...
386 assert(sizeSoFar == cvsLayout->StructSize &&
387 "Layout of constant struct may be incorrect!");
389 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
390 // FP Constants are printed as integer constants to avoid losing
392 double Val = CFP->getValue();
393 if (CFP->getType() == Type::DoubleTy) {
394 if (Data64bitsDirective)
395 O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
396 << " double value: " << Val << "\n";
397 else if (TD.isBigEndian()) {
398 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
399 << "\t" << CommentString << " double most significant word "
401 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
402 << "\t" << CommentString << " double least significant word "
405 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
406 << "\t" << CommentString << " double least significant word " << Val
408 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
409 << "\t" << CommentString << " double most significant word " << Val
414 O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
415 << " float " << Val << "\n";
418 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
419 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
420 uint64_t Val = CI->getRawValue();
422 if (Data64bitsDirective)
423 O << Data64bitsDirective << Val << "\n";
424 else if (TD.isBigEndian()) {
425 O << Data32bitsDirective << unsigned(Val >> 32)
426 << "\t" << CommentString << " Double-word most significant word "
428 O << Data32bitsDirective << unsigned(Val)
429 << "\t" << CommentString << " Double-word least significant word "
432 O << Data32bitsDirective << unsigned(Val)
433 << "\t" << CommentString << " Double-word least significant word "
435 O << Data32bitsDirective << unsigned(Val >> 32)
436 << "\t" << CommentString << " Double-word most significant word "
441 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
442 const PackedType *PTy = CP->getType();
444 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
445 EmitGlobalConstant(CP->getOperand(I));
450 const Type *type = CV->getType();
451 switch (type->getTypeID()) {
453 case Type::UByteTyID: case Type::SByteTyID:
454 O << Data8bitsDirective;
456 case Type::UShortTyID: case Type::ShortTyID:
457 O << Data16bitsDirective;
459 case Type::PointerTyID:
460 if (TD.getPointerSize() == 8) {
461 O << Data64bitsDirective;
464 //Fall through for pointer size == int size
465 case Type::UIntTyID: case Type::IntTyID:
466 O << Data32bitsDirective;
468 case Type::ULongTyID: case Type::LongTyID:
469 assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
470 O << Data64bitsDirective;
472 case Type::FloatTyID: case Type::DoubleTyID:
473 assert (0 && "Should have already output floating point constant.");
475 assert (0 && "Can't handle printing this type of thing");
478 EmitConstantValueOnly(CV);
482 /// printInlineAsm - This method formats and prints the specified machine
483 /// instruction that is an inline asm.
484 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
485 unsigned NumOperands = MI->getNumOperands();
487 // Count the number of register definitions.
488 unsigned NumDefs = 0;
489 for (; MI->getOperand(NumDefs).isDef(); ++NumDefs)
490 assert(NumDefs != NumOperands-1 && "No asm string?");
492 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
494 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
495 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
497 // The variant of the current asmprinter: FIXME: change.
498 int AsmPrinterVariant = 0;
500 int CurVariant = -1; // The number of the {.|.|.} region we are in.
501 const char *LastEmitted = AsmStr; // One past the last character emitted.
503 while (*LastEmitted) {
504 switch (*LastEmitted) {
506 // Not a special case, emit the string section literally.
507 const char *LiteralEnd = LastEmitted+1;
508 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
509 *LiteralEnd != '}' && *LiteralEnd != '$')
511 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
512 O.write(LastEmitted, LiteralEnd-LastEmitted);
513 LastEmitted = LiteralEnd;
517 ++LastEmitted; // Consume '$' character.
518 if (*LastEmitted == '$') { // $$ -> $
519 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
521 ++LastEmitted; // Consume second '$' character.
525 bool HasCurlyBraces = false;
526 if (*LastEmitted == '{') { // ${variable}
527 ++LastEmitted; // Consume '{' character.
528 HasCurlyBraces = true;
531 const char *IDStart = LastEmitted;
533 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
534 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
535 std::cerr << "Bad $ operand number in inline asm string: '"
541 if (HasCurlyBraces) {
542 if (*LastEmitted != '}') {
543 std::cerr << "Bad ${} expression in inline asm string: '"
547 ++LastEmitted; // Consume '}' character.
550 if ((unsigned)Val >= NumOperands-1) {
551 std::cerr << "Invalid $ operand number in inline asm string: '"
556 // Okay, we finally have an operand number. Ask the target to print this
558 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
559 if (const_cast<AsmPrinter*>(this)->
560 PrintAsmOperand(MI, Val+1, AsmPrinterVariant)) {
561 std::cerr << "Invalid operand found in inline asm: '"
569 ++LastEmitted; // Consume '{' character.
570 if (CurVariant != -1) {
571 std::cerr << "Nested variants found in inline asm string: '"
575 CurVariant = 0; // We're in the first variant now.
578 ++LastEmitted; // consume '|' character.
579 if (CurVariant == -1) {
580 std::cerr << "Found '|' character outside of variant in inline asm "
581 << "string: '" << AsmStr << "'\n";
584 ++CurVariant; // We're in the next variant.
587 ++LastEmitted; // consume '}' character.
588 if (CurVariant == -1) {
589 std::cerr << "Found '}' character outside of variant in inline asm "
590 << "string: '" << AsmStr << "'\n";
600 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
601 /// instruction, using the specified assembler variant. Targets should
602 /// overried this to format as appropriate.
603 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
604 unsigned AsmVariant) {
605 // Target doesn't support this yet!