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/Support/Mangler.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Target/TargetMachine.h"
27 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
28 : FunctionNumber(0), O(o), TM(tm),
31 PrivateGlobalPrefix("."),
32 GlobalVarAddrPrefix(""),
33 GlobalVarAddrSuffix(""),
34 FunctionAddrPrefix(""),
35 FunctionAddrSuffix(""),
36 InlineAsmStart("#APP\n"),
37 InlineAsmEnd("#NO_APP\n"),
38 ZeroDirective("\t.zero\t"),
39 AsciiDirective("\t.ascii\t"),
40 AscizDirective("\t.asciz\t"),
41 Data8bitsDirective("\t.byte\t"),
42 Data16bitsDirective("\t.short\t"),
43 Data32bitsDirective("\t.long\t"),
44 Data64bitsDirective("\t.quad\t"),
45 AlignDirective("\t.align\t"),
46 AlignmentIsInBytes(true),
47 SwitchToSectionDirective("\t.section\t"),
48 ConstantPoolSection("\t.section .rodata\n"),
49 StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
50 StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
52 COMMDirective("\t.comm\t"),
53 COMMDirectiveTakesAlignment(true),
54 HasDotTypeDotSizeDirective(true) {
58 /// SwitchSection - Switch to the specified section of the executable if we
59 /// are not already in it!
61 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
64 if (GV && GV->hasSection())
65 NS = SwitchToSectionDirective + GV->getSection();
67 NS = std::string("\t")+NewSection;
69 if (CurrentSection != NS) {
71 if (!CurrentSection.empty())
72 O << CurrentSection << '\n';
76 bool AsmPrinter::doInitialization(Module &M) {
77 Mang = new Mangler(M, GlobalPrefix);
79 if (!M.getModuleInlineAsm().empty())
80 O << CommentString << " Start of file scope inline assembly\n"
81 << M.getModuleInlineAsm()
82 << "\n" << CommentString << " End of file scope inline assembly\n";
84 SwitchSection("", 0); // Reset back to no section.
86 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
87 DebugInfo->AnalyzeModule(M);
93 bool AsmPrinter::doFinalization(Module &M) {
94 delete Mang; Mang = 0;
98 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
99 // What's my mangled name?
100 CurrentFnName = Mang->getValueName(MF.getFunction());
101 IncrementFunctionNumber();
104 /// EmitConstantPool - Print to the current output stream assembly
105 /// representations of the constants in the constant pool MCP. This is
106 /// used to print out constants which have been "spilled to memory" by
107 /// the code generator.
109 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
110 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
111 if (CP.empty()) return;
112 const TargetData &TD = TM.getTargetData();
114 SwitchSection(ConstantPoolSection, 0);
115 EmitAlignment(MCP->getConstantPoolAlignment());
116 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
117 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
118 << ":\t\t\t\t\t" << CommentString << " ";
119 WriteTypeSymbolic(O, CP[i].Val->getType(), 0) << '\n';
120 EmitGlobalConstant(CP[i].Val);
122 unsigned EntSize = TM.getTargetData().getTypeSize(CP[i].Val->getType());
123 unsigned ValEnd = CP[i].Offset + EntSize;
124 // Emit inter-object padding for alignment.
125 EmitZeros(CP[i+1].Offset-ValEnd);
130 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
131 /// special global used by LLVM. If so, emit it and return true, otherwise
132 /// do nothing and return false.
133 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
134 assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
135 "Not a special LLVM global!");
137 if (GV->getName() == "llvm.used")
138 return true; // No need to emit this at all.
140 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
141 SwitchSection(StaticCtorsSection, 0);
143 EmitXXStructorList(GV->getInitializer());
147 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
148 SwitchSection(StaticDtorsSection, 0);
150 EmitXXStructorList(GV->getInitializer());
157 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
158 /// function pointers, ignoring the init priority.
159 void AsmPrinter::EmitXXStructorList(Constant *List) {
160 // Should be an array of '{ int, void ()* }' structs. The first value is the
161 // init priority, which we ignore.
162 if (!isa<ConstantArray>(List)) return;
163 ConstantArray *InitList = cast<ConstantArray>(List);
164 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
165 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
166 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
168 if (CS->getOperand(1)->isNullValue())
169 return; // Found a null terminator, exit printing.
170 // Emit the function pointer.
171 EmitGlobalConstant(CS->getOperand(1));
175 /// getPreferredAlignmentLog - Return the preferred alignment of the
176 /// specified global, returned in log form. This includes an explicitly
177 /// requested alignment (if the global has one).
178 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
179 unsigned Alignment = TM.getTargetData().getTypeAlignmentShift(GV->getType());
180 if (GV->getAlignment() > (1U << Alignment))
181 Alignment = Log2_32(GV->getAlignment());
183 if (GV->hasInitializer()) {
184 // Always round up alignment of global doubles to 8 bytes.
185 if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
188 // If the global is not external, see if it is large. If so, give it a
190 if (TM.getTargetData().getTypeSize(GV->getType()->getElementType()) > 128)
191 Alignment = 4; // 16-byte alignment.
197 // EmitAlignment - Emit an alignment directive to the specified power of two.
198 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
199 if (GV && GV->getAlignment())
200 NumBits = Log2_32(GV->getAlignment());
201 if (NumBits == 0) return; // No need to emit alignment.
202 if (AlignmentIsInBytes) NumBits = 1 << NumBits;
203 O << AlignDirective << NumBits << "\n";
206 /// EmitZeros - Emit a block of zeros.
208 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
211 O << ZeroDirective << NumZeros << "\n";
213 for (; NumZeros; --NumZeros)
214 O << Data8bitsDirective << "0\n";
219 // Print out the specified constant, without a storage class. Only the
220 // constants valid in constant expressions can occur here.
221 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
222 if (CV->isNullValue() || isa<UndefValue>(CV))
224 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
225 assert(CB == ConstantBool::True);
227 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
228 if (((CI->getValue() << 32) >> 32) == CI->getValue())
231 O << (uint64_t)CI->getValue();
232 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
234 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
235 // This is a constant address for a global variable or function. Use the
236 // name of the variable or function as the address value, possibly
237 // decorating it with GlobalVarAddrPrefix/Suffix or
238 // FunctionAddrPrefix/Suffix (these all default to "" )
239 if (isa<Function>(GV))
240 O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
242 O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
243 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
244 const TargetData &TD = TM.getTargetData();
245 switch(CE->getOpcode()) {
246 case Instruction::GetElementPtr: {
247 // generate a symbolic expression for the byte address
248 const Constant *ptrVal = CE->getOperand(0);
249 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
250 if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
253 EmitConstantValueOnly(ptrVal);
255 O << ") + " << Offset;
257 O << ") - " << -Offset;
259 EmitConstantValueOnly(ptrVal);
263 case Instruction::Cast: {
264 // Support only non-converting or widening casts for now, that is, ones
265 // that do not involve a change in value. This assertion is really gross,
266 // and may not even be a complete check.
267 Constant *Op = CE->getOperand(0);
268 const Type *OpTy = Op->getType(), *Ty = CE->getType();
270 // Remember, kids, pointers can be losslessly converted back and forth
271 // into 32-bit or wider integers, regardless of signedness. :-P
272 assert(((isa<PointerType>(OpTy)
273 && (Ty == Type::LongTy || Ty == Type::ULongTy
274 || Ty == Type::IntTy || Ty == Type::UIntTy))
275 || (isa<PointerType>(Ty)
276 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
277 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
278 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
279 && OpTy->isLosslesslyConvertibleTo(Ty))))
280 && "FIXME: Don't yet support this kind of constant cast expr");
281 EmitConstantValueOnly(Op);
284 case Instruction::Add:
286 EmitConstantValueOnly(CE->getOperand(0));
288 EmitConstantValueOnly(CE->getOperand(1));
292 assert(0 && "Unsupported operator!");
295 assert(0 && "Unknown constant value!");
299 /// toOctal - Convert the low order bits of X into an octal digit.
301 static inline char toOctal(int X) {
305 /// printAsCString - Print the specified array as a C compatible string, only if
306 /// the predicate isString is true.
308 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
310 assert(CVA->isString() && "Array is not string compatible!");
313 for (unsigned i = 0; i != LastElt; ++i) {
315 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
319 } else if (C == '\\') {
321 } else if (isprint(C)) {
325 case '\b': O << "\\b"; break;
326 case '\f': O << "\\f"; break;
327 case '\n': O << "\\n"; break;
328 case '\r': O << "\\r"; break;
329 case '\t': O << "\\t"; break;
332 O << toOctal(C >> 6);
333 O << toOctal(C >> 3);
334 O << toOctal(C >> 0);
342 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
344 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
345 const TargetData &TD = TM.getTargetData();
347 if (CV->isNullValue() || isa<UndefValue>(CV)) {
348 EmitZeros(TD.getTypeSize(CV->getType()));
350 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
351 if (CVA->isString()) {
352 unsigned NumElts = CVA->getNumOperands();
353 if (AscizDirective && NumElts &&
354 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
356 printAsCString(O, CVA, NumElts-1);
359 printAsCString(O, CVA, NumElts);
362 } else { // Not a string. Print the values in successive locations
363 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
364 EmitGlobalConstant(CVA->getOperand(i));
367 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
368 // Print the fields in successive locations. Pad to align if needed!
369 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
370 uint64_t sizeSoFar = 0;
371 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
372 const Constant* field = CVS->getOperand(i);
374 // Check if padding is needed and insert one or more 0s.
375 uint64_t fieldSize = TD.getTypeSize(field->getType());
376 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
377 : cvsLayout->MemberOffsets[i+1])
378 - cvsLayout->MemberOffsets[i]) - fieldSize;
379 sizeSoFar += fieldSize + padSize;
381 // Now print the actual field value
382 EmitGlobalConstant(field);
384 // Insert the field padding unless it's zero bytes...
387 assert(sizeSoFar == cvsLayout->StructSize &&
388 "Layout of constant struct may be incorrect!");
390 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
391 // FP Constants are printed as integer constants to avoid losing
393 double Val = CFP->getValue();
394 if (CFP->getType() == Type::DoubleTy) {
395 if (Data64bitsDirective)
396 O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
397 << " double value: " << Val << "\n";
398 else if (TD.isBigEndian()) {
399 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
400 << "\t" << CommentString << " double most significant word "
402 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
403 << "\t" << CommentString << " double least significant word "
406 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
407 << "\t" << CommentString << " double least significant word " << Val
409 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
410 << "\t" << CommentString << " double most significant word " << Val
415 O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
416 << " float " << Val << "\n";
419 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
420 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
421 uint64_t Val = CI->getRawValue();
423 if (Data64bitsDirective)
424 O << Data64bitsDirective << Val << "\n";
425 else if (TD.isBigEndian()) {
426 O << Data32bitsDirective << unsigned(Val >> 32)
427 << "\t" << CommentString << " Double-word most significant word "
429 O << Data32bitsDirective << unsigned(Val)
430 << "\t" << CommentString << " Double-word least significant word "
433 O << Data32bitsDirective << unsigned(Val)
434 << "\t" << CommentString << " Double-word least significant word "
436 O << Data32bitsDirective << unsigned(Val >> 32)
437 << "\t" << CommentString << " Double-word most significant word "
442 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
443 const PackedType *PTy = CP->getType();
445 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
446 EmitGlobalConstant(CP->getOperand(I));
451 const Type *type = CV->getType();
452 switch (type->getTypeID()) {
454 case Type::UByteTyID: case Type::SByteTyID:
455 O << Data8bitsDirective;
457 case Type::UShortTyID: case Type::ShortTyID:
458 O << Data16bitsDirective;
460 case Type::PointerTyID:
461 if (TD.getPointerSize() == 8) {
462 O << Data64bitsDirective;
465 //Fall through for pointer size == int size
466 case Type::UIntTyID: case Type::IntTyID:
467 O << Data32bitsDirective;
469 case Type::ULongTyID: case Type::LongTyID:
470 assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
471 O << Data64bitsDirective;
473 case Type::FloatTyID: case Type::DoubleTyID:
474 assert (0 && "Should have already output floating point constant.");
476 assert (0 && "Can't handle printing this type of thing");
479 EmitConstantValueOnly(CV);
483 /// printInlineAsm - This method formats and prints the specified machine
484 /// instruction that is an inline asm.
485 void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
487 unsigned NumOperands = MI->getNumOperands();
489 // Count the number of register definitions.
490 unsigned NumDefs = 0;
491 for (; MI->getOperand(NumDefs).isDef(); ++NumDefs)
492 assert(NumDefs != NumOperands-1 && "No asm string?");
494 assert(MI->getOperand(NumDefs).isExternalSymbol() && "No asm string?");
496 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
497 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
499 // The variant of the current asmprinter: FIXME: change.
500 int AsmPrinterVariant = 0;
502 int CurVariant = -1; // The number of the {.|.|.} region we are in.
503 const char *LastEmitted = AsmStr; // One past the last character emitted.
505 while (*LastEmitted) {
506 switch (*LastEmitted) {
508 // Not a special case, emit the string section literally.
509 const char *LiteralEnd = LastEmitted+1;
510 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
511 *LiteralEnd != '}' && *LiteralEnd != '$')
513 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
514 O.write(LastEmitted, LiteralEnd-LastEmitted);
515 LastEmitted = LiteralEnd;
519 ++LastEmitted; // Consume '$' character.
520 if (*LastEmitted == '$') { // $$ -> $
521 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
523 ++LastEmitted; // Consume second '$' character.
527 bool HasCurlyBraces = false;
528 if (*LastEmitted == '{') { // ${variable}
529 ++LastEmitted; // Consume '{' character.
530 HasCurlyBraces = true;
533 const char *IDStart = LastEmitted;
535 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
536 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
537 std::cerr << "Bad $ operand number in inline asm string: '"
543 char Modifier[2] = { 0, 0 };
545 if (HasCurlyBraces) {
546 // If we have curly braces, check for a modifier character. This
547 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
548 if (*LastEmitted == ':') {
549 ++LastEmitted; // Consume ':' character.
550 if (*LastEmitted == 0) {
551 std::cerr << "Bad ${:} expression in inline asm string: '"
556 Modifier[0] = *LastEmitted;
557 ++LastEmitted; // Consume modifier character.
560 if (*LastEmitted != '}') {
561 std::cerr << "Bad ${} expression in inline asm string: '"
565 ++LastEmitted; // Consume '}' character.
568 if ((unsigned)Val >= NumOperands-1) {
569 std::cerr << "Invalid $ operand number in inline asm string: '"
574 // Okay, we finally have a value number. Ask the target to print this
576 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
579 // Scan to find the machine operand number for the operand.
581 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
582 OpNo += (OpFlags >> 3) + 1;
585 unsigned OpFlags = MI->getOperand(OpNo).getImmedValue();
586 ++OpNo; // Skip over the ID number.
589 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
590 if ((OpFlags & 7) == 4 /*ADDR MODE*/) {
591 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
592 Modifier[0] ? Modifier : 0);
594 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
595 Modifier[0] ? Modifier : 0);
598 std::cerr << "Invalid operand found in inline asm: '"
607 ++LastEmitted; // Consume '{' character.
608 if (CurVariant != -1) {
609 std::cerr << "Nested variants found in inline asm string: '"
613 CurVariant = 0; // We're in the first variant now.
616 ++LastEmitted; // consume '|' character.
617 if (CurVariant == -1) {
618 std::cerr << "Found '|' character outside of variant in inline asm "
619 << "string: '" << AsmStr << "'\n";
622 ++CurVariant; // We're in the next variant.
625 ++LastEmitted; // consume '}' character.
626 if (CurVariant == -1) {
627 std::cerr << "Found '}' character outside of variant in inline asm "
628 << "string: '" << AsmStr << "'\n";
635 O << "\n" << InlineAsmEnd;
638 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
639 /// instruction, using the specified assembler variant. Targets should
640 /// overried this to format as appropriate.
641 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
642 unsigned AsmVariant, const char *ExtraCode) {
643 // Target doesn't support this yet!
647 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
649 const char *ExtraCode) {
650 // Target doesn't support this yet!