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"
25 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
26 : FunctionNumber(0), O(o), TM(tm),
29 PrivateGlobalPrefix("."),
30 GlobalVarAddrPrefix(""),
31 GlobalVarAddrSuffix(""),
32 FunctionAddrPrefix(""),
33 FunctionAddrSuffix(""),
34 ZeroDirective("\t.zero\t"),
35 AsciiDirective("\t.ascii\t"),
36 AscizDirective("\t.asciz\t"),
37 Data8bitsDirective("\t.byte\t"),
38 Data16bitsDirective("\t.short\t"),
39 Data32bitsDirective("\t.long\t"),
40 Data64bitsDirective("\t.quad\t"),
41 AlignDirective("\t.align\t"),
42 AlignmentIsInBytes(true),
43 SwitchToSectionDirective("\t.section\t"),
44 ConstantPoolSection("\t.section .rodata\n"),
45 StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
46 StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
48 COMMDirective("\t.comm\t"),
49 COMMDirectiveTakesAlignment(true),
50 HasDotTypeDotSizeDirective(true) {
54 /// SwitchSection - Switch to the specified section of the executable if we
55 /// are not already in it!
57 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
60 if (GV && GV->hasSection())
61 NS = SwitchToSectionDirective + GV->getSection();
63 NS = std::string("\t")+NewSection;
65 if (CurrentSection != NS) {
67 if (!CurrentSection.empty())
68 O << CurrentSection << '\n';
72 bool AsmPrinter::doInitialization(Module &M) {
73 Mang = new Mangler(M, GlobalPrefix);
74 SwitchSection("", 0); // Reset back to no section.
78 bool AsmPrinter::doFinalization(Module &M) {
79 delete Mang; Mang = 0;
83 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
84 // What's my mangled name?
85 CurrentFnName = Mang->getValueName(MF.getFunction());
86 IncrementFunctionNumber();
89 /// EmitConstantPool - Print to the current output stream assembly
90 /// representations of the constants in the constant pool MCP. This is
91 /// used to print out constants which have been "spilled to memory" by
92 /// the code generator.
94 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
95 const std::vector<Constant*> &CP = MCP->getConstants();
96 if (CP.empty()) return;
97 const TargetData &TD = TM.getTargetData();
99 SwitchSection(ConstantPoolSection, 0);
100 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
101 // FIXME: force doubles to be naturally aligned. We should handle this
102 // more correctly in the future.
103 unsigned Alignment = TD.getTypeAlignmentShift(CP[i]->getType());
104 if (CP[i]->getType() == Type::DoubleTy && Alignment < 3) Alignment = 3;
106 EmitAlignment(Alignment);
107 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
108 << ":\t\t\t\t\t" << CommentString << *CP[i] << '\n';
109 EmitGlobalConstant(CP[i]);
113 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
114 /// special global used by LLVM. If so, emit it and return true, otherwise
115 /// do nothing and return false.
116 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
117 assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
118 "Not a special LLVM global!");
120 if (GV->getName() == "llvm.used")
121 return true; // No need to emit this at all.
123 if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
124 SwitchSection(StaticCtorsSection, 0);
126 EmitXXStructorList(GV->getInitializer());
130 if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
131 SwitchSection(StaticDtorsSection, 0);
133 EmitXXStructorList(GV->getInitializer());
140 /// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
141 /// function pointers, ignoring the init priority.
142 void AsmPrinter::EmitXXStructorList(Constant *List) {
143 // Should be an array of '{ int, void ()* }' structs. The first value is the
144 // init priority, which we ignore.
145 if (!isa<ConstantArray>(List)) return;
146 ConstantArray *InitList = cast<ConstantArray>(List);
147 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
148 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
149 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
151 if (CS->getOperand(1)->isNullValue())
152 return; // Found a null terminator, exit printing.
153 // Emit the function pointer.
154 EmitGlobalConstant(CS->getOperand(1));
159 // EmitAlignment - Emit an alignment directive to the specified power of two.
160 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
161 if (GV && GV->getAlignment())
162 NumBits = Log2_32(GV->getAlignment());
163 if (NumBits == 0) return; // No need to emit alignment.
164 if (AlignmentIsInBytes) NumBits = 1 << NumBits;
165 O << AlignDirective << NumBits << "\n";
168 /// EmitZeros - Emit a block of zeros.
170 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
173 O << ZeroDirective << NumZeros << "\n";
175 for (; NumZeros; --NumZeros)
176 O << Data8bitsDirective << "0\n";
181 // Print out the specified constant, without a storage class. Only the
182 // constants valid in constant expressions can occur here.
183 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
184 if (CV->isNullValue() || isa<UndefValue>(CV))
186 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
187 assert(CB == ConstantBool::True);
189 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
190 if (((CI->getValue() << 32) >> 32) == CI->getValue())
193 O << (uint64_t)CI->getValue();
194 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
196 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
197 // This is a constant address for a global variable or function. Use the
198 // name of the variable or function as the address value, possibly
199 // decorating it with GlobalVarAddrPrefix/Suffix or
200 // FunctionAddrPrefix/Suffix (these all default to "" )
201 if (isa<Function>(GV))
202 O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
204 O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
205 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
206 const TargetData &TD = TM.getTargetData();
207 switch(CE->getOpcode()) {
208 case Instruction::GetElementPtr: {
209 // generate a symbolic expression for the byte address
210 const Constant *ptrVal = CE->getOperand(0);
211 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
212 if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
215 EmitConstantValueOnly(ptrVal);
217 O << ") + " << Offset;
219 O << ") - " << -Offset;
221 EmitConstantValueOnly(ptrVal);
225 case Instruction::Cast: {
226 // Support only non-converting or widening casts for now, that is, ones
227 // that do not involve a change in value. This assertion is really gross,
228 // and may not even be a complete check.
229 Constant *Op = CE->getOperand(0);
230 const Type *OpTy = Op->getType(), *Ty = CE->getType();
232 // Remember, kids, pointers can be losslessly converted back and forth
233 // into 32-bit or wider integers, regardless of signedness. :-P
234 assert(((isa<PointerType>(OpTy)
235 && (Ty == Type::LongTy || Ty == Type::ULongTy
236 || Ty == Type::IntTy || Ty == Type::UIntTy))
237 || (isa<PointerType>(Ty)
238 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
239 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
240 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
241 && OpTy->isLosslesslyConvertibleTo(Ty))))
242 && "FIXME: Don't yet support this kind of constant cast expr");
243 EmitConstantValueOnly(Op);
246 case Instruction::Add:
248 EmitConstantValueOnly(CE->getOperand(0));
250 EmitConstantValueOnly(CE->getOperand(1));
254 assert(0 && "Unsupported operator!");
257 assert(0 && "Unknown constant value!");
261 /// toOctal - Convert the low order bits of X into an octal digit.
263 static inline char toOctal(int X) {
267 /// printAsCString - Print the specified array as a C compatible string, only if
268 /// the predicate isString is true.
270 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
272 assert(CVA->isString() && "Array is not string compatible!");
275 for (unsigned i = 0; i != LastElt; ++i) {
277 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
281 } else if (C == '\\') {
283 } else if (isprint(C)) {
287 case '\b': O << "\\b"; break;
288 case '\f': O << "\\f"; break;
289 case '\n': O << "\\n"; break;
290 case '\r': O << "\\r"; break;
291 case '\t': O << "\\t"; break;
294 O << toOctal(C >> 6);
295 O << toOctal(C >> 3);
296 O << toOctal(C >> 0);
304 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
306 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
307 const TargetData &TD = TM.getTargetData();
309 if (CV->isNullValue() || isa<UndefValue>(CV)) {
310 EmitZeros(TD.getTypeSize(CV->getType()));
312 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
313 if (CVA->isString()) {
314 unsigned NumElts = CVA->getNumOperands();
315 if (AscizDirective && NumElts &&
316 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
318 printAsCString(O, CVA, NumElts-1);
321 printAsCString(O, CVA, NumElts);
324 } else { // Not a string. Print the values in successive locations
325 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
326 EmitGlobalConstant(CVA->getOperand(i));
329 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
330 // Print the fields in successive locations. Pad to align if needed!
331 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
332 uint64_t sizeSoFar = 0;
333 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
334 const Constant* field = CVS->getOperand(i);
336 // Check if padding is needed and insert one or more 0s.
337 uint64_t fieldSize = TD.getTypeSize(field->getType());
338 uint64_t padSize = ((i == e-1? cvsLayout->StructSize
339 : cvsLayout->MemberOffsets[i+1])
340 - cvsLayout->MemberOffsets[i]) - fieldSize;
341 sizeSoFar += fieldSize + padSize;
343 // Now print the actual field value
344 EmitGlobalConstant(field);
346 // Insert the field padding unless it's zero bytes...
349 assert(sizeSoFar == cvsLayout->StructSize &&
350 "Layout of constant struct may be incorrect!");
352 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
353 // FP Constants are printed as integer constants to avoid losing
355 double Val = CFP->getValue();
356 if (CFP->getType() == Type::DoubleTy) {
357 if (Data64bitsDirective)
358 O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
359 << " double value: " << Val << "\n";
360 else if (TD.isBigEndian()) {
361 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
362 << "\t" << CommentString << " double most significant word "
364 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
365 << "\t" << CommentString << " double least significant word "
368 O << Data32bitsDirective << unsigned(DoubleToBits(Val))
369 << "\t" << CommentString << " double least significant word " << Val
371 O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
372 << "\t" << CommentString << " double most significant word " << Val
377 O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
378 << " float " << Val << "\n";
381 } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
382 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
383 uint64_t Val = CI->getRawValue();
385 if (Data64bitsDirective)
386 O << Data64bitsDirective << Val << "\n";
387 else if (TD.isBigEndian()) {
388 O << Data32bitsDirective << unsigned(Val >> 32)
389 << "\t" << CommentString << " Double-word most significant word "
391 O << Data32bitsDirective << unsigned(Val)
392 << "\t" << CommentString << " Double-word least significant word "
395 O << Data32bitsDirective << unsigned(Val)
396 << "\t" << CommentString << " Double-word least significant word "
398 O << Data32bitsDirective << unsigned(Val >> 32)
399 << "\t" << CommentString << " Double-word most significant word "
404 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
405 const PackedType *PTy = CP->getType();
407 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
408 EmitGlobalConstant(CP->getOperand(I));
413 const Type *type = CV->getType();
414 switch (type->getTypeID()) {
416 case Type::UByteTyID: case Type::SByteTyID:
417 O << Data8bitsDirective;
419 case Type::UShortTyID: case Type::ShortTyID:
420 O << Data16bitsDirective;
422 case Type::PointerTyID:
423 if (TD.getPointerSize() == 8) {
424 O << Data64bitsDirective;
427 //Fall through for pointer size == int size
428 case Type::UIntTyID: case Type::IntTyID:
429 O << Data32bitsDirective;
431 case Type::ULongTyID: case Type::LongTyID:
432 assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
433 O << Data64bitsDirective;
435 case Type::FloatTyID: case Type::DoubleTyID:
436 assert (0 && "Should have already output floating point constant.");
438 assert (0 && "Can't handle printing this type of thing");
441 EmitConstantValueOnly(CV);