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 InlineAsmStart("#APP\n"),
36 InlineAsmEnd("#NO_APP\n"),
37 ZeroDirective("\t.zero\t"),
38 AsciiDirective("\t.ascii\t"),
39 AscizDirective("\t.asciz\t"),
40 Data8bitsDirective("\t.byte\t"),
41 Data16bitsDirective("\t.short\t"),
42 Data32bitsDirective("\t.long\t"),
43 Data64bitsDirective("\t.quad\t"),
44 AlignDirective("\t.align\t"),
45 AlignmentIsInBytes(true),
46 SwitchToSectionDirective("\t.section\t"),
47 ConstantPoolSection("\t.section .rodata\n"),
48 StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
49 StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
51 COMMDirective("\t.comm\t"),
52 COMMDirectiveTakesAlignment(true),
53 HasDotTypeDotSizeDirective(true) {
57 /// SwitchSection - Switch to the specified section of the executable if we
58 /// are not already in it!
60 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
63 if (GV && GV->hasSection())
64 NS = SwitchToSectionDirective + GV->getSection();
66 NS = std::string("\t")+NewSection;
68 if (CurrentSection != NS) {
70 if (!CurrentSection.empty())
71 O << CurrentSection << '\n';
75 bool AsmPrinter::doInitialization(Module &M) {
76 Mang = new Mangler(M, GlobalPrefix);
78 if (!M.getModuleInlineAsm().empty())
79 O << CommentString << " Start of file scope inline assembly\n"
80 << M.getModuleInlineAsm()
81 << "\n" << CommentString << " End of file scope inline assembly\n";
83 SwitchSection("", 0); // Reset back to no section.
85 if (MachineDebugInfo *DebugInfo = getAnalysisToUpdate<MachineDebugInfo>()) {
86 DebugInfo->AnalyzeModule(M);
92 bool AsmPrinter::doFinalization(Module &M) {
93 delete Mang; Mang = 0;
97 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
98 // What's my mangled name?
99 CurrentFnName = Mang->getValueName(MF.getFunction());
100 IncrementFunctionNumber();
103 /// EmitConstantPool - Print to the current output stream assembly
104 /// representations of the constants in the constant pool MCP. This is
105 /// used to print out constants which have been "spilled to memory" by
106 /// the code generator.
108 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
109 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
110 if (CP.empty()) return;
111 const TargetData &TD = TM.getTargetData();
113 SwitchSection(ConstantPoolSection, 0);
114 EmitAlignment(MCP->getConstantPoolAlignment());
115 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
116 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
117 << ":\t\t\t\t\t" << CommentString << *CP[i].Val << '\n';
118 EmitGlobalConstant(CP[i].Val);
120 unsigned EntSize = TM.getTargetData().getTypeSize(CP[i].Val->getType());
121 unsigned ValEnd = CP[i].Offset + EntSize;
122 // Emit inter-object padding for alignment.
123 EmitZeros(CP[i+1].Offset-ValEnd);
128 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
129 /// special global used by LLVM. If so, emit it and return true, otherwise
130 /// do nothing and return false.
131 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
132 assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
133 "Not a special LLVM global!");
135 if (GV->getName() == "llvm.used")
136 return true; // No need to emit this at all.
138 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
139 SwitchSection(StaticCtorsSection, 0);
141 EmitXXStructorList(GV->getInitializer());
145 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
146 SwitchSection(StaticDtorsSection, 0);
148 EmitXXStructorList(GV->getInitializer());
155 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
156 /// function pointers, ignoring the init priority.
157 void AsmPrinter::EmitXXStructorList(Constant *List) {
158 // Should be an array of '{ int, void ()* }' structs. The first value is the
159 // init priority, which we ignore.
160 if (!isa<ConstantArray>(List)) return;
161 ConstantArray *InitList = cast<ConstantArray>(List);
162 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
163 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
164 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
166 if (CS->getOperand(1)->isNullValue())
167 return; // Found a null terminator, exit printing.
168 // Emit the function pointer.
169 EmitGlobalConstant(CS->getOperand(1));
173 /// getPreferredAlignmentLog - Return the preferred alignment of the
174 /// specified global, returned in log form. This includes an explicitly
175 /// requested alignment (if the global has one).
176 unsigned AsmPrinter::getPreferredAlignmentLog(const GlobalVariable *GV) const {
177 unsigned Alignment = TM.getTargetData().getTypeAlignmentShift(GV->getType());
178 if (GV->getAlignment() > (1U << Alignment))
179 Alignment = Log2_32(GV->getAlignment());
181 if (GV->hasInitializer()) {
182 // Always round up alignment of global doubles to 8 bytes.
183 if (GV->getType()->getElementType() == Type::DoubleTy && Alignment < 3)
186 // If the global is not external, see if it is large. If so, give it a
188 if (TM.getTargetData().getTypeSize(GV->getType()->getElementType()) > 128)
189 Alignment = 4; // 16-byte alignment.
195 // EmitAlignment - Emit an alignment directive to the specified power of two.
196 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
197 if (GV && GV->getAlignment())
198 NumBits = Log2_32(GV->getAlignment());
199 if (NumBits == 0) return; // No need to emit alignment.
200 if (AlignmentIsInBytes) NumBits = 1 << NumBits;
201 O << AlignDirective << NumBits << "\n";
204 /// EmitZeros - Emit a block of zeros.
206 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
209 O << ZeroDirective << NumZeros << "\n";
211 for (; NumZeros; --NumZeros)
212 O << Data8bitsDirective << "0\n";
217 // Print out the specified constant, without a storage class. Only the
218 // constants valid in constant expressions can occur here.
219 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
220 if (CV->isNullValue() || isa<UndefValue>(CV))
222 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
223 assert(CB == ConstantBool::True);
225 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
226 if (((CI->getValue() << 32) >> 32) == CI->getValue())
229 O << (uint64_t)CI->getValue();
230 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
232 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
233 // This is a constant address for a global variable or function. Use the
234 // name of the variable or function as the address value, possibly
235 // decorating it with GlobalVarAddrPrefix/Suffix or
236 // FunctionAddrPrefix/Suffix (these all default to "" )
237 if (isa<Function>(GV))
238 O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
240 O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
241 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
242 const TargetData &TD = TM.getTargetData();
243 switch(CE->getOpcode()) {
244 case Instruction::GetElementPtr: {
245 // generate a symbolic expression for the byte address
246 const Constant *ptrVal = CE->getOperand(0);
247 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
248 if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
251 EmitConstantValueOnly(ptrVal);
253 O << ") + " << Offset;
255 O << ") - " << -Offset;
257 EmitConstantValueOnly(ptrVal);
261 case Instruction::Cast: {
262 // Support only non-converting or widening casts for now, that is, ones
263 // that do not involve a change in value. This assertion is really gross,
264 // and may not even be a complete check.
265 Constant *Op = CE->getOperand(0);
266 const Type *OpTy = Op->getType(), *Ty = CE->getType();
268 // Remember, kids, pointers can be losslessly converted back and forth
269 // into 32-bit or wider integers, regardless of signedness. :-P
270 assert(((isa<PointerType>(OpTy)
271 && (Ty == Type::LongTy || Ty == Type::ULongTy
272 || Ty == Type::IntTy || Ty == Type::UIntTy))
273 || (isa<PointerType>(Ty)
274 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
275 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
276 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
277 && OpTy->isLosslesslyConvertibleTo(Ty))))
278 && "FIXME: Don't yet support this kind of constant cast expr");
279 EmitConstantValueOnly(Op);
282 case Instruction::Add:
284 EmitConstantValueOnly(CE->getOperand(0));
286 EmitConstantValueOnly(CE->getOperand(1));
290 assert(0 && "Unsupported operator!");
293 assert(0 && "Unknown constant value!");
297 /// toOctal - Convert the low order bits of X into an octal digit.
299 static inline char toOctal(int X) {
303 /// printAsCString - Print the specified array as a C compatible string, only if
304 /// the predicate isString is true.
306 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
308 assert(CVA->isString() && "Array is not string compatible!");
311 for (unsigned i = 0; i != LastElt; ++i) {
313 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
317 } else if (C == '\\') {
319 } else if (isprint(C)) {
323 case '\b': O << "\\b"; break;
324 case '\f': O << "\\f"; break;
325 case '\n': O << "\\n"; break;
326 case '\r': O << "\\r"; break;
327 case '\t': O << "\\t"; break;
330 O << toOctal(C >> 6);
331 O << toOctal(C >> 3);
332 O << toOctal(C >> 0);
340 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
342 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
343 const TargetData &TD = TM.getTargetData();
345 if (CV->isNullValue() || isa<UndefValue>(CV)) {
346 EmitZeros(TD.getTypeSize(CV->getType()));
348 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
349 if (CVA->isString()) {
350 unsigned NumElts = CVA->getNumOperands();
351 if (AscizDirective && NumElts &&
352 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
354 printAsCString(O, CVA, NumElts-1);
357 printAsCString(O, CVA, NumElts);
360 } else { // Not a string. Print the values in successive locations
361 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
362 EmitGlobalConstant(CVA->getOperand(i));
365 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
366 // Print the fields in successive locations. Pad to align if needed!
367 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
368 uint64_t sizeSoFar = 0;
369 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
370 const Constant* field = CVS->getOperand(i);
372 // Check if padding is needed and insert one or more 0s.
373 uint64_t fieldSize = TD.getTypeSize(field->getType());
374 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
375 : cvsLayout->MemberOffsets[i+1])
376 - cvsLayout->MemberOffsets[i]) - fieldSize;
377 sizeSoFar += fieldSize + padSize;
379 // Now print the actual field value
380 EmitGlobalConstant(field);
382 // Insert the field padding unless it's zero bytes...
385 assert(sizeSoFar == cvsLayout->StructSize &&
386 "Layout of constant struct may be incorrect!");
388 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
389 // FP Constants are printed as integer constants to avoid losing
391 double Val = CFP->getValue();
392 if (CFP->getType() == Type::DoubleTy) {
393 if (Data64bitsDirective)
394 O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
395 << " double value: " << Val << "\n";
396 else if (TD.isBigEndian()) {
397 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
398 << "\t" << CommentString << " double most significant word "
400 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
401 << "\t" << CommentString << " double least significant word "
404 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
405 << "\t" << CommentString << " double least significant word " << Val
407 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
408 << "\t" << CommentString << " double most significant word " << Val
413 O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
414 << " float " << Val << "\n";
417 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
418 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
419 uint64_t Val = CI->getRawValue();
421 if (Data64bitsDirective)
422 O << Data64bitsDirective << Val << "\n";
423 else if (TD.isBigEndian()) {
424 O << Data32bitsDirective << unsigned(Val >> 32)
425 << "\t" << CommentString << " Double-word most significant word "
427 O << Data32bitsDirective << unsigned(Val)
428 << "\t" << CommentString << " Double-word least significant word "
431 O << Data32bitsDirective << unsigned(Val)
432 << "\t" << CommentString << " Double-word least significant word "
434 O << Data32bitsDirective << unsigned(Val >> 32)
435 << "\t" << CommentString << " Double-word most significant word "
440 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
441 const PackedType *PTy = CP->getType();
443 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
444 EmitGlobalConstant(CP->getOperand(I));
449 const Type *type = CV->getType();
450 switch (type->getTypeID()) {
452 case Type::UByteTyID: case Type::SByteTyID:
453 O << Data8bitsDirective;
455 case Type::UShortTyID: case Type::ShortTyID:
456 O << Data16bitsDirective;
458 case Type::PointerTyID:
459 if (TD.getPointerSize() == 8) {
460 O << Data64bitsDirective;
463 //Fall through for pointer size == int size
464 case Type::UIntTyID: case Type::IntTyID:
465 O << Data32bitsDirective;
467 case Type::ULongTyID: case Type::LongTyID:
468 assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
469 O << Data64bitsDirective;
471 case Type::FloatTyID: case Type::DoubleTyID:
472 assert (0 && "Should have already output floating point constant.");
474 assert (0 && "Can't handle printing this type of thing");
477 EmitConstantValueOnly(CV);
481 /// printInlineAsm - This method formats and prints the specified machine
482 /// instruction that is an inline asm.
483 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 char Modifier[2] = { 0, 0 };
543 if (HasCurlyBraces) {
544 // If we have curly braces, check for a modifier character. This
545 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
546 if (*LastEmitted == ':') {
547 ++LastEmitted; // Consume ':' character.
548 if (*LastEmitted == 0) {
549 std::cerr << "Bad ${:} expression in inline asm string: '"
554 Modifier[0] = *LastEmitted;
555 ++LastEmitted; // Consume modifier character.
558 if (*LastEmitted != '}') {
559 std::cerr << "Bad ${} expression in inline asm string: '"
563 ++LastEmitted; // Consume '}' character.
566 if ((unsigned)Val >= NumOperands-1) {
567 std::cerr << "Invalid $ operand number in inline asm string: '"
572 char ExtraCode = 0; // FIXME:
574 // Okay, we finally have an operand number. Ask the target to print this
576 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
577 if (const_cast<AsmPrinter*>(this)->
578 PrintAsmOperand(MI, Val+1, AsmPrinterVariant,
579 Modifier[0] ? Modifier : 0)) {
580 std::cerr << "Invalid operand found in inline asm: '"
588 ++LastEmitted; // Consume '{' character.
589 if (CurVariant != -1) {
590 std::cerr << "Nested variants found in inline asm string: '"
594 CurVariant = 0; // We're in the first variant now.
597 ++LastEmitted; // consume '|' character.
598 if (CurVariant == -1) {
599 std::cerr << "Found '|' character outside of variant in inline asm "
600 << "string: '" << AsmStr << "'\n";
603 ++CurVariant; // We're in the next variant.
606 ++LastEmitted; // consume '}' character.
607 if (CurVariant == -1) {
608 std::cerr << "Found '}' character outside of variant in inline asm "
609 << "string: '" << AsmStr << "'\n";
616 O << "\n" << InlineAsmEnd;
619 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
620 /// instruction, using the specified assembler variant. Targets should
621 /// overried this to format as appropriate.
622 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
623 unsigned AsmVariant, const char *ExtraCode) {
624 // Target doesn't support this yet!