blob: bf3d4241e3b3fafe27b82a5d20d70470a4ff88d0 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
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"
Chris Lattner31a54742010-01-16 21:57:06 +000019#include "llvm/CodeGen/DwarfWriter.h"
Gordon Henriksen1aed5992008-08-17 18:44:35 +000020#include "llvm/CodeGen/GCMetadataPrinter.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/CodeGen/MachineConstantPool.h"
David Greeneca9b04b2009-11-13 21:34:57 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
David Greene066ed6a2009-08-18 19:22:55 +000023#include "llvm/CodeGen/MachineFunction.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
David Greenee52fd872009-08-10 16:38:07 +000025#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000026#include "llvm/CodeGen/MachineModuleInfo.h"
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +000027#include "llvm/Analysis/DebugInfo.h"
Chris Lattner1eb0ad02009-07-27 21:28:04 +000028#include "llvm/MC/MCContext.h"
David Greene4a37a692009-07-16 22:24:20 +000029#include "llvm/MC/MCInst.h"
Chris Lattnere6ad12f2009-07-31 18:48:30 +000030#include "llvm/MC/MCSection.h"
31#include "llvm/MC/MCStreamer.h"
Chris Lattner08c97082009-09-12 23:02:08 +000032#include "llvm/MC/MCSymbol.h"
Evan Cheng42ceb472009-03-25 01:47:28 +000033#include "llvm/Support/CommandLine.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc006e1c2010-01-22 19:52:01 +000035#include "llvm/Support/Format.h"
David Greene63486122009-07-13 20:25:48 +000036#include "llvm/Support/FormattedStream.h"
Chris Lattner621c44d2009-08-22 20:48:53 +000037#include "llvm/MC/MCAsmInfo.h"
Chris Lattner31a54742010-01-16 21:57:06 +000038#include "llvm/Target/Mangler.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/Target/TargetData.h"
David Greeneca9b04b2009-11-13 21:34:57 +000040#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include "llvm/Target/TargetLowering.h"
Chris Lattnerc4c40a92009-07-28 03:13:23 +000042#include "llvm/Target/TargetLoweringObjectFile.h"
Evan Cheng0eeed442008-07-01 23:18:29 +000043#include "llvm/Target/TargetOptions.h"
Evan Cheng3c0eda52008-03-15 00:03:38 +000044#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng6fb06762007-11-09 01:32:10 +000045#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner89b36582008-08-17 07:19:36 +000046#include "llvm/ADT/SmallString.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047#include <cerrno>
48using namespace llvm;
49
Evan Cheng42ceb472009-03-25 01:47:28 +000050static cl::opt<cl::boolOrDefault>
51AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
52 cl::init(cl::BOU_UNSET));
53
Chris Lattner1ab24612010-01-22 07:06:15 +000054static bool getVerboseAsm(bool VDef) {
55 switch (AsmVerbose) {
56 default:
57 case cl::BOU_UNSET: return VDef;
58 case cl::BOU_TRUE: return true;
59 case cl::BOU_FALSE: return false;
60 }
61}
62
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063char AsmPrinter::ID = 0;
David Greene302008d2009-07-14 20:18:05 +000064AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm,
Chris Lattner621c44d2009-08-22 20:48:53 +000065 const MCAsmInfo *T, bool VDef)
Daniel Dunbarb10d2222009-07-01 01:48:54 +000066 : MachineFunctionPass(&ID), FunctionNumber(0), O(o),
Chris Lattnera5ef4d32009-08-22 21:43:10 +000067 TM(tm), MAI(T), TRI(tm.getRegisterInfo()),
Chris Lattner1eb0ad02009-07-27 21:28:04 +000068
69 OutContext(*new MCContext()),
Chris Lattnera835afd2009-09-14 03:02:37 +000070 // FIXME: Pass instprinter to streamer.
Chris Lattner92c78e82010-01-20 06:39:07 +000071 OutStreamer(*createAsmStreamer(OutContext, O, *T,
Chris Lattner1ab24612010-01-22 07:06:15 +000072 TM.getTargetData()->isLittleEndian(),
73 getVerboseAsm(VDef), 0)),
Chris Lattner1eb0ad02009-07-27 21:28:04 +000074
Devang Patel042945f2010-01-16 06:09:35 +000075 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) {
Chris Lattner2424eac2009-06-24 19:09:55 +000076 DW = 0; MMI = 0;
Chris Lattner1ab24612010-01-22 07:06:15 +000077 VerboseAsm = getVerboseAsm(VDef);
Evan Cheng42ceb472009-03-25 01:47:28 +000078}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079
Gordon Henriksen3385c9b2008-08-17 12:08:44 +000080AsmPrinter::~AsmPrinter() {
81 for (gcp_iterator I = GCMetadataPrinters.begin(),
82 E = GCMetadataPrinters.end(); I != E; ++I)
83 delete I->second;
Chris Lattner1eb0ad02009-07-27 21:28:04 +000084
85 delete &OutStreamer;
86 delete &OutContext;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +000087}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088
Chris Lattner75bdd292009-08-03 19:12:26 +000089TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Chris Lattnerc4c40a92009-07-28 03:13:23 +000090 return TM.getTargetLowering()->getObjFileLowering();
91}
92
Chris Lattnerd69d8ad2009-08-18 06:15:16 +000093/// getCurrentSection() - Return the current section we are emitting to.
94const MCSection *AsmPrinter::getCurrentSection() const {
95 return OutStreamer.getCurrentSection();
96}
97
98
Gordon Henriksendf87fdc2008-01-07 01:30:38 +000099void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +0000100 AU.setPreservesAll();
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000101 MachineFunctionPass::getAnalysisUsage(AU);
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000102 AU.addRequired<GCModuleInfo>();
David Greene066ed6a2009-08-18 19:22:55 +0000103 if (VerboseAsm)
David Greenee52fd872009-08-10 16:38:07 +0000104 AU.addRequired<MachineLoopInfo>();
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000105}
106
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107bool AsmPrinter::doInitialization(Module &M) {
Chris Lattner01316272009-07-31 17:42:42 +0000108 // Initialize TargetLoweringObjectFile.
109 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
110 .Initialize(OutContext, TM);
111
Chris Lattner63ab9bb2010-01-17 18:22:35 +0000112 Mang = new Mangler(*MAI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113
Bob Wilsonb5f835e2009-09-30 22:06:26 +0000114 // Allow the target to emit any magic that it wants at the start of the file.
115 EmitStartOfAsmFile(M);
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000116
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000117 if (MAI->hasSingleParameterDotFile()) {
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000118 /* Very minimal debug info. It is ignored if we emit actual
Bob Wilson6ed4b622009-09-30 21:26:13 +0000119 debug info. If we don't, this at least helps the user find where
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000120 a function came from. */
121 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n";
122 }
123
Bob Wilsonb5f835e2009-09-30 22:06:26 +0000124 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
125 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000126 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
127 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000128 MP->beginAssembly(O, *this, *MAI);
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000129
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 if (!M.getModuleInlineAsm().empty())
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000131 O << MAI->getCommentString() << " Start of file scope inline assembly\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 << M.getModuleInlineAsm()
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000133 << '\n' << MAI->getCommentString()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 << " End of file scope inline assembly\n";
135
Chris Lattnerc73e8eb2009-09-24 05:44:53 +0000136 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
137 if (MMI)
138 MMI->AnalyzeModule(M);
139 DW = getAnalysisIfAvailable<DwarfWriter>();
Sanjiv Gupta5461b522009-11-14 07:22:25 +0000140 if (DW)
Chris Lattnerc73e8eb2009-09-24 05:44:53 +0000141 DW->BeginModule(&M, MMI, O, this, MAI);
Devang Patel1a454842009-06-19 21:54:26 +0000142
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143 return false;
144}
145
Chris Lattnerd9609472010-01-19 04:39:15 +0000146/// EmitGlobalVariable - Emit the specified global variable to the .s file.
147void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
148 if (!GV->hasInitializer()) // External globals require no code.
149 return;
150
151 // Check to see if this is a special global used by LLVM, if so, emit it.
152 if (EmitSpecialLLVMGlobal(GV))
153 return;
Chris Lattner410c9472010-01-19 05:38:33 +0000154
155 MCSymbol *GVSym = GetGlobalValueSymbol(GV);
156 printVisibility(GVSym, GV->getVisibility());
157
158 if (MAI->hasDotTypeDotSizeDirective()) {
159 O << "\t.type\t" << *GVSym;
160 if (MAI->getCommentString()[0] != '@')
161 O << ",@object\n";
162 else
163 O << ",%object\n";
164 }
Chris Lattnerd9609472010-01-19 04:39:15 +0000165
Chris Lattner410c9472010-01-19 05:38:33 +0000166 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
167
168 const TargetData *TD = TM.getTargetData();
169 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
170 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
171
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000172 // Handle common and BSS local symbols (.lcomm).
173 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
Chris Lattner410c9472010-01-19 05:38:33 +0000174 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
175
Chris Lattner410c9472010-01-19 05:38:33 +0000176 if (VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000177 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
178 /*PrintType=*/false, GV->getParent());
179 OutStreamer.GetCommentOS() << '\n';
Chris Lattner410c9472010-01-19 05:38:33 +0000180 }
Chris Lattnerf26c7792010-01-19 06:25:51 +0000181
182 // Handle common symbols.
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000183 if (GVKind.isCommon()) {
184 // .comm _foo, 42, 4
Chris Lattnerecf1cdc2010-01-19 06:01:04 +0000185 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000186 return;
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000187 }
Chris Lattnerf26c7792010-01-19 06:25:51 +0000188
189 // Handle local BSS symbols.
190 if (MAI->hasMachoZeroFillDirective()) {
191 const MCSection *TheSection =
192 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
193 // .zerofill __DATA, __bss, _foo, 400, 5
194 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
195 return;
196 }
197
198 if (const char *LComm = MAI->getLCOMMDirective()) {
199 // .lcomm _foo, 42
200 O << LComm << *GVSym << ',' << Size;
201 O << '\n';
202 return;
203 }
204
205 // .local _foo
206 O << "\t.local\t" << *GVSym << '\n';
207 // .comm _foo, 42, 4
208 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
Chris Lattner410c9472010-01-19 05:38:33 +0000209 return;
210 }
211
212 const MCSection *TheSection =
213 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
214
215 // Handle the zerofill directive on darwin, which is a special form of BSS
216 // emission.
217 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
218 // .globl _foo
219 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
220 // .zerofill __DATA, __common, _foo, 400, 5
221 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
222 return;
223 }
224
225 OutStreamer.SwitchSection(TheSection);
226
227 // TODO: Factor into an 'emit linkage' thing that is shared with function
228 // bodies.
229 switch (GV->getLinkage()) {
230 case GlobalValue::CommonLinkage:
231 case GlobalValue::LinkOnceAnyLinkage:
232 case GlobalValue::LinkOnceODRLinkage:
233 case GlobalValue::WeakAnyLinkage:
234 case GlobalValue::WeakODRLinkage:
235 case GlobalValue::LinkerPrivateLinkage:
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000236 if (MAI->getWeakDefDirective() != 0) {
Chris Lattner410c9472010-01-19 05:38:33 +0000237 // .globl _foo
238 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
239 // .weak_definition _foo
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000240 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::WeakDefinition);
Chris Lattner410c9472010-01-19 05:38:33 +0000241 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
242 // .globl _foo
243 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
244 // .linkonce same_size
245 O << LinkOnce;
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000246 } else {
247 // .weak _foo
248 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Weak);
249 }
Chris Lattner410c9472010-01-19 05:38:33 +0000250 break;
251 case GlobalValue::DLLExportLinkage:
252 case GlobalValue::AppendingLinkage:
253 // FIXME: appending linkage variables should go into a section of
254 // their name or something. For now, just emit them as external.
255 case GlobalValue::ExternalLinkage:
256 // If external or appending, declare as a global symbol.
257 // .globl _foo
258 OutStreamer.EmitSymbolAttribute(GVSym, MCStreamer::Global);
259 break;
260 case GlobalValue::PrivateLinkage:
261 case GlobalValue::InternalLinkage:
262 break;
263 default:
264 llvm_unreachable("Unknown linkage type!");
265 }
266
267 EmitAlignment(AlignLog, GV);
Chris Lattner410c9472010-01-19 05:38:33 +0000268 if (VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000269 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
270 /*PrintType=*/false, GV->getParent());
271 OutStreamer.GetCommentOS() << '\n';
Chris Lattner410c9472010-01-19 05:38:33 +0000272 }
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000273 OutStreamer.EmitLabel(GVSym);
Chris Lattner410c9472010-01-19 05:38:33 +0000274
275 EmitGlobalConstant(GV->getInitializer());
276
277 if (MAI->hasDotTypeDotSizeDirective())
278 O << "\t.size\t" << *GVSym << ", " << Size << '\n';
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000279
280 OutStreamer.AddBlankLine();
Chris Lattnerd9609472010-01-19 04:39:15 +0000281}
282
283
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284bool AsmPrinter::doFinalization(Module &M) {
Chris Lattnerae982212009-07-21 18:38:57 +0000285 // Emit global variables.
286 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
287 I != E; ++I)
Chris Lattnerd9609472010-01-19 04:39:15 +0000288 EmitGlobalVariable(I);
Chris Lattnerae982212009-07-21 18:38:57 +0000289
Chris Lattnere1225cc2009-06-24 18:54:37 +0000290 // Emit final debug information.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000291 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
Chris Lattnere1225cc2009-06-24 18:54:37 +0000292 DW->EndModule();
293
Chris Lattnerdb191f02009-06-24 18:52:01 +0000294 // If the target wants to know about weak references, print them all.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000295 if (MAI->getWeakRefDirective()) {
Chris Lattnerdb191f02009-06-24 18:52:01 +0000296 // FIXME: This is not lazy, it would be nice to only print weak references
297 // to stuff that is actually used. Note that doing so would require targets
298 // to notice uses in operands (due to constant exprs etc). This should
299 // happen with the MC stuff eventually.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300
Chris Lattnerdb191f02009-06-24 18:52:01 +0000301 // Print out module-level global variables here.
302 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
303 I != E; ++I) {
Chris Lattnercbfe4062010-01-16 18:17:26 +0000304 if (!I->hasExternalWeakLinkage()) continue;
Chris Lattnerce409842010-01-17 21:43:43 +0000305 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
Chris Lattnerdb191f02009-06-24 18:52:01 +0000306 }
307
Chris Lattner0f98c332009-08-03 23:10:34 +0000308 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
Chris Lattnercbfe4062010-01-16 18:17:26 +0000309 if (!I->hasExternalWeakLinkage()) continue;
Chris Lattnerce409842010-01-17 21:43:43 +0000310 O << MAI->getWeakRefDirective() << *GetGlobalValueSymbol(I) << '\n';
Chris Lattnerdb191f02009-06-24 18:52:01 +0000311 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 }
313
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000314 if (MAI->getSetDirective()) {
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000315 O << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
Chris Lattnerdb191f02009-06-24 18:52:01 +0000317 I != E; ++I) {
Chris Lattnerc0c8d7d2010-01-16 01:17:26 +0000318 MCSymbol *Name = GetGlobalValueSymbol(I);
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000319
320 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
Chris Lattnerc0c8d7d2010-01-16 01:17:26 +0000321 MCSymbol *Target = GetGlobalValueSymbol(GV);
Anton Korobeynikovb191f5c2008-09-24 22:21:04 +0000322
Chris Lattnerce409842010-01-17 21:43:43 +0000323 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
324 O << "\t.globl\t" << *Name << '\n';
325 else if (I->hasWeakLinkage())
326 O << MAI->getWeakRefDirective() << *Name << '\n';
327 else
Chris Lattner1ff31942010-01-16 01:37:14 +0000328 assert(I->hasLocalLinkage() && "Invalid alias linkage");
Anton Korobeynikova6f01832008-03-11 21:41:14 +0000329
Anton Korobeynikovb191f5c2008-09-24 22:21:04 +0000330 printVisibility(Name, I->getVisibility());
Anton Korobeynikova6f01832008-03-11 21:41:14 +0000331
Chris Lattnerce409842010-01-17 21:43:43 +0000332 O << MAI->getSetDirective() << ' ' << *Name << ", " << *Target << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 }
334 }
335
Duncan Sands4e0d6a72009-01-28 13:14:17 +0000336 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000337 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
338 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
339 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000340 MP->finishAssembly(O, *this, *MAI);
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000341
Dan Gohmana65530a2008-05-05 00:28:39 +0000342 // If we don't have any trampolines, then we don't require stack memory
343 // to be executable. Some targets have a directive to declare this.
Chris Lattnerdb191f02009-06-24 18:52:01 +0000344 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
Dan Gohmana65530a2008-05-05 00:28:39 +0000345 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000346 if (MAI->getNonexecutableStackDirective())
347 O << MAI->getNonexecutableStackDirective() << '\n';
Dan Gohmana65530a2008-05-05 00:28:39 +0000348
Chris Lattnerb6113072009-09-18 20:17:03 +0000349
350 // Allow the target to emit any magic that it wants at the end of the file,
351 // after everything else has gone out.
352 EmitEndOfAsmFile(M);
353
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354 delete Mang; Mang = 0;
Chris Lattner2424eac2009-06-24 19:09:55 +0000355 DW = 0; MMI = 0;
Chris Lattner1eb0ad02009-07-27 21:28:04 +0000356
357 OutStreamer.Finish();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 return false;
359}
360
361void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
Chris Lattnerac5a6ad2010-01-16 01:24:10 +0000362 // Get the function symbol.
Chris Lattner8d656d92010-01-15 23:55:16 +0000363 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction());
Evan Cheng477013c2007-10-14 05:57:21 +0000364 IncrementFunctionNumber();
David Greenee52fd872009-08-10 16:38:07 +0000365
Chris Lattner57c76b52009-09-16 00:35:39 +0000366 if (VerboseAsm)
David Greenee52fd872009-08-10 16:38:07 +0000367 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368}
369
Evan Cheng68c18682009-03-13 07:51:59 +0000370namespace {
371 // SectionCPs - Keep track the alignment, constpool entries per Section.
372 struct SectionCPs {
Chris Lattnere6ad12f2009-07-31 18:48:30 +0000373 const MCSection *S;
Evan Cheng68c18682009-03-13 07:51:59 +0000374 unsigned Alignment;
375 SmallVector<unsigned, 4> CPEs;
Douglas Gregor8cb41382009-12-19 07:05:23 +0000376 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
Evan Cheng68c18682009-03-13 07:51:59 +0000377 };
378}
379
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380/// EmitConstantPool - Print to the current output stream assembly
381/// representations of the constants in the constant pool MCP. This is
382/// used to print out constants which have been "spilled to memory" by
383/// the code generator.
384///
385void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
386 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
387 if (CP.empty()) return;
388
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000389 // Calculate sections for constant pool entries. We collect entries to go into
390 // the same section together to reduce amount of section switch statements.
Evan Cheng68c18682009-03-13 07:51:59 +0000391 SmallVector<SectionCPs, 4> CPSections;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Chris Lattner680c6f62009-07-22 00:28:43 +0000393 const MachineConstantPoolEntry &CPE = CP[i];
Evan Cheng68c18682009-03-13 07:51:59 +0000394 unsigned Align = CPE.getAlignment();
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000395
396 SectionKind Kind;
397 switch (CPE.getRelocationInfo()) {
398 default: llvm_unreachable("Unknown section kind");
Chris Lattnera9453412009-08-01 23:57:16 +0000399 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000400 case 1:
Chris Lattnera9453412009-08-01 23:57:16 +0000401 Kind = SectionKind::getReadOnlyWithRelLocal();
Chris Lattnered0c6762009-07-26 07:00:12 +0000402 break;
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000403 case 0:
Chris Lattnered0c6762009-07-26 07:00:12 +0000404 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
Chris Lattnera9453412009-08-01 23:57:16 +0000405 case 4: Kind = SectionKind::getMergeableConst4(); break;
406 case 8: Kind = SectionKind::getMergeableConst8(); break;
407 case 16: Kind = SectionKind::getMergeableConst16();break;
408 default: Kind = SectionKind::getMergeableConst(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000409 }
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000410 }
411
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000412 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
Chris Lattner680c6f62009-07-22 00:28:43 +0000413
Evan Cheng68c18682009-03-13 07:51:59 +0000414 // The number of sections are small, just do a linear search from the
415 // last section to the first.
416 bool Found = false;
417 unsigned SecIdx = CPSections.size();
418 while (SecIdx != 0) {
419 if (CPSections[--SecIdx].S == S) {
420 Found = true;
421 break;
422 }
423 }
424 if (!Found) {
425 SecIdx = CPSections.size();
426 CPSections.push_back(SectionCPs(S, Align));
427 }
428
429 if (Align > CPSections[SecIdx].Alignment)
430 CPSections[SecIdx].Alignment = Align;
431 CPSections[SecIdx].CPEs.push_back(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 }
433
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000434 // Now print stuff into the calculated sections.
Evan Cheng68c18682009-03-13 07:51:59 +0000435 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
Chris Lattner73266f92009-08-19 05:49:37 +0000436 OutStreamer.SwitchSection(CPSections[i].S);
Evan Cheng68c18682009-03-13 07:51:59 +0000437 EmitAlignment(Log2_32(CPSections[i].Alignment));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438
Evan Cheng68c18682009-03-13 07:51:59 +0000439 unsigned Offset = 0;
440 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
441 unsigned CPI = CPSections[i].CPEs[j];
442 MachineConstantPoolEntry CPE = CP[CPI];
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000443
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 // Emit inter-object padding for alignment.
Evan Cheng68c18682009-03-13 07:51:59 +0000445 unsigned AlignMask = CPE.getAlignment() - 1;
446 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
Chris Lattnera71dc602010-01-19 19:46:13 +0000447 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
Evan Cheng68c18682009-03-13 07:51:59 +0000448
449 const Type *Ty = CPE.getType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000450 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
Evan Cheng68c18682009-03-13 07:51:59 +0000451
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000452 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
Dan Gohman87581eb2009-08-12 18:32:22 +0000453 << CPI << ':';
Evan Cheng68c18682009-03-13 07:51:59 +0000454 if (VerboseAsm) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000455 O.PadToColumn(MAI->getCommentColumn());
456 O << MAI->getCommentString() << " constant ";
Dan Gohman2aa282f2009-08-13 01:36:44 +0000457 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent());
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000458 }
Evan Cheng68c18682009-03-13 07:51:59 +0000459 O << '\n';
460 if (CPE.isMachineConstantPoolEntry())
461 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
462 else
463 EmitGlobalConstant(CPE.Val.ConstVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 }
465 }
466}
467
468/// EmitJumpTableInfo - Print assembly representations of the jump tables used
469/// by the current function to the current output stream.
470///
471void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI,
472 MachineFunction &MF) {
473 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
474 if (JT.empty()) return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000475
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
477
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000478 // Pick the directive to use to print the jump table entries, and switch to
479 // the appropriate section.
480 TargetLowering *LoweringInfo = TM.getTargetLowering();
481
Anton Korobeynikov7f3fa2c2008-07-09 13:27:16 +0000482 const Function *F = MF.getFunction();
Evan Chengccca6f72009-06-18 20:37:15 +0000483 bool JTInDiffSection = false;
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000484 if (F->isWeakForLinker() ||
485 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 // In PIC mode, we need to emit the jump table to the same section as the
487 // function body itself, otherwise the label differences won't make sense.
Anton Korobeynikov7f3fa2c2008-07-09 13:27:16 +0000488 // We should also do if the section name is NULL or function is declared in
489 // discardable section.
Chris Lattner73266f92009-08-19 05:49:37 +0000490 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang,
491 TM));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000492 } else {
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000493 // Otherwise, drop it in the readonly section.
494 const MCSection *ReadOnlySection =
Chris Lattnera9453412009-08-01 23:57:16 +0000495 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
Chris Lattner73266f92009-08-19 05:49:37 +0000496 OutStreamer.SwitchSection(ReadOnlySection);
Evan Chengccca6f72009-06-18 20:37:15 +0000497 JTInDiffSection = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498 }
499
500 EmitAlignment(Log2_32(MJTI->getAlignment()));
501
502 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
503 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs;
504
505 // If this jump table was deleted, ignore it.
506 if (JTBBs.empty()) continue;
507
508 // For PIC codegen, if possible we want to use the SetDirective to reduce
509 // the number of relocations the assembler will generate for the jump table.
510 // Set directives are all printed before the jump table itself.
Evan Cheng6fb06762007-11-09 01:32:10 +0000511 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets;
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000512 if (MAI->getSetDirective() && IsPic)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Evan Cheng6fb06762007-11-09 01:32:10 +0000514 if (EmittedSets.insert(JTBBs[ii]))
515 printPICJumpTableSetLabel(i, JTBBs[ii]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516
Chris Lattner149495f2009-09-13 19:02:16 +0000517 // On some targets (e.g. Darwin) we want to emit two consequtive labels
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 // before each jump table. The first label is never referenced, but tells
519 // the assembler and linker the extents of the jump table object. The
520 // second label is actually referenced by the code.
Chris Lattner149495f2009-09-13 19:02:16 +0000521 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) {
522 O << MAI->getLinkerPrivateGlobalPrefix()
523 << "JTI" << getFunctionNumber() << '_' << i << ":\n";
Evan Chengccca6f72009-06-18 20:37:15 +0000524 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000526 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
Evan Cheng477013c2007-10-14 05:57:21 +0000527 << '_' << i << ":\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528
529 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000530 printPICJumpTableEntry(MJTI, JTBBs[ii], i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 O << '\n';
532 }
533 }
534}
535
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000536void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
537 const MachineBasicBlock *MBB,
538 unsigned uid) const {
Chris Lattner3fb451e2009-08-11 20:29:57 +0000539 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000540
541 // Use JumpTableDirective otherwise honor the entry size from the jump table
542 // info.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000543 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC);
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000544 bool HadJTEntryDirective = JTEntryDirective != NULL;
545 if (!HadJTEntryDirective) {
546 JTEntryDirective = MJTI->getEntrySize() == 4 ?
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000547 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000548 }
549
550 O << JTEntryDirective << ' ';
551
552 // If we have emitted set directives for the jump table entries, print
553 // them rather than the entries themselves. If we're emitting PIC, then
554 // emit the table entries as differences between two text section labels.
555 // If we're emitting non-PIC code, then emit the entries as direct
556 // references to the target basic blocks.
Chris Lattner3fb451e2009-08-11 20:29:57 +0000557 if (!isPIC) {
Chris Lattnerce409842010-01-17 21:43:43 +0000558 O << *GetMBBSymbol(MBB->getNumber());
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000559 } else if (MAI->getSetDirective()) {
560 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
Chris Lattner3fb451e2009-08-11 20:29:57 +0000561 << '_' << uid << "_set_" << MBB->getNumber();
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000562 } else {
Chris Lattnerce409842010-01-17 21:43:43 +0000563 O << *GetMBBSymbol(MBB->getNumber());
Chris Lattner3fb451e2009-08-11 20:29:57 +0000564 // If the arch uses custom Jump Table directives, don't calc relative to
565 // JT
566 if (!HadJTEntryDirective)
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000567 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI"
Chris Lattner3fb451e2009-08-11 20:29:57 +0000568 << getFunctionNumber() << '_' << uid;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000569 }
570}
571
572
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
574/// special global used by LLVM. If so, emit it and return true, otherwise
575/// do nothing and return false.
576bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Daniel Dunbare03513b2009-07-25 23:55:21 +0000577 if (GV->getName() == "llvm.used") {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000578 if (MAI->getUsedDirective() != 0) // No need to emit this at all.
Andrew Lenharth61d35f52007-08-22 19:33:11 +0000579 EmitLLVMUsedList(GV->getInitializer());
580 return true;
581 }
582
Chris Lattner1e0e0d12009-07-20 06:14:25 +0000583 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
Chris Lattner68433442009-04-13 05:44:34 +0000584 if (GV->getSection() == "llvm.metadata" ||
585 GV->hasAvailableExternallyLinkage())
586 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587
588 if (!GV->hasAppendingLinkage()) return false;
589
590 assert(GV->hasInitializer() && "Not a special LLVM global!");
591
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000592 const TargetData *TD = TM.getTargetData();
593 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
Chris Lattner0c433e92009-03-09 05:52:15 +0000594 if (GV->getName() == "llvm.global_ctors") {
Chris Lattner73266f92009-08-19 05:49:37 +0000595 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
Chris Lattner1e0e4892009-03-09 08:18:48 +0000596 EmitAlignment(Align, 0);
597 EmitXXStructorList(GV->getInitializer());
Chris Lattner2f2fe052010-01-19 04:34:02 +0000598
599 if (TM.getRelocationModel() == Reloc::Static &&
600 MAI->hasStaticCtorDtorReferenceInStaticMode())
601 O << ".reference .constructors_used\n";
Chris Lattner1e0e4892009-03-09 08:18:48 +0000602 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 }
604
Chris Lattner0c433e92009-03-09 05:52:15 +0000605 if (GV->getName() == "llvm.global_dtors") {
Chris Lattner73266f92009-08-19 05:49:37 +0000606 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
Chris Lattner1e0e4892009-03-09 08:18:48 +0000607 EmitAlignment(Align, 0);
608 EmitXXStructorList(GV->getInitializer());
Chris Lattner2f2fe052010-01-19 04:34:02 +0000609
610 if (TM.getRelocationModel() == Reloc::Static &&
611 MAI->hasStaticCtorDtorReferenceInStaticMode())
612 O << ".reference .destructors_used\n";
Chris Lattner1e0e4892009-03-09 08:18:48 +0000613 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 }
615
616 return false;
617}
618
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000619/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
Dale Johannesen60567622008-09-09 22:29:13 +0000620/// global in the specified llvm.used list for which emitUsedDirectiveFor
621/// is true, as being used with this directive.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622void AsmPrinter::EmitLLVMUsedList(Constant *List) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000623 const char *Directive = MAI->getUsedDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624
Dan Gohman9e1657f2009-06-14 23:30:43 +0000625 // Should be an array of 'i8*'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
627 if (InitList == 0) return;
628
629 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner3f621b32009-07-17 22:00:23 +0000630 const GlobalValue *GV =
631 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
Chris Lattner84362ac2009-07-31 20:52:39 +0000632 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) {
Dale Johannesen4911fb82008-09-03 20:34:58 +0000633 O << Directive;
634 EmitConstantValueOnly(InitList->getOperand(i));
635 O << '\n';
636 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 }
638}
639
640/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
641/// function pointers, ignoring the init priority.
642void AsmPrinter::EmitXXStructorList(Constant *List) {
643 // Should be an array of '{ int, void ()* }' structs. The first value is the
644 // init priority, which we ignore.
645 if (!isa<ConstantArray>(List)) return;
646 ConstantArray *InitList = cast<ConstantArray>(List);
647 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
648 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
649 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
650
651 if (CS->getOperand(1)->isNullValue())
652 return; // Found a null terminator, exit printing.
653 // Emit the function pointer.
654 EmitGlobalConstant(CS->getOperand(1));
655 }
656}
657
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658
659//===----------------------------------------------------------------------===//
660/// LEB 128 number encoding.
661
Bob Wilsoncda028f2009-11-06 22:38:38 +0000662/// PrintULEB128 - Print a series of hexadecimal values (separated by commas)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663/// representing an unsigned leb128 value.
664void AsmPrinter::PrintULEB128(unsigned Value) const {
665 do {
Chris Lattner83b7a2c2008-11-10 04:35:24 +0000666 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667 Value >>= 7;
668 if (Value) Byte |= 0x80;
Chris Lattner052348e2010-01-22 21:57:56 +0000669 O << "0x";
670 O.write_hex(Byte);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 if (Value) O << ", ";
672 } while (Value);
673}
674
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676//===--------------------------------------------------------------------===//
677// Emission and print routines
678//
679
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680/// EOL - Print a newline character to asm stream. If a comment is present
681/// then it will be printed first. Comments should not contain '\n'.
Benjamin Kramer0ad2db92010-01-17 07:46:39 +0000682void AsmPrinter::EOL(const Twine &Comment) const {
683 if (VerboseAsm && !Comment.isTriviallyEmpty()) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000684 O.PadToColumn(MAI->getCommentColumn());
Chris Lattnere795ca52010-01-20 07:19:19 +0000685 O << MAI->getCommentString() << ' ' << Comment;
Owen Anderson367bfbb2008-07-01 21:16:27 +0000686 }
687 O << '\n';
688}
689
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
691/// unsigned leb128 value.
692void AsmPrinter::EmitULEB128Bytes(unsigned Value) const {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000693 if (MAI->hasLEB128()) {
Chris Lattner20f334f2010-01-22 22:56:55 +0000694 O << "\t.uleb128\t" << Value;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 } else {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000696 O << MAI->getData8bitsDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697 PrintULEB128(Value);
698 }
699}
700
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701/// EmitInt8 - Emit a byte directive and value.
702///
703void AsmPrinter::EmitInt8(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000704 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705}
706
707/// EmitInt16 - Emit a short directive and value.
708///
709void AsmPrinter::EmitInt16(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000710 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711}
712
713/// EmitInt32 - Emit a long directive and value.
714///
715void AsmPrinter::EmitInt32(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000716 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717}
718
719/// EmitInt64 - Emit a long long directive and value.
720///
721void AsmPrinter::EmitInt64(uint64_t Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000722 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723}
724
725/// toOctal - Convert the low order bits of X into an octal digit.
726///
727static inline char toOctal(int X) {
728 return (X&7)+'0';
729}
730
731/// printStringChar - Print a char, escaped if necessary.
732///
David Greene302008d2009-07-14 20:18:05 +0000733static void printStringChar(formatted_raw_ostream &O, unsigned char C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 if (C == '"') {
735 O << "\\\"";
736 } else if (C == '\\') {
737 O << "\\\\";
Chris Lattner07ec1462009-01-22 23:38:45 +0000738 } else if (isprint((unsigned char)C)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 O << C;
740 } else {
741 switch(C) {
742 case '\b': O << "\\b"; break;
743 case '\f': O << "\\f"; break;
744 case '\n': O << "\\n"; break;
745 case '\r': O << "\\r"; break;
746 case '\t': O << "\\t"; break;
747 default:
748 O << '\\';
749 O << toOctal(C >> 6);
750 O << toOctal(C >> 3);
751 O << toOctal(C >> 0);
752 break;
753 }
754 }
755}
756
757/// EmitString - Emit a string with quotes and a null terminator.
758/// Special characters are emitted properly.
759/// \literal (Eg. '\t') \endliteral
Devang Patelc10337d2009-11-24 19:42:17 +0000760void AsmPrinter::EmitString(const StringRef String) const {
Dan Gohmana5d39352009-11-13 21:55:31 +0000761 EmitString(String.data(), String.size());
Bill Wendling3f94b412009-04-09 23:51:31 +0000762}
763
764void AsmPrinter::EmitString(const char *String, unsigned Size) const {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000765 const char* AscizDirective = MAI->getAscizDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 if (AscizDirective)
767 O << AscizDirective;
768 else
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000769 O << MAI->getAsciiDirective();
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000770 O << '\"';
Bill Wendling3f94b412009-04-09 23:51:31 +0000771 for (unsigned i = 0; i < Size; ++i)
Chris Lattnere2d4bf72009-04-08 00:28:38 +0000772 printStringChar(O, String[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 if (AscizDirective)
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000774 O << '\"';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 else
776 O << "\\0\"";
777}
778
779
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000780/// EmitFile - Emit a .file directive.
Benjamin Kramer0ad2db92010-01-17 07:46:39 +0000781void AsmPrinter::EmitFile(unsigned Number, StringRef Name) const {
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000782 O << "\t.file\t" << Number << " \"";
Chris Lattnere2d4bf72009-04-08 00:28:38 +0000783 for (unsigned i = 0, N = Name.size(); i < N; ++i)
784 printStringChar(O, Name[i]);
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000785 O << '\"';
Dan Gohmane7ba1be2007-09-24 20:58:13 +0000786}
787
788
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789//===----------------------------------------------------------------------===//
790
791// EmitAlignment - Emit an alignment directive to the specified power of
792// two boundary. For example, if you pass in 3 here, you will get an 8
793// byte alignment. If a global value is specified, and if that global has
794// an explicit alignment requested, it will unconditionally override the
795// alignment request. However, if ForcedAlignBits is specified, this value
796// has final say: the ultimate alignment will be the max of ForcedAlignBits
797// and the alignment computed with NumBits and the global.
798//
799// The algorithm is:
800// Align = NumBits;
801// if (GV && GV->hasalignment) Align = GV->getalignment();
802// Align = std::max(Align, ForcedAlignBits);
803//
804void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Cheng7e7d1942008-02-29 19:36:59 +0000805 unsigned ForcedAlignBits,
806 bool UseFillExpr) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 if (GV && GV->getAlignment())
808 NumBits = Log2_32(GV->getAlignment());
809 NumBits = std::max(NumBits, ForcedAlignBits);
810
811 if (NumBits == 0) return; // No need to emit alignment.
Chris Lattner4891d142009-08-19 06:12:02 +0000812
813 unsigned FillValue = 0;
Chris Lattnerd69d8ad2009-08-18 06:15:16 +0000814 if (getCurrentSection()->getKind().isText())
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000815 FillValue = MAI->getTextAlignFillValue();
Chris Lattner4891d142009-08-19 06:12:02 +0000816
817 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818}
David Greenecdc2de32009-08-05 21:00:52 +0000819
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820// Print out the specified constant, without a storage class. Only the
821// constants valid in constant expressions can occur here.
822void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
Chris Lattner458c8772010-01-13 04:29:19 +0000823 if (CV->isNullValue() || isa<UndefValue>(CV)) {
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000824 O << '0';
Chris Lattner458c8772010-01-13 04:29:19 +0000825 return;
826 }
827
828 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Scott Michel2c1d0552008-06-03 06:18:19 +0000829 O << CI->getZExtValue();
Chris Lattner458c8772010-01-13 04:29:19 +0000830 return;
831 }
832
833 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 // This is a constant address for a global variable or function. Use the
Chris Lattner36d03292009-09-15 23:11:32 +0000835 // name of the variable or function as the address value.
Chris Lattnerce409842010-01-17 21:43:43 +0000836 O << *GetGlobalValueSymbol(GV);
Chris Lattner458c8772010-01-13 04:29:19 +0000837 return;
838 }
839
840 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
Chris Lattnerce409842010-01-17 21:43:43 +0000841 O << *GetBlockAddressSymbol(BA);
Chris Lattner458c8772010-01-13 04:29:19 +0000842 return;
843 }
844
845 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
846 if (CE == 0) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000847 llvm_unreachable("Unknown constant value!");
Chris Lattner458c8772010-01-13 04:29:19 +0000848 O << '0';
849 return;
850 }
851
852 switch (CE->getOpcode()) {
853 case Instruction::ZExt:
854 case Instruction::SExt:
855 case Instruction::FPTrunc:
856 case Instruction::FPExt:
857 case Instruction::UIToFP:
858 case Instruction::SIToFP:
859 case Instruction::FPToUI:
860 case Instruction::FPToSI:
861 default:
862 llvm_unreachable("FIXME: Don't support this constant cast expr");
863 case Instruction::GetElementPtr: {
864 // generate a symbolic expression for the byte address
865 const TargetData *TD = TM.getTargetData();
866 const Constant *ptrVal = CE->getOperand(0);
867 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
868 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
869 idxVec.size());
870 if (Offset == 0)
871 return EmitConstantValueOnly(ptrVal);
872
873 // Truncate/sext the offset to the pointer size.
874 if (TD->getPointerSizeInBits() != 64) {
875 int SExtAmount = 64-TD->getPointerSizeInBits();
876 Offset = (Offset << SExtAmount) >> SExtAmount;
877 }
878
879 if (Offset)
880 O << '(';
881 EmitConstantValueOnly(ptrVal);
882 if (Offset > 0)
883 O << ") + " << Offset;
884 else
885 O << ") - " << -Offset;
886 return;
887 }
888 case Instruction::BitCast:
889 return EmitConstantValueOnly(CE->getOperand(0));
890
891 case Instruction::IntToPtr: {
892 // Handle casts to pointers by changing them into casts to the appropriate
893 // integer type. This promotes constant folding and simplifies this code.
894 const TargetData *TD = TM.getTargetData();
895 Constant *Op = CE->getOperand(0);
896 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
897 false/*ZExt*/);
898 return EmitConstantValueOnly(Op);
899 }
900
901 case Instruction::PtrToInt: {
902 // Support only foldable casts to/from pointers that can be eliminated by
903 // changing the pointer to the appropriately sized integer type.
904 Constant *Op = CE->getOperand(0);
905 const Type *Ty = CE->getType();
906 const TargetData *TD = TM.getTargetData();
907
908 // We can emit the pointer value into this slot if the slot is an
909 // integer slot greater or equal to the size of the pointer.
910 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
911 return EmitConstantValueOnly(Op);
912
913 O << "((";
914 EmitConstantValueOnly(Op);
915 APInt ptrMask =
916 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
917
918 SmallString<40> S;
919 ptrMask.toStringUnsigned(S);
920 O << ") & " << S.str() << ')';
921 return;
922 }
923
924 case Instruction::Trunc:
925 // We emit the value and depend on the assembler to truncate the generated
926 // expression properly. This is important for differences between
927 // blockaddress labels. Since the two labels are in the same function, it
928 // is reasonable to treat their delta as a 32-bit value.
929 return EmitConstantValueOnly(CE->getOperand(0));
930
931 case Instruction::Add:
932 case Instruction::Sub:
933 case Instruction::And:
934 case Instruction::Or:
935 case Instruction::Xor:
936 O << '(';
937 EmitConstantValueOnly(CE->getOperand(0));
938 O << ')';
939 switch (CE->getOpcode()) {
940 case Instruction::Add:
941 O << " + ";
942 break;
943 case Instruction::Sub:
944 O << " - ";
945 break;
946 case Instruction::And:
947 O << " & ";
948 break;
949 case Instruction::Or:
950 O << " | ";
951 break;
952 case Instruction::Xor:
953 O << " ^ ";
954 break;
955 default:
956 break;
957 }
958 O << '(';
959 EmitConstantValueOnly(CE->getOperand(1));
960 O << ')';
961 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 }
963}
964
965/// printAsCString - Print the specified array as a C compatible string, only if
966/// the predicate isString is true.
967///
David Greene302008d2009-07-14 20:18:05 +0000968static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 unsigned LastElt) {
970 assert(CVA->isString() && "Array is not string compatible!");
971
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000972 O << '\"';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 for (unsigned i = 0; i != LastElt; ++i) {
974 unsigned char C =
975 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
976 printStringChar(O, C);
977 }
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000978 O << '\"';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979}
980
981/// EmitString - Emit a zero-byte-terminated string constant.
982///
983void AsmPrinter::EmitString(const ConstantArray *CVA) const {
984 unsigned NumElts = CVA->getNumOperands();
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000985 if (MAI->getAscizDirective() && NumElts &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000987 O << MAI->getAscizDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 printAsCString(O, CVA, NumElts-1);
989 } else {
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000990 O << MAI->getAsciiDirective();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 printAsCString(O, CVA, NumElts);
992 }
Dan Gohman12ebe3f2008-06-30 22:03:41 +0000993 O << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994}
995
Chris Lattnere72333d2010-01-19 19:10:44 +0000996static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
997 AsmPrinter &AP) {
998 if (AddrSpace == 0 && CA->isString()) {
999 AP.EmitString(CA);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001000 } else { // Not a string. Print the values in successive locations
Chris Lattnere72333d2010-01-19 19:10:44 +00001001 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1002 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001003 }
1004}
1005
Chris Lattnere72333d2010-01-19 19:10:44 +00001006static void EmitGlobalConstantVector(const ConstantVector *CV,
1007 unsigned AddrSpace, AsmPrinter &AP) {
Chris Lattnerd3544672010-01-20 07:41:15 +00001008 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Chris Lattnere72333d2010-01-19 19:10:44 +00001009 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001010}
1011
Chris Lattnere72333d2010-01-19 19:10:44 +00001012static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1013 unsigned AddrSpace, AsmPrinter &AP) {
Dan Gohmane78b0c72008-12-22 21:14:27 +00001014 // Print the fields in successive locations. Pad to align if needed!
Chris Lattnere72333d2010-01-19 19:10:44 +00001015 const TargetData *TD = AP.TM.getTargetData();
1016 unsigned Size = TD->getTypeAllocSize(CS->getType());
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001017 const StructLayout *Layout = TD->getStructLayout(CS->getType());
Chris Lattnere72333d2010-01-19 19:10:44 +00001018 uint64_t SizeSoFar = 0;
1019 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattnerd3544672010-01-20 07:41:15 +00001020 const Constant *Field = CS->getOperand(i);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001021
1022 // Check if padding is needed and insert one or more 0s.
Chris Lattnerd3544672010-01-20 07:41:15 +00001023 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001024 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1025 - Layout->getElementOffset(i)) - FieldSize;
1026 SizeSoFar += FieldSize + PadSize;
Dan Gohmane78b0c72008-12-22 21:14:27 +00001027
1028 // Now print the actual field value.
Chris Lattnerd3544672010-01-20 07:41:15 +00001029 AP.EmitGlobalConstant(Field, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001030
1031 // Insert padding - this may include padding to increase the size of the
1032 // current field up to the ABI size (if the struct is not packed) as well
1033 // as padding to ensure that the next field starts at the right offset.
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001034 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001035 }
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001036 assert(SizeSoFar == Layout->getSizeInBytes() &&
Dan Gohmane78b0c72008-12-22 21:14:27 +00001037 "Layout of constant struct may be incorrect!");
1038}
1039
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001040static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1041 AsmPrinter &AP) {
Dan Gohmane78b0c72008-12-22 21:14:27 +00001042 // FP Constants are printed as integer constants to avoid losing
Chris Lattner41fd4b12010-01-20 06:53:37 +00001043 // precision.
Chris Lattner82cdc062009-10-05 05:54:46 +00001044 if (CFP->getType()->isDoubleTy()) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001045 if (AP.VerboseAsm) {
Chris Lattner49d74392010-01-22 19:17:48 +00001046 double Val = CFP->getValueAPF().convertToDouble();
1047 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
Chris Lattner4e789282010-01-19 22:16:33 +00001048 }
1049
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001050 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1051 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001052 return;
Chris Lattner82cdc062009-10-05 05:54:46 +00001053 }
1054
1055 if (CFP->getType()->isFloatTy()) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001056 if (AP.VerboseAsm) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001057 float Val = CFP->getValueAPF().convertToFloat();
1058 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
Dan Gohman87581eb2009-08-12 18:32:22 +00001059 }
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001060 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1061 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001062 return;
Chris Lattner82cdc062009-10-05 05:54:46 +00001063 }
1064
1065 if (CFP->getType()->isX86_FP80Ty()) {
Dan Gohmane78b0c72008-12-22 21:14:27 +00001066 // all long double variants are printed as hex
1067 // api needed to prevent premature destruction
Chris Lattner4e789282010-01-19 22:16:33 +00001068 APInt API = CFP->getValueAPF().bitcastToAPInt();
1069 const uint64_t *p = API.getRawData();
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001070 if (AP.VerboseAsm) {
Chris Lattner84382d22010-01-19 22:11:05 +00001071 // Convert to double so we can print the approximate val as a comment.
1072 APFloat DoubleVal = CFP->getValueAPF();
1073 bool ignored;
1074 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1075 &ignored);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001076 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1077 << DoubleVal.convertToDouble() << '\n';
Chris Lattner84382d22010-01-19 22:11:05 +00001078 }
1079
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001080 if (AP.TM.getTargetData()->isBigEndian()) {
1081 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1082 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
Chris Lattner84382d22010-01-19 22:11:05 +00001083 } else {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001084 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1085 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001086 }
Chris Lattner41fd4b12010-01-20 06:53:37 +00001087
1088 // Emit the tail padding for the long double.
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001089 const TargetData &TD = *AP.TM.getTargetData();
1090 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1091 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001092 return;
Chris Lattner82cdc062009-10-05 05:54:46 +00001093 }
1094
Chris Lattner4e789282010-01-19 22:16:33 +00001095 assert(CFP->getType()->isPPC_FP128Ty() &&
1096 "Floating point constant type not handled");
1097 // All long double variants are printed as hex api needed to prevent
1098 // premature destruction.
1099 APInt API = CFP->getValueAPF().bitcastToAPInt();
1100 const uint64_t *p = API.getRawData();
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001101 if (AP.TM.getTargetData()->isBigEndian()) {
1102 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1103 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
Chris Lattner41fd4b12010-01-20 06:53:37 +00001104 } else {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001105 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1106 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
Chris Lattner4e789282010-01-19 22:16:33 +00001107 }
Dan Gohmane78b0c72008-12-22 21:14:27 +00001108}
1109
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001110static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1111 unsigned AddrSpace, AsmPrinter &AP) {
1112 const TargetData *TD = AP.TM.getTargetData();
Dan Gohmane78b0c72008-12-22 21:14:27 +00001113 unsigned BitWidth = CI->getBitWidth();
Chris Lattner50340312010-01-13 04:39:46 +00001114 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
Dan Gohmane78b0c72008-12-22 21:14:27 +00001115
1116 // We don't expect assemblers to support integer data directives
1117 // for more than 64 bits, so we emit the data in at most 64-bit
1118 // quantities at a time.
1119 const uint64_t *RawData = CI->getValue().getRawData();
1120 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001121 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1122 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001123 }
1124}
1125
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Sanjiv Guptadc2943d2009-01-30 04:25:10 +00001127void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
Chris Lattnere795ca52010-01-20 07:19:19 +00001128 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001129 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
Chris Lattner030176b2010-01-19 21:51:22 +00001130 return OutStreamer.EmitZeros(Size, AddrSpace);
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001131 }
1132
1133 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1134 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1135 switch (Size) {
1136 case 1:
1137 case 2:
1138 case 4:
1139 case 8:
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001140 if (VerboseAsm)
1141 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001142 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1143 return;
1144 default:
1145 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1146 return;
1147 }
1148 }
Chris Lattner9d767d82010-01-13 04:34:19 +00001149
Chris Lattnere72333d2010-01-19 19:10:44 +00001150 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1151 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001152
Chris Lattnere72333d2010-01-19 19:10:44 +00001153 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1154 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001155
Chris Lattnere72333d2010-01-19 19:10:44 +00001156 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001157 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001158
Chris Lattnere72333d2010-01-19 19:10:44 +00001159 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1160 return EmitGlobalConstantVector(V, AddrSpace, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161
Chris Lattner4fb5a132010-01-20 17:57:50 +00001162 if (isa<ConstantPointerNull>(CV)) {
1163 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1164 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1165 return;
1166 }
1167
Chris Lattner939a3142010-01-20 07:33:29 +00001168 // Otherwise, it must be a ConstantExpr. Emit the data directive, then emit
1169 // the expression value.
1170 switch (TM.getTargetData()->getTypeAllocSize(CV->getType())) {
1171 case 0: return;
1172 case 1: O << MAI->getData8bitsDirective(AddrSpace); break;
1173 case 2: O << MAI->getData16bitsDirective(AddrSpace); break;
1174 case 4: O << MAI->getData32bitsDirective(AddrSpace); break;
1175 case 8:
1176 if (const char *Dir = MAI->getData64bitsDirective(AddrSpace)) {
1177 O << Dir;
1178 break;
1179 }
1180 // FALL THROUGH.
1181 default:
1182 llvm_unreachable("Target cannot handle given data directive width!");
1183 return;
1184 }
1185
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 EmitConstantValueOnly(CV);
Dan Gohman12ebe3f2008-06-30 22:03:41 +00001187 O << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188}
1189
Chris Lattner89b36582008-08-17 07:19:36 +00001190void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001191 // Target doesn't support this yet!
Edwin Törökbd448e32009-07-14 16:55:14 +00001192 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193}
1194
1195/// PrintSpecial - Print information related to the specified machine instr
1196/// that is independent of the operand, and may be independent of the instr
1197/// itself. This can be useful for portably encoding the comment character
1198/// or other bits of target-specific knowledge into the asmstrings. The
1199/// syntax used is ${:comment}. Targets can override this to add support
1200/// for their own strange codes.
Chris Lattner6af48032009-03-10 05:37:13 +00001201void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 if (!strcmp(Code, "private")) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001203 O << MAI->getPrivateGlobalPrefix();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 } else if (!strcmp(Code, "comment")) {
Evan Cheng11db8142009-03-24 00:17:40 +00001205 if (VerboseAsm)
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001206 O << MAI->getCommentString();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 } else if (!strcmp(Code, "uid")) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 // Comparing the address of MI isn't sufficient, because machineinstrs may
1209 // be allocated to the same address across functions.
1210 const Function *ThisF = MI->getParent()->getParent()->getFunction();
1211
Owen Andersonda3388b2009-06-24 22:28:12 +00001212 // If this is a new LastFn instruction, bump the counter.
1213 if (LastMI != MI || LastFn != ThisF) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 ++Counter;
1215 LastMI = MI;
Owen Andersonda3388b2009-06-24 22:28:12 +00001216 LastFn = ThisF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217 }
1218 O << Counter;
1219 } else {
Edwin Törökced9ff82009-07-11 13:10:19 +00001220 std::string msg;
1221 raw_string_ostream Msg(msg);
1222 Msg << "Unknown special formatter '" << Code
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 << "' for machine instr: " << *MI;
Edwin Törökced9ff82009-07-11 13:10:19 +00001224 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 }
1226}
1227
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +00001228/// processDebugLoc - Processes the debug information of each machine
1229/// instruction's DebugLoc.
Devang Patel5450fc12009-10-06 02:19:11 +00001230void AsmPrinter::processDebugLoc(const MachineInstr *MI,
1231 bool BeforePrintingInsn) {
Devang Patel90a0fe32009-11-10 23:06:00 +00001232 if (!MAI || !DW || !MAI->doesSupportDebugInformation()
1233 || !DW->ShouldEmitDwarfDebug())
Chris Lattner693cfcc2009-08-05 04:09:18 +00001234 return;
Devang Patel86049dc2009-09-30 23:12:50 +00001235 DebugLoc DL = MI->getDebugLoc();
Devang Patel90a0fe32009-11-10 23:06:00 +00001236 if (DL.isUnknown())
1237 return;
Devang Patel042945f2010-01-16 06:09:35 +00001238 DILocation CurDLT = MF->getDILocation(DL);
1239 if (CurDLT.getScope().isNull())
Devang Patel90a0fe32009-11-10 23:06:00 +00001240 return;
1241
Chris Lattnere795ca52010-01-20 07:19:19 +00001242 if (!BeforePrintingInsn) {
Devang Patel90a0fe32009-11-10 23:06:00 +00001243 // After printing instruction
1244 DW->EndScope(MI);
Chris Lattnere795ca52010-01-20 07:19:19 +00001245 } else if (CurDLT.getNode() != PrevDLT) {
1246 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(),
1247 CurDLT.getColumnNumber(),
1248 CurDLT.getScope().getNode());
1249 printLabel(L);
1250 O << '\n';
1251 DW->BeginScope(MI, L);
1252 PrevDLT = CurDLT.getNode();
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +00001253 }
1254}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255
Devang Patel90a0fe32009-11-10 23:06:00 +00001256
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257/// printInlineAsm - This method formats and prints the specified machine
1258/// instruction that is an inline asm.
1259void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
1260 unsigned NumOperands = MI->getNumOperands();
1261
1262 // Count the number of register definitions.
1263 unsigned NumDefs = 0;
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001264 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 ++NumDefs)
1266 assert(NumDefs != NumOperands-1 && "No asm string?");
1267
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001268 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269
1270 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
1271 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
1272
Dan Gohmanbbc43962009-11-06 00:04:54 +00001273 O << '\t';
1274
Dale Johannesene99fc902008-01-29 02:21:21 +00001275 // If this asmstr is empty, just print the #APP/#NOAPP markers.
1276 // These are useful to see where empty asm's wound up.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 if (AsmStr[0] == 0) {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001278 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
1279 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 return;
1281 }
1282
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001283 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284
1285 // The variant of the current asmprinter.
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001286 int AsmPrinterVariant = MAI->getAssemblerDialect();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287
1288 int CurVariant = -1; // The number of the {.|.|.} region we are in.
1289 const char *LastEmitted = AsmStr; // One past the last character emitted.
1290
1291 while (*LastEmitted) {
1292 switch (*LastEmitted) {
1293 default: {
1294 // Not a special case, emit the string section literally.
1295 const char *LiteralEnd = LastEmitted+1;
1296 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
1297 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
1298 ++LiteralEnd;
1299 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1300 O.write(LastEmitted, LiteralEnd-LastEmitted);
1301 LastEmitted = LiteralEnd;
1302 break;
1303 }
1304 case '\n':
1305 ++LastEmitted; // Consume newline character.
Dan Gohman12ebe3f2008-06-30 22:03:41 +00001306 O << '\n'; // Indent code with newline.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 break;
1308 case '$': {
1309 ++LastEmitted; // Consume '$' character.
1310 bool Done = true;
1311
1312 // Handle escapes.
1313 switch (*LastEmitted) {
1314 default: Done = false; break;
1315 case '$': // $$ -> $
1316 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
1317 O << '$';
1318 ++LastEmitted; // Consume second '$' character.
1319 break;
1320 case '(': // $( -> same as GCC's { character.
1321 ++LastEmitted; // Consume '(' character.
1322 if (CurVariant != -1) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001323 llvm_report_error("Nested variants found in inline asm string: '"
1324 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 }
1326 CurVariant = 0; // We're in the first variant now.
1327 break;
1328 case '|':
1329 ++LastEmitted; // consume '|' character.
Dale Johannesen8b0e1172008-10-10 21:04:42 +00001330 if (CurVariant == -1)
1331 O << '|'; // this is gcc's behavior for | outside a variant
1332 else
1333 ++CurVariant; // We're in the next variant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 break;
1335 case ')': // $) -> same as GCC's } char.
1336 ++LastEmitted; // consume ')' character.
Dale Johannesen8b0e1172008-10-10 21:04:42 +00001337 if (CurVariant == -1)
1338 O << '}'; // this is gcc's behavior for } outside a variant
1339 else
1340 CurVariant = -1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 break;
1342 }
1343 if (Done) break;
1344
1345 bool HasCurlyBraces = false;
1346 if (*LastEmitted == '{') { // ${variable}
1347 ++LastEmitted; // Consume '{' character.
1348 HasCurlyBraces = true;
1349 }
1350
Chris Lattner6af48032009-03-10 05:37:13 +00001351 // If we have ${:foo}, then this is not a real operand reference, it is a
1352 // "magic" string reference, just like in .td files. Arrange to call
1353 // PrintSpecial.
1354 if (HasCurlyBraces && *LastEmitted == ':') {
1355 ++LastEmitted;
1356 const char *StrStart = LastEmitted;
1357 const char *StrEnd = strchr(StrStart, '}');
1358 if (StrEnd == 0) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001359 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '"
1360 + std::string(AsmStr) + "'");
Chris Lattner6af48032009-03-10 05:37:13 +00001361 }
1362
1363 std::string Val(StrStart, StrEnd);
1364 PrintSpecial(MI, Val.c_str());
1365 LastEmitted = StrEnd+1;
1366 break;
1367 }
1368
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 const char *IDStart = LastEmitted;
1370 char *IDEnd;
1371 errno = 0;
1372 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
1373 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001374 llvm_report_error("Bad $ operand number in inline asm string: '"
1375 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 }
1377 LastEmitted = IDEnd;
1378
1379 char Modifier[2] = { 0, 0 };
1380
1381 if (HasCurlyBraces) {
1382 // If we have curly braces, check for a modifier character. This
1383 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
1384 if (*LastEmitted == ':') {
1385 ++LastEmitted; // Consume ':' character.
1386 if (*LastEmitted == 0) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001387 llvm_report_error("Bad ${:} expression in inline asm string: '"
1388 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389 }
1390
1391 Modifier[0] = *LastEmitted;
1392 ++LastEmitted; // Consume modifier character.
1393 }
1394
1395 if (*LastEmitted != '}') {
Edwin Törökced9ff82009-07-11 13:10:19 +00001396 llvm_report_error("Bad ${} expression in inline asm string: '"
1397 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398 }
1399 ++LastEmitted; // Consume '}' character.
1400 }
1401
1402 if ((unsigned)Val >= NumOperands-1) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001403 llvm_report_error("Invalid $ operand number in inline asm string: '"
1404 + std::string(AsmStr) + "'");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 }
1406
1407 // Okay, we finally have a value number. Ask the target to print this
1408 // operand!
1409 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
1410 unsigned OpNo = 1;
1411
1412 bool Error = false;
1413
1414 // Scan to find the machine operand number for the operand.
1415 for (; Val; --Val) {
1416 if (OpNo >= MI->getNumOperands()) break;
Chris Lattnerda4cff12007-12-30 20:50:28 +00001417 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Evan Cheng92167402009-03-20 18:03:34 +00001418 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419 }
1420
1421 if (OpNo >= MI->getNumOperands()) {
1422 Error = true;
1423 } else {
Chris Lattnerda4cff12007-12-30 20:50:28 +00001424 unsigned OpFlags = MI->getOperand(OpNo).getImm();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 ++OpNo; // Skip over the ID number.
1426
Chris Lattnerce409842010-01-17 21:43:43 +00001427 if (Modifier[0] == 'l') // labels are target independent
1428 O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
Dale Johannesencfb19e62007-11-05 21:20:28 +00001429 else {
1430 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
Dale Johannesen94464072008-09-24 01:07:17 +00001431 if ((OpFlags & 7) == 4) {
Dale Johannesencfb19e62007-11-05 21:20:28 +00001432 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
1433 Modifier[0] ? Modifier : 0);
1434 } else {
1435 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
1436 Modifier[0] ? Modifier : 0);
1437 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 }
1439 }
1440 if (Error) {
Edwin Törökced9ff82009-07-11 13:10:19 +00001441 std::string msg;
1442 raw_string_ostream Msg(msg);
Chris Lattnerce409842010-01-17 21:43:43 +00001443 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
Edwin Törökced9ff82009-07-11 13:10:19 +00001444 MI->print(Msg);
1445 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 }
1447 }
1448 break;
1449 }
1450 }
1451 }
Chris Lattner32d4cc72009-09-09 23:14:36 +00001452 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453}
1454
Evan Cheng3c0eda52008-03-15 00:03:38 +00001455/// printImplicitDef - This method prints the specified machine instruction
1456/// that is an implicit def.
1457void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
Chris Lattner32d4cc72009-09-09 23:14:36 +00001458 if (!VerboseAsm) return;
1459 O.PadToColumn(MAI->getCommentColumn());
1460 O << MAI->getCommentString() << " implicit-def: "
Chris Lattner28f7e352009-09-13 19:48:37 +00001461 << TRI->getName(MI->getOperand(0).getReg());
Evan Cheng3c0eda52008-03-15 00:03:38 +00001462}
1463
Jakob Stoklund Olesen7f251672009-11-04 19:24:37 +00001464void AsmPrinter::printKill(const MachineInstr *MI) const {
1465 if (!VerboseAsm) return;
1466 O.PadToColumn(MAI->getCommentColumn());
1467 O << MAI->getCommentString() << " kill:";
1468 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
1469 const MachineOperand &op = MI->getOperand(n);
1470 assert(op.isReg() && "KILL instruction must have only register operands");
1471 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
1472 }
1473}
1474
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475/// printLabel - This method prints a local label used by debug and
1476/// exception handling tables.
1477void AsmPrinter::printLabel(const MachineInstr *MI) const {
Dan Gohman7d546402008-07-01 00:16:26 +00001478 printLabel(MI->getOperand(0).getImm());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479}
1480
Evan Chenga53c40a2008-02-01 09:10:45 +00001481void AsmPrinter::printLabel(unsigned Id) const {
Chris Lattner32d4cc72009-09-09 23:14:36 +00001482 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
Evan Chenga53c40a2008-02-01 09:10:45 +00001483}
1484
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001485/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
1486/// instruction, using the specified assembler variant. Targets should
Dale Johannesenc90c30b2010-01-14 21:50:17 +00001487/// override this to format as appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1489 unsigned AsmVariant, const char *ExtraCode) {
1490 // Target doesn't support this yet!
1491 return true;
1492}
1493
1494bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
1495 unsigned AsmVariant,
1496 const char *ExtraCode) {
1497 // Target doesn't support this yet!
1498 return true;
1499}
1500
Dan Gohman885793b2009-11-20 23:18:13 +00001501MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
1502 const char *Suffix) const {
1503 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
Dan Gohman91057512009-10-30 01:27:03 +00001504}
1505
1506MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
Dan Gohman885793b2009-11-20 23:18:13 +00001507 const BasicBlock *BB,
1508 const char *Suffix) const {
Dan Gohman91057512009-10-30 01:27:03 +00001509 assert(BB->hasName() &&
1510 "Address of anonymous basic block not supported yet!");
1511
Dan Gohmanff592ec2009-11-05 23:14:35 +00001512 // This code must use the function name itself, and not the function number,
1513 // since it must be possible to generate the label name from within other
1514 // functions.
Chris Lattner6be13f32010-01-13 07:30:49 +00001515 SmallString<60> FnName;
1516 Mang->getNameWithPrefix(FnName, F, false);
Dan Gohman91057512009-10-30 01:27:03 +00001517
Chris Lattner6be13f32010-01-13 07:30:49 +00001518 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
Chris Lattnera38b2872010-01-13 06:38:18 +00001519 SmallString<60> NameResult;
Chris Lattner6be13f32010-01-13 07:30:49 +00001520 Mang->getNameWithPrefix(NameResult,
1521 StringRef("BA") + Twine((unsigned)FnName.size()) +
1522 "_" + FnName.str() + "_" + BB->getName() + Suffix,
1523 Mangler::Private);
Dan Gohmanff592ec2009-11-05 23:14:35 +00001524
Chris Lattnera38b2872010-01-13 06:38:18 +00001525 return OutContext.GetOrCreateSymbol(NameResult.str());
Dan Gohman91057512009-10-30 01:27:03 +00001526}
1527
Chris Lattner08c97082009-09-12 23:02:08 +00001528MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
1529 SmallString<60> Name;
1530 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
1531 << getFunctionNumber() << '_' << MBBID;
1532
1533 return OutContext.GetOrCreateSymbol(Name.str());
1534}
1535
Chris Lattner2eb781d2010-01-15 23:18:17 +00001536/// GetGlobalValueSymbol - Return the MCSymbol for the specified global
1537/// value.
1538MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
1539 SmallString<60> NameStr;
1540 Mang->getNameWithPrefix(NameStr, GV, false);
1541 return OutContext.GetOrCreateSymbol(NameStr.str());
1542}
1543
Chris Lattnera6f2a102010-01-16 18:37:32 +00001544/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
Chris Lattnerf7871d12010-01-15 23:25:11 +00001545/// global value name as its base, with the specified suffix, and where the
Chris Lattnera6f2a102010-01-16 18:37:32 +00001546/// symbol is forced to have private linkage if ForcePrivate is true.
1547MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1548 StringRef Suffix,
1549 bool ForcePrivate) const {
Chris Lattnerf7871d12010-01-15 23:25:11 +00001550 SmallString<60> NameStr;
Chris Lattnera6f2a102010-01-16 18:37:32 +00001551 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
Chris Lattnerf7871d12010-01-15 23:25:11 +00001552 NameStr.append(Suffix.begin(), Suffix.end());
1553 return OutContext.GetOrCreateSymbol(NameStr.str());
1554}
1555
Chris Lattner2eb781d2010-01-15 23:18:17 +00001556/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1557/// ExternalSymbol.
1558MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1559 SmallString<60> NameStr;
1560 Mang->getNameWithPrefix(NameStr, Sym);
1561 return OutContext.GetOrCreateSymbol(NameStr.str());
1562}
1563
Chris Lattner08c97082009-09-12 23:02:08 +00001564
Chris Lattner5abc72c2010-01-22 21:50:41 +00001565
1566/// PrintParentLoopComment - Print comments about parent loops of this one.
1567static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1568 unsigned FunctionNumber) {
1569 if (Loop == 0) return;
1570 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1571 OS.indent(Loop->getLoopDepth()*2)
1572 << "Parent Loop BB" << FunctionNumber << "_"
1573 << Loop->getHeader()->getNumber()
1574 << " Depth=" << Loop->getLoopDepth() << '\n';
1575}
1576
1577
1578/// PrintChildLoopComment - Print comments about child loops within
1579/// the loop for this basic block, with nesting.
1580static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1581 unsigned FunctionNumber) {
1582 // Add child loop information
1583 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1584 OS.indent((*CL)->getLoopDepth()*2)
1585 << "Child Loop BB" << FunctionNumber << "_"
1586 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1587 << '\n';
1588 PrintChildLoopComment(OS, *CL, FunctionNumber);
1589 }
1590}
1591
1592/// EmitComments - Pretty-print comments for basic blocks.
1593static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB,
1594 const MachineLoopInfo *LI,
1595 const AsmPrinter &AP) {
1596 // Add loop depth information
1597 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1598 if (Loop == 0) return;
1599
1600 MachineBasicBlock *Header = Loop->getHeader();
1601 assert(Header && "No header for loop");
1602
1603 // If this block is not a loop header, just print out what is the loop header
1604 // and return.
1605 if (Header != &MBB) {
1606 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1607 Twine(AP.getFunctionNumber())+"_" +
1608 Twine(Loop->getHeader()->getNumber())+
1609 " Depth="+Twine(Loop->getLoopDepth()));
1610 return;
1611 }
1612
1613 // Otherwise, it is a loop header. Print out information about child and
1614 // parent loops.
1615 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1616
1617 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1618
1619 OS << "=>";
1620 OS.indent(Loop->getLoopDepth()*2-2);
1621
1622 OS << "This ";
1623 if (Loop->empty())
1624 OS << "Inner ";
1625 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1626
1627 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1628}
1629
1630
Chris Lattner2faa4ef2009-09-13 18:25:37 +00001631/// EmitBasicBlockStart - This method prints the label for the specified
1632/// MachineBasicBlock, an alignment (if present) and a comment describing
1633/// it if appropriate.
Chris Lattnerda5fb6d2009-09-14 03:15:54 +00001634void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001635 // Emit an alignment directive for this block, if needed.
Chris Lattner2faa4ef2009-09-13 18:25:37 +00001636 if (unsigned Align = MBB->getAlignment())
1637 EmitAlignment(Log2_32(Align));
Evan Cheng45c1edb2008-02-28 00:43:03 +00001638
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001639 // If the block has its address taken, emit a special label to satisfy
1640 // references to the block. This is done so that we don't need to
1641 // remember the number of this label, and so that we can make
1642 // forward references to labels without knowing what their numbers
1643 // will be.
Dan Gohman91057512009-10-30 01:27:03 +00001644 if (MBB->hasAddressTaken()) {
Chris Lattner8bae1052010-01-20 07:24:05 +00001645 const BasicBlock *BB = MBB->getBasicBlock();
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001646 if (VerboseAsm)
1647 OutStreamer.AddComment("Address Taken");
Chris Lattner8bae1052010-01-20 07:24:05 +00001648 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB));
Dan Gohman91057512009-10-30 01:27:03 +00001649 }
1650
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001651 // Print the main label for the block.
Dan Gohman5fda4342009-10-06 17:38:38 +00001652 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001653 if (VerboseAsm) {
Dan Gohman5fda4342009-10-06 17:38:38 +00001654 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001655 if (const BasicBlock *BB = MBB->getBasicBlock())
1656 if (BB->hasName())
1657 OutStreamer.AddComment("%" + BB->getName());
Chris Lattner82be51c2010-01-22 21:00:45 +00001658
Chris Lattner5abc72c2010-01-22 21:50:41 +00001659 PrintBasicBlockLoopComments(*MBB, LI, *this);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001660 OutStreamer.AddBlankLine();
1661 }
Dan Gohman5fda4342009-10-06 17:38:38 +00001662 } else {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001663 if (VerboseAsm) {
1664 if (const BasicBlock *BB = MBB->getBasicBlock())
1665 if (BB->hasName())
1666 OutStreamer.AddComment("%" + BB->getName());
Chris Lattner5abc72c2010-01-22 21:50:41 +00001667 PrintBasicBlockLoopComments(*MBB, LI, *this);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001668 }
Chris Lattner82be51c2010-01-22 21:00:45 +00001669
Chris Lattner8bae1052010-01-20 07:24:05 +00001670 OutStreamer.EmitLabel(GetMBBSymbol(MBB->getNumber()));
Dan Gohman5fda4342009-10-06 17:38:38 +00001671 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001672}
1673
Evan Cheng6fb06762007-11-09 01:32:10 +00001674/// printPICJumpTableSetLabel - This method prints a set label for the
1675/// specified MachineBasicBlock for a jumptable entry.
1676void AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
1677 const MachineBasicBlock *MBB) const {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001678 if (!MAI->getSetDirective())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 return;
1680
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001681 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
Chris Lattnerce409842010-01-17 21:43:43 +00001682 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
1683 << *GetMBBSymbol(MBB->getNumber())
1684 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
Evan Cheng477013c2007-10-14 05:57:21 +00001685 << '_' << uid << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686}
1687
Evan Cheng6fb06762007-11-09 01:32:10 +00001688void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
1689 const MachineBasicBlock *MBB) const {
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001690 if (!MAI->getSetDirective())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691 return;
1692
Chris Lattnera5ef4d32009-08-22 21:43:10 +00001693 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
Evan Cheng477013c2007-10-14 05:57:21 +00001694 << getFunctionNumber() << '_' << uid << '_' << uid2
Chris Lattnerce409842010-01-17 21:43:43 +00001695 << "_set_" << MBB->getNumber() << ','
1696 << *GetMBBSymbol(MBB->getNumber())
1697 << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
Evan Cheng477013c2007-10-14 05:57:21 +00001698 << '_' << uid << '_' << uid2 << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001699}
1700
Chris Lattner67cce682010-01-15 23:38:51 +00001701void AsmPrinter::printVisibility(const MCSymbol *Sym,
1702 unsigned Visibility) const {
1703 if (Visibility == GlobalValue::HiddenVisibility) {
Chris Lattnerce409842010-01-17 21:43:43 +00001704 if (const char *Directive = MAI->getHiddenDirective())
1705 O << Directive << *Sym << '\n';
Chris Lattner67cce682010-01-15 23:38:51 +00001706 } else if (Visibility == GlobalValue::ProtectedVisibility) {
Chris Lattnerce409842010-01-17 21:43:43 +00001707 if (const char *Directive = MAI->getProtectedDirective())
1708 O << Directive << *Sym << '\n';
Chris Lattner67cce682010-01-15 23:38:51 +00001709 }
1710}
1711
Anton Korobeynikov440f23d2008-11-22 16:15:34 +00001712void AsmPrinter::printOffset(int64_t Offset) const {
1713 if (Offset > 0)
1714 O << '+' << Offset;
1715 else if (Offset < 0)
1716 O << Offset;
1717}
1718
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001719GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1720 if (!S->usesMetadata())
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001721 return 0;
1722
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001723 gcp_iterator GCPI = GCMetadataPrinters.find(S);
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001724 if (GCPI != GCMetadataPrinters.end())
1725 return GCPI->second;
1726
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001727 const char *Name = S->getName().c_str();
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001728
1729 for (GCMetadataPrinterRegistry::iterator
1730 I = GCMetadataPrinterRegistry::begin(),
1731 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1732 if (strcmp(Name, I->getName()) == 0) {
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001733 GCMetadataPrinter *GMP = I->instantiate();
1734 GMP->S = S;
1735 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1736 return GMP;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001737 }
1738
Chris Lattnerbf9d76d2009-08-23 07:19:13 +00001739 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +00001740 llvm_unreachable(0);
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001741}
David Greene63486122009-07-13 20:25:48 +00001742
1743/// EmitComments - Pretty-print comments for instructions
Chris Lattnerfdbeb812009-08-07 23:42:01 +00001744void AsmPrinter::EmitComments(const MachineInstr &MI) const {
David Greeneca9b04b2009-11-13 21:34:57 +00001745 if (!VerboseAsm)
1746 return;
David Greene4a37a692009-07-16 22:24:20 +00001747
David Greeneca9b04b2009-11-13 21:34:57 +00001748 bool Newline = false;
1749
1750 if (!MI.getDebugLoc().isUnknown()) {
Devang Patel042945f2010-01-16 06:09:35 +00001751 DILocation DLT = MF->getDILocation(MI.getDebugLoc());
David Greeneca9b04b2009-11-13 21:34:57 +00001752
1753 // Print source line info.
1754 O.PadToColumn(MAI->getCommentColumn());
Dan Gohman4698bab2009-12-05 00:23:29 +00001755 O << MAI->getCommentString() << ' ';
Devang Patel042945f2010-01-16 06:09:35 +00001756 DIScope Scope = DLT.getScope();
Dan Gohman4698bab2009-12-05 00:23:29 +00001757 // Omit the directory, because it's likely to be long and uninteresting.
1758 if (!Scope.isNull())
1759 O << Scope.getFilename();
1760 else
1761 O << "<unknown>";
Devang Patel042945f2010-01-16 06:09:35 +00001762 O << ':' << DLT.getLineNumber();
1763 if (DLT.getColumnNumber() != 0)
1764 O << ':' << DLT.getColumnNumber();
David Greeneca9b04b2009-11-13 21:34:57 +00001765 Newline = true;
David Greene4a37a692009-07-16 22:24:20 +00001766 }
David Greeneca9b04b2009-11-13 21:34:57 +00001767
David Greene2e7b9932009-11-16 15:12:23 +00001768 // Check for spills and reloads
1769 int FI;
1770
1771 const MachineFrameInfo *FrameInfo =
1772 MI.getParent()->getParent()->getFrameInfo();
1773
1774 // We assume a single instruction only has a spill or reload, not
1775 // both.
David Greene11a046f12009-12-04 22:46:04 +00001776 const MachineMemOperand *MMO;
David Greene2e7b9932009-11-16 15:12:23 +00001777 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
1778 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
David Greene11a046f12009-12-04 22:46:04 +00001779 MMO = *MI.memoperands_begin();
David Greene2e7b9932009-11-16 15:12:23 +00001780 if (Newline) O << '\n';
1781 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001782 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload";
David Greene2e7b9932009-11-16 15:12:23 +00001783 Newline = true;
1784 }
1785 }
David Greene11a046f12009-12-04 22:46:04 +00001786 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
David Greene2e7b9932009-11-16 15:12:23 +00001787 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1788 if (Newline) O << '\n';
1789 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001790 O << MAI->getCommentString() << ' '
1791 << MMO->getSize() << "-byte Folded Reload";
David Greene2e7b9932009-11-16 15:12:23 +00001792 Newline = true;
1793 }
1794 }
1795 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
1796 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
David Greene11a046f12009-12-04 22:46:04 +00001797 MMO = *MI.memoperands_begin();
David Greene2e7b9932009-11-16 15:12:23 +00001798 if (Newline) O << '\n';
1799 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001800 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill";
David Greene2e7b9932009-11-16 15:12:23 +00001801 Newline = true;
1802 }
1803 }
David Greene11a046f12009-12-04 22:46:04 +00001804 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
David Greene2e7b9932009-11-16 15:12:23 +00001805 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
1806 if (Newline) O << '\n';
1807 O.PadToColumn(MAI->getCommentColumn());
Dan Gohmane26680b2009-12-04 23:19:55 +00001808 O << MAI->getCommentString() << ' '
1809 << MMO->getSize() << "-byte Folded Spill";
David Greene2e7b9932009-11-16 15:12:23 +00001810 Newline = true;
1811 }
1812 }
1813
1814 // Check for spill-induced copies
1815 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1816 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
1817 SrcSubIdx, DstSubIdx)) {
1818 if (MI.getAsmPrinterFlag(ReloadReuse)) {
1819 if (Newline) O << '\n';
1820 O.PadToColumn(MAI->getCommentColumn());
1821 O << MAI->getCommentString() << " Reload Reuse";
David Greene2e7b9932009-11-16 15:12:23 +00001822 }
1823 }
David Greene63486122009-07-13 20:25:48 +00001824}
1825