blob: f7c9d84483e18051dfd49860e167182a81e2d157 [file] [log] [blame]
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "asm-printer"
15#include "llvm/CodeGen/AsmPrinter.h"
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -070016#ifndef ANDROID_TARGET_BUILD
17# include "DwarfDebug.h"
18# include "DwarfException.h"
19#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -080020#include "llvm/Module.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080021#include "llvm/CodeGen/GCMetadataPrinter.h"
22#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineJumpTableInfo.h"
26#include "llvm/CodeGen/MachineLoopInfo.h"
27#include "llvm/CodeGen/MachineModuleInfo.h"
28#include "llvm/Analysis/ConstantFolding.h"
29#include "llvm/Analysis/DebugInfo.h"
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070030#include "llvm/MC/MCAsmInfo.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080031#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCExpr.h"
33#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCSection.h"
35#include "llvm/MC/MCStreamer.h"
36#include "llvm/MC/MCSymbol.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080037#include "llvm/Target/Mangler.h"
38#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetLoweringObjectFile.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080042#include "llvm/Target/TargetRegisterInfo.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080043#include "llvm/ADT/SmallString.h"
44#include "llvm/ADT/Statistic.h"
Shih-wei Liaoe264f622010-02-10 11:10:31 -080045#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/Format.h"
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070047#include "llvm/Support/Timer.h"
Shih-wei Liaoe4454322010-04-07 12:21:42 -070048#include <ctype.h>
Shih-wei Liaoe264f622010-02-10 11:10:31 -080049using namespace llvm;
50
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070051static const char *DWARFGroupName = "DWARF Emission";
52static const char *DbgTimerName = "DWARF Debug Writer";
53static const char *EHTimerName = "DWARF Exception Writer";
54
Shih-wei Liaoe264f622010-02-10 11:10:31 -080055STATISTIC(EmittedInsts, "Number of machine instrs printed");
56
57char AsmPrinter::ID = 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070058
59typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
60static gcp_map_type &getGCMap(void *&P) {
61 if (P == 0)
62 P = new gcp_map_type();
63 return *(gcp_map_type*)P;
64}
65
66
67AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
68 : MachineFunctionPass(&ID),
69 TM(tm), MAI(tm.getMCAsmInfo()),
70 OutContext(Streamer.getContext()),
71 OutStreamer(Streamer),
72 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
73 DD = 0; DE = 0; MMI = 0; LI = 0;
74 GCMetadataPrinters = 0;
Shih-wei Liaoe264f622010-02-10 11:10:31 -080075 VerboseAsm = Streamer.isVerboseAsm();
76}
77
78AsmPrinter::~AsmPrinter() {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070079 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
80
81 if (GCMetadataPrinters != 0) {
82 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
83
84 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
85 delete I->second;
86 delete &GCMap;
87 GCMetadataPrinters = 0;
88 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -080089
90 delete &OutStreamer;
Shih-wei Liaoe264f622010-02-10 11:10:31 -080091}
92
93/// getFunctionNumber - Return a unique ID for the current function.
94///
95unsigned AsmPrinter::getFunctionNumber() const {
96 return MF->getFunctionNumber();
97}
98
Shih-wei Liao7abe37e2010-04-28 01:47:00 -070099const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800100 return TM.getTargetLowering()->getObjFileLowering();
101}
102
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700103
104/// getTargetData - Return information about data layout.
105const TargetData &AsmPrinter::getTargetData() const {
106 return *TM.getTargetData();
107}
108
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800109/// getCurrentSection() - Return the current section we are emitting to.
110const MCSection *AsmPrinter::getCurrentSection() const {
111 return OutStreamer.getCurrentSection();
112}
113
114
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700115
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800116void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
117 AU.setPreservesAll();
118 MachineFunctionPass::getAnalysisUsage(AU);
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700119 AU.addRequired<MachineModuleInfo>();
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800120 AU.addRequired<GCModuleInfo>();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700121 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800122 AU.addRequired<MachineLoopInfo>();
123}
124
125bool AsmPrinter::doInitialization(Module &M) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700126 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
127 MMI->AnalyzeModule(M);
128
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800129 // Initialize TargetLoweringObjectFile.
130 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
131 .Initialize(OutContext, TM);
132
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700133 Mang = new Mangler(OutContext, *TM.getTargetData());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800134
135 // Allow the target to emit any magic that it wants at the start of the file.
136 EmitStartOfAsmFile(M);
137
138 // Very minimal debug info. It is ignored if we emit actual debug info. If we
139 // don't, this at least helps the user find where a global came from.
140 if (MAI->hasSingleParameterDotFile()) {
141 // .file "foo.c"
142 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
143 }
144
145 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
146 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
147 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
148 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700149 MP->beginAssembly(*this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800150
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700151 // Emit module-level inline asm if it exists.
152 if (!M.getModuleInlineAsm().empty()) {
153 OutStreamer.AddComment("Start of file scope inline assembly");
154 OutStreamer.AddBlankLine();
155 EmitInlineAsm(M.getModuleInlineAsm(), 0/*no loc cookie*/);
156 OutStreamer.AddComment("End of file scope inline assembly");
157 OutStreamer.AddBlankLine();
158 }
159
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700160#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700161 if (MAI->doesSupportDebugInformation())
162 DD = new DwarfDebug(this, &M);
163
164 if (MAI->doesSupportExceptionHandling())
165 DE = new DwarfException(this);
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700166#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800167
168 return false;
169}
170
171void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
172 switch ((GlobalValue::LinkageTypes)Linkage) {
173 case GlobalValue::CommonLinkage:
174 case GlobalValue::LinkOnceAnyLinkage:
175 case GlobalValue::LinkOnceODRLinkage:
176 case GlobalValue::WeakAnyLinkage:
177 case GlobalValue::WeakODRLinkage:
178 case GlobalValue::LinkerPrivateLinkage:
179 if (MAI->getWeakDefDirective() != 0) {
180 // .globl _foo
181 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
182 // .weak_definition _foo
183 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
184 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
185 // .globl _foo
186 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
187 // FIXME: linkonce should be a section attribute, handled by COFF Section
188 // assignment.
189 // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
190 // .linkonce discard
191 // FIXME: It would be nice to use .linkonce samesize for non-common
192 // globals.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700193 OutStreamer.EmitRawText(StringRef(LinkOnce));
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800194 } else {
195 // .weak _foo
196 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
197 }
198 break;
199 case GlobalValue::DLLExportLinkage:
200 case GlobalValue::AppendingLinkage:
201 // FIXME: appending linkage variables should go into a section of
202 // their name or something. For now, just emit them as external.
203 case GlobalValue::ExternalLinkage:
204 // If external or appending, declare as a global symbol.
205 // .globl _foo
206 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
207 break;
208 case GlobalValue::PrivateLinkage:
209 case GlobalValue::InternalLinkage:
210 break;
211 default:
212 llvm_unreachable("Unknown linkage type!");
213 }
214}
215
216
217/// EmitGlobalVariable - Emit the specified global variable to the .s file.
218void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
219 if (!GV->hasInitializer()) // External globals require no code.
220 return;
221
222 // Check to see if this is a special global used by LLVM, if so, emit it.
223 if (EmitSpecialLLVMGlobal(GV))
224 return;
225
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700226 MCSymbol *GVSym = Mang->getSymbol(GV);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800227 EmitVisibility(GVSym, GV->getVisibility());
228
229 if (MAI->hasDotTypeDotSizeDirective())
230 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
231
232 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
233
234 const TargetData *TD = TM.getTargetData();
235 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700236
237 // If the alignment is specified, we *must* obey it. Overaligning a global
238 // with a specified alignment is a prompt way to break globals emitted to
239 // sections and expected to be contiguous (e.g. ObjC metadata).
240 unsigned AlignLog;
241 if (unsigned GVAlign = GV->getAlignment())
242 AlignLog = Log2_32(GVAlign);
243 else
244 AlignLog = TD->getPreferredAlignmentLog(GV);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800245
246 // Handle common and BSS local symbols (.lcomm).
247 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
248 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
249
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700250 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800251 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
252 /*PrintType=*/false, GV->getParent());
253 OutStreamer.GetCommentOS() << '\n';
254 }
255
256 // Handle common symbols.
257 if (GVKind.isCommon()) {
258 // .comm _foo, 42, 4
259 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
260 return;
261 }
262
263 // Handle local BSS symbols.
264 if (MAI->hasMachoZeroFillDirective()) {
265 const MCSection *TheSection =
266 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
267 // .zerofill __DATA, __bss, _foo, 400, 5
268 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
269 return;
270 }
271
272 if (MAI->hasLCOMMDirective()) {
273 // .lcomm _foo, 42
274 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
275 return;
276 }
277
278 // .local _foo
279 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
280 // .comm _foo, 42, 4
281 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
282 return;
283 }
284
285 const MCSection *TheSection =
286 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
287
288 // Handle the zerofill directive on darwin, which is a special form of BSS
289 // emission.
290 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
291 // .globl _foo
292 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
293 // .zerofill __DATA, __common, _foo, 400, 5
294 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
295 return;
296 }
297
298 OutStreamer.SwitchSection(TheSection);
299
300 EmitLinkage(GV->getLinkage(), GVSym);
301 EmitAlignment(AlignLog, GV);
302
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700303 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800304 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
305 /*PrintType=*/false, GV->getParent());
306 OutStreamer.GetCommentOS() << '\n';
307 }
308 OutStreamer.EmitLabel(GVSym);
309
310 EmitGlobalConstant(GV->getInitializer());
311
312 if (MAI->hasDotTypeDotSizeDirective())
313 // .size foo, 42
314 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
315
316 OutStreamer.AddBlankLine();
317}
318
319/// EmitFunctionHeader - This method emits the header for the current
320/// function.
321void AsmPrinter::EmitFunctionHeader() {
322 // Print out constants referenced by the function
323 EmitConstantPool();
324
325 // Print the 'header' of function.
326 const Function *F = MF->getFunction();
327
328 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
329 EmitVisibility(CurrentFnSym, F->getVisibility());
330
331 EmitLinkage(F->getLinkage(), CurrentFnSym);
332 EmitAlignment(MF->getAlignment(), F);
333
334 if (MAI->hasDotTypeDotSizeDirective())
335 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
336
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700337 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800338 WriteAsOperand(OutStreamer.GetCommentOS(), F,
339 /*PrintType=*/false, F->getParent());
340 OutStreamer.GetCommentOS() << '\n';
341 }
342
343 // Emit the CurrentFnSym. This is a virtual function to allow targets to
344 // do their wild and crazy things as required.
345 EmitFunctionEntryLabel();
346
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700347 // If the function had address-taken blocks that got deleted, then we have
348 // references to the dangling symbols. Emit them at the start of the function
349 // so that we don't get references to undefined symbols.
350 std::vector<MCSymbol*> DeadBlockSyms;
351 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
352 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
353 OutStreamer.AddComment("Address taken block that was later removed");
354 OutStreamer.EmitLabel(DeadBlockSyms[i]);
355 }
356
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800357 // Add some workaround for linkonce linkage on Cygwin\MinGW.
358 if (MAI->getLinkOnceDirective() != 0 &&
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700359 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800360 // FIXME: What is this?
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700361 MCSymbol *FakeStub =
362 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
363 CurrentFnSym->getName());
364 OutStreamer.EmitLabel(FakeStub);
365 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800366
367 // Emit pre-function debug and/or EH information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700368#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700369 if (DE) {
370 if (TimePassesIsEnabled) {
371 NamedRegionTimer T(EHTimerName, DWARFGroupName);
372 DE->BeginFunction(MF);
373 } else {
374 DE->BeginFunction(MF);
375 }
376 }
377 if (DD) {
378 if (TimePassesIsEnabled) {
379 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
380 DD->beginFunction(MF);
381 } else {
382 DD->beginFunction(MF);
383 }
384 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700385#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800386}
387
388/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
389/// function. This can be overridden by targets as required to do custom stuff.
390void AsmPrinter::EmitFunctionEntryLabel() {
391 OutStreamer.EmitLabel(CurrentFnSym);
392}
393
394
395/// EmitComments - Pretty-print comments for instructions.
396static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
397 const MachineFunction *MF = MI.getParent()->getParent();
398 const TargetMachine &TM = MF->getTarget();
399
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700400 DebugLoc DL = MI.getDebugLoc();
401 if (!DL.isUnknown()) { // Print source line info.
402 DIScope Scope(DL.getScope(MF->getFunction()->getContext()));
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800403 // Omit the directory, because it's likely to be long and uninteresting.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700404 if (Scope.Verify())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800405 CommentOS << Scope.getFilename();
406 else
407 CommentOS << "<unknown>";
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700408 CommentOS << ':' << DL.getLine();
409 if (DL.getCol() != 0)
410 CommentOS << ':' << DL.getCol();
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800411 CommentOS << '\n';
412 }
413
414 // Check for spills and reloads
415 int FI;
416
417 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
418
419 // We assume a single instruction only has a spill or reload, not
420 // both.
421 const MachineMemOperand *MMO;
422 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
423 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
424 MMO = *MI.memoperands_begin();
425 CommentOS << MMO->getSize() << "-byte Reload\n";
426 }
427 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
428 if (FrameInfo->isSpillSlotObjectIndex(FI))
429 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
430 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
431 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
432 MMO = *MI.memoperands_begin();
433 CommentOS << MMO->getSize() << "-byte Spill\n";
434 }
435 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
436 if (FrameInfo->isSpillSlotObjectIndex(FI))
437 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
438 }
439
440 // Check for spill-induced copies
441 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
442 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
443 SrcSubIdx, DstSubIdx)) {
444 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
445 CommentOS << " Reload Reuse\n";
446 }
447}
448
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700449/// EmitImplicitDef - This method emits the specified machine instruction
450/// that is an implicit def.
451static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
452 unsigned RegNo = MI->getOperand(0).getReg();
453 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
454 AP.TM.getRegisterInfo()->getName(RegNo));
455 AP.OutStreamer.AddBlankLine();
456}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800457
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700458static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
459 std::string Str = "kill:";
460 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
461 const MachineOperand &Op = MI->getOperand(i);
462 assert(Op.isReg() && "KILL instruction must have only register operands");
463 Str += ' ';
464 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
465 Str += (Op.isDef() ? "<def>" : "<kill>");
466 }
467 AP.OutStreamer.AddComment(Str);
468 AP.OutStreamer.AddBlankLine();
469}
470
471/// EmitDebugValueComment - This method handles the target-independent form
472/// of DBG_VALUE, returning true if it was able to do so. A false return
473/// means the target will need to handle MI in EmitInstruction.
474static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
475 // This code handles only the 3-operand target-independent form.
476 if (MI->getNumOperands() != 3)
477 return false;
478
479 SmallString<128> Str;
480 raw_svector_ostream OS(Str);
481 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
482
483 // cast away const; DIetc do not take const operands for some reason.
484 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
485 OS << V.getName() << " <- ";
486
487 // Register or immediate value. Register 0 means undef.
488 if (MI->getOperand(0).isFPImm()) {
489 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
490 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
491 OS << (double)APF.convertToFloat();
492 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
493 OS << APF.convertToDouble();
494 } else {
495 // There is no good way to print long double. Convert a copy to
496 // double. Ah well, it's only a comment.
497 bool ignored;
498 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
499 &ignored);
500 OS << "(long double) " << APF.convertToDouble();
501 }
502 } else if (MI->getOperand(0).isImm()) {
503 OS << MI->getOperand(0).getImm();
504 } else {
505 assert(MI->getOperand(0).isReg() && "Unknown operand type");
506 if (MI->getOperand(0).getReg() == 0) {
507 // Suppress offset, it is not meaningful here.
508 OS << "undef";
509 // NOTE: Want this comment at start of line, don't emit with AddComment.
510 AP.OutStreamer.EmitRawText(OS.str());
511 return true;
512 }
513 OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
514 }
515
516 OS << '+' << MI->getOperand(1).getImm();
517 // NOTE: Want this comment at start of line, don't emit with AddComment.
518 AP.OutStreamer.EmitRawText(OS.str());
519 return true;
520}
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800521
522/// EmitFunctionBody - This method emits the body and trailer for a
523/// function.
524void AsmPrinter::EmitFunctionBody() {
525 // Emit target-specific gunk before the function body.
526 EmitFunctionBodyStart();
527
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700528 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
529
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800530 // Print out code for the function.
531 bool HasAnyRealCode = false;
532 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
533 I != E; ++I) {
534 // Print a label for the basic block.
535 EmitBasicBlockStart(I);
536 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
537 II != IE; ++II) {
538 // Print the assembly for the instruction.
539 if (!II->isLabel())
540 HasAnyRealCode = true;
541
542 ++EmittedInsts;
543
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700544#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700545 if (ShouldPrintDebugScopes) {
546 if (TimePassesIsEnabled) {
547 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
548 DD->beginScope(II);
549 } else {
550 DD->beginScope(II);
551 }
552 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700553#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800554
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700555 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800556 EmitComments(*II, OutStreamer.GetCommentOS());
557
558 switch (II->getOpcode()) {
559 case TargetOpcode::DBG_LABEL:
560 case TargetOpcode::EH_LABEL:
561 case TargetOpcode::GC_LABEL:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700562 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800563 break;
564 case TargetOpcode::INLINEASM:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700565 EmitInlineAsm(II);
566 break;
567 case TargetOpcode::DBG_VALUE:
568 if (isVerbose()) {
569 if (!EmitDebugValueComment(II, *this))
570 EmitInstruction(II);
571 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800572 break;
573 case TargetOpcode::IMPLICIT_DEF:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700574 if (isVerbose()) EmitImplicitDef(II, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800575 break;
576 case TargetOpcode::KILL:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700577 if (isVerbose()) EmitKill(II, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800578 break;
579 default:
580 EmitInstruction(II);
581 break;
582 }
583
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700584#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700585 if (ShouldPrintDebugScopes) {
586 if (TimePassesIsEnabled) {
587 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
588 DD->endScope(II);
589 } else {
590 DD->endScope(II);
591 }
592 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700593#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800594 }
595 }
596
597 // If the function is empty and the object file uses .subsections_via_symbols,
598 // then we need to emit *something* to the function body to prevent the
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700599 // labels from collapsing together. Just emit a noop.
600 if (MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) {
601 MCInst Noop;
602 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
603 if (Noop.getOpcode()) {
604 OutStreamer.AddComment("avoids zero-length function");
605 OutStreamer.EmitInstruction(Noop);
606 } else // Target not mc-ized yet.
607 OutStreamer.EmitRawText(StringRef("\tnop\n"));
608 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800609
610 // Emit target-specific gunk after the function body.
611 EmitFunctionBodyEnd();
612
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700613 // If the target wants a .size directive for the size of the function, emit
614 // it.
615 if (MAI->hasDotTypeDotSizeDirective()) {
616 // Create a symbol for the end of function, so we can get the size as
617 // difference between the function label and the temp label.
618 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
619 OutStreamer.EmitLabel(FnEndLabel);
620
621 const MCExpr *SizeExp =
622 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
623 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
624 OutContext);
625 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
626 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800627
628 // Emit post-function debug information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700629#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700630 if (DD) {
631 if (TimePassesIsEnabled) {
632 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
633 DD->endFunction(MF);
634 } else {
635 DD->endFunction(MF);
636 }
637 }
638 if (DE) {
639 if (TimePassesIsEnabled) {
640 NamedRegionTimer T(EHTimerName, DWARFGroupName);
641 DE->EndFunction();
642 } else {
643 DE->EndFunction();
644 }
645 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700646#endif // ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700647 MMI->EndFunction();
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800648
649 // Print out jump tables referenced by the function.
650 EmitJumpTableInfo();
651
652 OutStreamer.AddBlankLine();
653}
654
655
656bool AsmPrinter::doFinalization(Module &M) {
657 // Emit global variables.
658 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
659 I != E; ++I)
660 EmitGlobalVariable(I);
661
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700662 // Finalize debug and EH information.
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700663#ifndef ANDROID_TARGET_BUILD
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700664 if (DE) {
665 if (TimePassesIsEnabled) {
666 NamedRegionTimer T(EHTimerName, DWARFGroupName);
667 DE->EndModule();
668 } else {
669 DE->EndModule();
670 }
671 delete DE; DE = 0;
672 }
673 if (DD) {
674 if (TimePassesIsEnabled) {
675 NamedRegionTimer T(DbgTimerName, DWARFGroupName);
676 DD->endModule();
677 } else {
678 DD->endModule();
679 }
680 delete DD; DD = 0;
681 }
Shih-wei Liaoa59a85f2010-04-29 00:24:07 -0700682#endif // ANDROID_TARGET_BUILD
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800683
684 // If the target wants to know about weak references, print them all.
685 if (MAI->getWeakRefDirective()) {
686 // FIXME: This is not lazy, it would be nice to only print weak references
687 // to stuff that is actually used. Note that doing so would require targets
688 // to notice uses in operands (due to constant exprs etc). This should
689 // happen with the MC stuff eventually.
690
691 // Print out module-level global variables here.
692 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
693 I != E; ++I) {
694 if (!I->hasExternalWeakLinkage()) continue;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700695 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800696 }
697
698 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
699 if (!I->hasExternalWeakLinkage()) continue;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700700 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800701 }
702 }
703
704 if (MAI->hasSetDirective()) {
705 OutStreamer.AddBlankLine();
706 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
707 I != E; ++I) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700708 MCSymbol *Name = Mang->getSymbol(I);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800709
710 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700711 MCSymbol *Target = Mang->getSymbol(GV);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800712
713 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
714 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
715 else if (I->hasWeakLinkage())
716 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
717 else
718 assert(I->hasLocalLinkage() && "Invalid alias linkage");
719
720 EmitVisibility(Name, I->getVisibility());
721
722 // Emit the directives as assignments aka .set:
723 OutStreamer.EmitAssignment(Name,
724 MCSymbolRefExpr::Create(Target, OutContext));
725 }
726 }
727
728 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
729 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
730 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
731 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700732 MP->finishAssembly(*this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800733
734 // If we don't have any trampolines, then we don't require stack memory
735 // to be executable. Some targets have a directive to declare this.
736 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
737 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700738 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800739 OutStreamer.SwitchSection(S);
740
741 // Allow the target to emit any magic that it wants at the end of the file,
742 // after everything else has gone out.
743 EmitEndOfAsmFile(M);
744
745 delete Mang; Mang = 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700746 MMI = 0;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800747
748 OutStreamer.Finish();
749 return false;
750}
751
752void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
753 this->MF = &MF;
754 // Get the function symbol.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700755 CurrentFnSym = Mang->getSymbol(MF.getFunction());
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800756
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700757 if (isVerbose())
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800758 LI = &getAnalysis<MachineLoopInfo>();
759}
760
761namespace {
762 // SectionCPs - Keep track the alignment, constpool entries per Section.
763 struct SectionCPs {
764 const MCSection *S;
765 unsigned Alignment;
766 SmallVector<unsigned, 4> CPEs;
767 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
768 };
769}
770
771/// EmitConstantPool - Print to the current output stream assembly
772/// representations of the constants in the constant pool MCP. This is
773/// used to print out constants which have been "spilled to memory" by
774/// the code generator.
775///
776void AsmPrinter::EmitConstantPool() {
777 const MachineConstantPool *MCP = MF->getConstantPool();
778 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
779 if (CP.empty()) return;
780
781 // Calculate sections for constant pool entries. We collect entries to go into
782 // the same section together to reduce amount of section switch statements.
783 SmallVector<SectionCPs, 4> CPSections;
784 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
785 const MachineConstantPoolEntry &CPE = CP[i];
786 unsigned Align = CPE.getAlignment();
787
788 SectionKind Kind;
789 switch (CPE.getRelocationInfo()) {
790 default: llvm_unreachable("Unknown section kind");
791 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
792 case 1:
793 Kind = SectionKind::getReadOnlyWithRelLocal();
794 break;
795 case 0:
796 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
797 case 4: Kind = SectionKind::getMergeableConst4(); break;
798 case 8: Kind = SectionKind::getMergeableConst8(); break;
799 case 16: Kind = SectionKind::getMergeableConst16();break;
800 default: Kind = SectionKind::getMergeableConst(); break;
801 }
802 }
803
804 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
805
806 // The number of sections are small, just do a linear search from the
807 // last section to the first.
808 bool Found = false;
809 unsigned SecIdx = CPSections.size();
810 while (SecIdx != 0) {
811 if (CPSections[--SecIdx].S == S) {
812 Found = true;
813 break;
814 }
815 }
816 if (!Found) {
817 SecIdx = CPSections.size();
818 CPSections.push_back(SectionCPs(S, Align));
819 }
820
821 if (Align > CPSections[SecIdx].Alignment)
822 CPSections[SecIdx].Alignment = Align;
823 CPSections[SecIdx].CPEs.push_back(i);
824 }
825
826 // Now print stuff into the calculated sections.
827 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
828 OutStreamer.SwitchSection(CPSections[i].S);
829 EmitAlignment(Log2_32(CPSections[i].Alignment));
830
831 unsigned Offset = 0;
832 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
833 unsigned CPI = CPSections[i].CPEs[j];
834 MachineConstantPoolEntry CPE = CP[CPI];
835
836 // Emit inter-object padding for alignment.
837 unsigned AlignMask = CPE.getAlignment() - 1;
838 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
839 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
840
841 const Type *Ty = CPE.getType();
842 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
843
844 // Emit the label with a comment on it.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700845 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800846 OutStreamer.GetCommentOS() << "constant pool ";
847 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
848 MF->getFunction()->getParent());
849 OutStreamer.GetCommentOS() << '\n';
850 }
851 OutStreamer.EmitLabel(GetCPISymbol(CPI));
852
853 if (CPE.isMachineConstantPoolEntry())
854 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
855 else
856 EmitGlobalConstant(CPE.Val.ConstVal);
857 }
858 }
859}
860
861/// EmitJumpTableInfo - Print assembly representations of the jump tables used
862/// by the current function to the current output stream.
863///
864void AsmPrinter::EmitJumpTableInfo() {
865 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
866 if (MJTI == 0) return;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700867 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800868 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
869 if (JT.empty()) return;
870
871 // Pick the directive to use to print the jump table entries, and switch to
872 // the appropriate section.
873 const Function *F = MF->getFunction();
874 bool JTInDiffSection = false;
875 if (// In PIC mode, we need to emit the jump table to the same section as the
876 // function body itself, otherwise the label differences won't make sense.
877 // FIXME: Need a better predicate for this: what about custom entries?
878 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
879 // We should also do if the section name is NULL or function is declared
880 // in discardable section
881 // FIXME: this isn't the right predicate, should be based on the MCSection
882 // for the function.
883 F->isWeakForLinker()) {
884 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
885 } else {
886 // Otherwise, drop it in the readonly section.
887 const MCSection *ReadOnlySection =
888 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
889 OutStreamer.SwitchSection(ReadOnlySection);
890 JTInDiffSection = true;
891 }
892
893 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
894
895 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
896 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
897
898 // If this jump table was deleted, ignore it.
899 if (JTBBs.empty()) continue;
900
901 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
902 // .set directive for each unique entry. This reduces the number of
903 // relocations the assembler will generate for the jump table.
904 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
905 MAI->hasSetDirective()) {
906 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
907 const TargetLowering *TLI = TM.getTargetLowering();
908 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
909 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
910 const MachineBasicBlock *MBB = JTBBs[ii];
911 if (!EmittedSets.insert(MBB)) continue;
912
913 // .set LJTSet, LBB32-base
914 const MCExpr *LHS =
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700915 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800916 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
917 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
918 }
919 }
920
921 // On some targets (e.g. Darwin) we want to emit two consequtive labels
922 // before each jump table. The first label is never referenced, but tells
923 // the assembler and linker the extents of the jump table object. The
924 // second label is actually referenced by the code.
925 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
926 // FIXME: This doesn't have to have any specific name, just any randomly
927 // named and numbered 'l' label would work. Simplify GetJTISymbol.
928 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
929
930 OutStreamer.EmitLabel(GetJTISymbol(JTI));
931
932 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
933 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
934 }
935}
936
937/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
938/// current stream.
939void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
940 const MachineBasicBlock *MBB,
941 unsigned UID) const {
942 const MCExpr *Value = 0;
943 switch (MJTI->getEntryKind()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700944 case MachineJumpTableInfo::EK_Inline:
945 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800946 case MachineJumpTableInfo::EK_Custom32:
947 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
948 OutContext);
949 break;
950 case MachineJumpTableInfo::EK_BlockAddress:
951 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
952 // .word LBB123
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700953 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800954 break;
955 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
956 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
957 // with a relocation as gp-relative, e.g.:
958 // .gprel32 LBB123
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700959 MCSymbol *MBBSym = MBB->getSymbol();
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800960 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
961 return;
962 }
963
964 case MachineJumpTableInfo::EK_LabelDifference32: {
965 // EK_LabelDifference32 - Each entry is the address of the block minus
966 // the address of the jump table. This is used for PIC jump tables where
967 // gprel32 is not supported. e.g.:
968 // .word LBB123 - LJTI1_2
969 // If the .set directive is supported, this is emitted as:
970 // .set L4_5_set_123, LBB123 - LJTI1_2
971 // .word L4_5_set_123
972
973 // If we have emitted set directives for the jump table entries, print
974 // them rather than the entries themselves. If we're emitting PIC, then
975 // emit the table entries as differences between two text section labels.
976 if (MAI->hasSetDirective()) {
977 // If we used .set, reference the .set's symbol.
978 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
979 OutContext);
980 break;
981 }
982 // Otherwise, use the difference as the jump table entry.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -0700983 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Shih-wei Liaoe264f622010-02-10 11:10:31 -0800984 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
985 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
986 break;
987 }
988 }
989
990 assert(Value && "Unknown entry kind!");
991
992 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
993 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
994}
995
996
997/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
998/// special global used by LLVM. If so, emit it and return true, otherwise
999/// do nothing and return false.
1000bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1001 if (GV->getName() == "llvm.used") {
1002 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1003 EmitLLVMUsedList(GV->getInitializer());
1004 return true;
1005 }
1006
1007 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1008 if (GV->getSection() == "llvm.metadata" ||
1009 GV->hasAvailableExternallyLinkage())
1010 return true;
1011
1012 if (!GV->hasAppendingLinkage()) return false;
1013
1014 assert(GV->hasInitializer() && "Not a special LLVM global!");
1015
1016 const TargetData *TD = TM.getTargetData();
1017 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1018 if (GV->getName() == "llvm.global_ctors") {
1019 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
1020 EmitAlignment(Align, 0);
1021 EmitXXStructorList(GV->getInitializer());
1022
1023 if (TM.getRelocationModel() == Reloc::Static &&
1024 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1025 StringRef Sym(".constructors_used");
1026 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1027 MCSA_Reference);
1028 }
1029 return true;
1030 }
1031
1032 if (GV->getName() == "llvm.global_dtors") {
1033 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
1034 EmitAlignment(Align, 0);
1035 EmitXXStructorList(GV->getInitializer());
1036
1037 if (TM.getRelocationModel() == Reloc::Static &&
1038 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1039 StringRef Sym(".destructors_used");
1040 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1041 MCSA_Reference);
1042 }
1043 return true;
1044 }
1045
1046 return false;
1047}
1048
1049/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1050/// global in the specified llvm.used list for which emitUsedDirectiveFor
1051/// is true, as being used with this directive.
1052void AsmPrinter::EmitLLVMUsedList(Constant *List) {
1053 // Should be an array of 'i8*'.
1054 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1055 if (InitList == 0) return;
1056
1057 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1058 const GlobalValue *GV =
1059 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1060 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001061 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001062 }
1063}
1064
1065/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
1066/// function pointers, ignoring the init priority.
1067void AsmPrinter::EmitXXStructorList(Constant *List) {
1068 // Should be an array of '{ int, void ()* }' structs. The first value is the
1069 // init priority, which we ignore.
1070 if (!isa<ConstantArray>(List)) return;
1071 ConstantArray *InitList = cast<ConstantArray>(List);
1072 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1073 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1074 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
1075
1076 if (CS->getOperand(1)->isNullValue())
1077 return; // Found a null terminator, exit printing.
1078 // Emit the function pointer.
1079 EmitGlobalConstant(CS->getOperand(1));
1080 }
1081}
1082
1083//===--------------------------------------------------------------------===//
1084// Emission and print routines
1085//
1086
1087/// EmitInt8 - Emit a byte directive and value.
1088///
1089void AsmPrinter::EmitInt8(int Value) const {
1090 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1091}
1092
1093/// EmitInt16 - Emit a short directive and value.
1094///
1095void AsmPrinter::EmitInt16(int Value) const {
1096 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1097}
1098
1099/// EmitInt32 - Emit a long directive and value.
1100///
1101void AsmPrinter::EmitInt32(int Value) const {
1102 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1103}
1104
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001105/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1106/// in bytes of the directive is specified by Size and Hi/Lo specify the
1107/// labels. This implicitly uses .set if it is available.
1108void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1109 unsigned Size) const {
1110 // Get the Hi-Lo expression.
1111 const MCExpr *Diff =
1112 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1113 MCSymbolRefExpr::Create(Lo, OutContext),
1114 OutContext);
1115
1116 if (!MAI->hasSetDirective()) {
1117 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1118 return;
1119 }
1120
1121 // Otherwise, emit with .set (aka assignment).
1122 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1123 OutStreamer.EmitAssignment(SetLabel, Diff);
1124 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001125}
1126
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001127/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1128/// where the size in bytes of the directive is specified by Size and Hi/Lo
1129/// specify the labels. This implicitly uses .set if it is available.
1130void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1131 const MCSymbol *Lo, unsigned Size)
1132 const {
1133
1134 // Emit Hi+Offset - Lo
1135 // Get the Hi+Offset expression.
1136 const MCExpr *Plus =
1137 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1138 MCConstantExpr::Create(Offset, OutContext),
1139 OutContext);
1140
1141 // Get the Hi+Offset-Lo expression.
1142 const MCExpr *Diff =
1143 MCBinaryExpr::CreateSub(Plus,
1144 MCSymbolRefExpr::Create(Lo, OutContext),
1145 OutContext);
1146
1147 if (!MAI->hasSetDirective())
1148 OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1149 else {
1150 // Otherwise, emit with .set (aka assignment).
1151 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1152 OutStreamer.EmitAssignment(SetLabel, Diff);
1153 OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1154 }
1155}
1156
1157
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001158//===----------------------------------------------------------------------===//
1159
1160// EmitAlignment - Emit an alignment directive to the specified power of
1161// two boundary. For example, if you pass in 3 here, you will get an 8
1162// byte alignment. If a global value is specified, and if that global has
1163// an explicit alignment requested, it will unconditionally override the
1164// alignment request. However, if ForcedAlignBits is specified, this value
1165// has final say: the ultimate alignment will be the max of ForcedAlignBits
1166// and the alignment computed with NumBits and the global.
1167//
1168// The algorithm is:
1169// Align = NumBits;
1170// if (GV && GV->hasalignment) Align = GV->getalignment();
1171// Align = std::max(Align, ForcedAlignBits);
1172//
1173void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
1174 unsigned ForcedAlignBits,
1175 bool UseFillExpr) const {
1176 if (GV && GV->getAlignment())
1177 NumBits = Log2_32(GV->getAlignment());
1178 NumBits = std::max(NumBits, ForcedAlignBits);
1179
1180 if (NumBits == 0) return; // No need to emit alignment.
1181
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001182 if (getCurrentSection()->getKind().isText())
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001183 OutStreamer.EmitCodeAlignment(1 << NumBits);
1184 else
1185 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001186}
1187
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001188//===----------------------------------------------------------------------===//
1189// Constant emission.
1190//===----------------------------------------------------------------------===//
1191
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001192/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1193///
1194static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1195 MCContext &Ctx = AP.OutContext;
1196
1197 if (CV->isNullValue() || isa<UndefValue>(CV))
1198 return MCConstantExpr::Create(0, Ctx);
1199
1200 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1201 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1202
1203 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001204 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001205 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1206 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1207
1208 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1209 if (CE == 0) {
1210 llvm_unreachable("Unknown constant value to lower!");
1211 return MCConstantExpr::Create(0, Ctx);
1212 }
1213
1214 switch (CE->getOpcode()) {
1215 default:
1216 // If the code isn't optimized, there may be outstanding folding
1217 // opportunities. Attempt to fold the expression using TargetData as a
1218 // last resort before giving up.
1219 if (Constant *C =
1220 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1221 if (C != CE)
1222 return LowerConstant(C, AP);
1223#ifndef NDEBUG
1224 CE->dump();
1225#endif
1226 llvm_unreachable("FIXME: Don't support this constant expr");
1227 case Instruction::GetElementPtr: {
1228 const TargetData &TD = *AP.TM.getTargetData();
1229 // Generate a symbolic expression for the byte address
1230 const Constant *PtrVal = CE->getOperand(0);
1231 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1232 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1233 IdxVec.size());
1234
1235 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1236 if (Offset == 0)
1237 return Base;
1238
1239 // Truncate/sext the offset to the pointer size.
1240 if (TD.getPointerSizeInBits() != 64) {
1241 int SExtAmount = 64-TD.getPointerSizeInBits();
1242 Offset = (Offset << SExtAmount) >> SExtAmount;
1243 }
1244
1245 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1246 Ctx);
1247 }
1248
1249 case Instruction::Trunc:
1250 // We emit the value and depend on the assembler to truncate the generated
1251 // expression properly. This is important for differences between
1252 // blockaddress labels. Since the two labels are in the same function, it
1253 // is reasonable to treat their delta as a 32-bit value.
1254 // FALL THROUGH.
1255 case Instruction::BitCast:
1256 return LowerConstant(CE->getOperand(0), AP);
1257
1258 case Instruction::IntToPtr: {
1259 const TargetData &TD = *AP.TM.getTargetData();
1260 // Handle casts to pointers by changing them into casts to the appropriate
1261 // integer type. This promotes constant folding and simplifies this code.
1262 Constant *Op = CE->getOperand(0);
1263 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1264 false/*ZExt*/);
1265 return LowerConstant(Op, AP);
1266 }
1267
1268 case Instruction::PtrToInt: {
1269 const TargetData &TD = *AP.TM.getTargetData();
1270 // Support only foldable casts to/from pointers that can be eliminated by
1271 // changing the pointer to the appropriately sized integer type.
1272 Constant *Op = CE->getOperand(0);
1273 const Type *Ty = CE->getType();
1274
1275 const MCExpr *OpExpr = LowerConstant(Op, AP);
1276
1277 // We can emit the pointer value into this slot if the slot is an
1278 // integer slot equal to the size of the pointer.
1279 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1280 return OpExpr;
1281
1282 // Otherwise the pointer is smaller than the resultant integer, mask off
1283 // the high bits so we are sure to get a proper truncation if the input is
1284 // a constant expr.
1285 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1286 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1287 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1288 }
1289
1290 // The MC library also has a right-shift operator, but it isn't consistently
1291 // signed or unsigned between different targets.
1292 case Instruction::Add:
1293 case Instruction::Sub:
1294 case Instruction::Mul:
1295 case Instruction::SDiv:
1296 case Instruction::SRem:
1297 case Instruction::Shl:
1298 case Instruction::And:
1299 case Instruction::Or:
1300 case Instruction::Xor: {
1301 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1302 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1303 switch (CE->getOpcode()) {
1304 default: llvm_unreachable("Unknown binary operator constant cast expr");
1305 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1306 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1307 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1308 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1309 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1310 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1311 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1312 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1313 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1314 }
1315 }
1316 }
1317}
1318
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001319static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1320 AsmPrinter &AP);
1321
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001322static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1323 AsmPrinter &AP) {
1324 if (AddrSpace != 0 || !CA->isString()) {
1325 // Not a string. Print the values in successive locations
1326 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001327 EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001328 return;
1329 }
1330
1331 // Otherwise, it can be emitted as .ascii.
1332 SmallVector<char, 128> TmpVec;
1333 TmpVec.reserve(CA->getNumOperands());
1334 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1335 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1336
1337 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1338}
1339
1340static void EmitGlobalConstantVector(const ConstantVector *CV,
1341 unsigned AddrSpace, AsmPrinter &AP) {
1342 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001343 EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001344}
1345
1346static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1347 unsigned AddrSpace, AsmPrinter &AP) {
1348 // Print the fields in successive locations. Pad to align if needed!
1349 const TargetData *TD = AP.TM.getTargetData();
1350 unsigned Size = TD->getTypeAllocSize(CS->getType());
1351 const StructLayout *Layout = TD->getStructLayout(CS->getType());
1352 uint64_t SizeSoFar = 0;
1353 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1354 const Constant *Field = CS->getOperand(i);
1355
1356 // Check if padding is needed and insert one or more 0s.
1357 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1358 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1359 - Layout->getElementOffset(i)) - FieldSize;
1360 SizeSoFar += FieldSize + PadSize;
1361
1362 // Now print the actual field value.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001363 EmitGlobalConstantImpl(Field, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001364
1365 // Insert padding - this may include padding to increase the size of the
1366 // current field up to the ABI size (if the struct is not packed) as well
1367 // as padding to ensure that the next field starts at the right offset.
1368 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1369 }
1370 assert(SizeSoFar == Layout->getSizeInBytes() &&
1371 "Layout of constant struct may be incorrect!");
1372}
1373
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001374static void EmitGlobalConstantUnion(const ConstantUnion *CU,
1375 unsigned AddrSpace, AsmPrinter &AP) {
1376 const TargetData *TD = AP.TM.getTargetData();
1377 unsigned Size = TD->getTypeAllocSize(CU->getType());
1378
1379 const Constant *Contents = CU->getOperand(0);
1380 unsigned FilledSize = TD->getTypeAllocSize(Contents->getType());
1381
1382 // Print the actually filled part
1383 EmitGlobalConstantImpl(Contents, AddrSpace, AP);
1384
1385 // And pad with enough zeroes
1386 AP.OutStreamer.EmitZeros(Size-FilledSize, AddrSpace);
1387}
1388
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001389static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1390 AsmPrinter &AP) {
1391 // FP Constants are printed as integer constants to avoid losing
1392 // precision.
1393 if (CFP->getType()->isDoubleTy()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001394 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001395 double Val = CFP->getValueAPF().convertToDouble();
1396 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1397 }
1398
1399 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1400 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1401 return;
1402 }
1403
1404 if (CFP->getType()->isFloatTy()) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001405 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001406 float Val = CFP->getValueAPF().convertToFloat();
1407 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1408 }
1409 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1410 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1411 return;
1412 }
1413
1414 if (CFP->getType()->isX86_FP80Ty()) {
1415 // all long double variants are printed as hex
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001416 // API needed to prevent premature destruction
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001417 APInt API = CFP->getValueAPF().bitcastToAPInt();
1418 const uint64_t *p = API.getRawData();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001419 if (AP.isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001420 // Convert to double so we can print the approximate val as a comment.
1421 APFloat DoubleVal = CFP->getValueAPF();
1422 bool ignored;
1423 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1424 &ignored);
1425 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1426 << DoubleVal.convertToDouble() << '\n';
1427 }
1428
1429 if (AP.TM.getTargetData()->isBigEndian()) {
1430 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1431 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1432 } else {
1433 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1434 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1435 }
1436
1437 // Emit the tail padding for the long double.
1438 const TargetData &TD = *AP.TM.getTargetData();
1439 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1440 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1441 return;
1442 }
1443
1444 assert(CFP->getType()->isPPC_FP128Ty() &&
1445 "Floating point constant type not handled");
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001446 // All long double variants are printed as hex
1447 // API needed to prevent premature destruction.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001448 APInt API = CFP->getValueAPF().bitcastToAPInt();
1449 const uint64_t *p = API.getRawData();
1450 if (AP.TM.getTargetData()->isBigEndian()) {
1451 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1452 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1453 } else {
1454 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1455 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1456 }
1457}
1458
1459static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1460 unsigned AddrSpace, AsmPrinter &AP) {
1461 const TargetData *TD = AP.TM.getTargetData();
1462 unsigned BitWidth = CI->getBitWidth();
1463 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1464
1465 // We don't expect assemblers to support integer data directives
1466 // for more than 64 bits, so we emit the data in at most 64-bit
1467 // quantities at a time.
1468 const uint64_t *RawData = CI->getValue().getRawData();
1469 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1470 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1471 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1472 }
1473}
1474
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001475static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1476 AsmPrinter &AP) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001477 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001478 uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1479 return AP.OutStreamer.EmitZeros(Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001480 }
1481
1482 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001483 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001484 switch (Size) {
1485 case 1:
1486 case 2:
1487 case 4:
1488 case 8:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001489 if (AP.isVerbose())
1490 AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1491 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001492 return;
1493 default:
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001494 EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001495 return;
1496 }
1497 }
1498
1499 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001500 return EmitGlobalConstantArray(CVA, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001501
1502 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001503 return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001504
1505 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001506 return EmitGlobalConstantFP(CFP, AddrSpace, AP);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001507
1508 if (isa<ConstantPointerNull>(CV)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001509 unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1510 AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001511 return;
1512 }
1513
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001514 if (const ConstantUnion *CVU = dyn_cast<ConstantUnion>(CV))
1515 return EmitGlobalConstantUnion(CVU, AddrSpace, AP);
1516
1517 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1518 return EmitGlobalConstantVector(V, AddrSpace, AP);
1519
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001520 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1521 // thread the streamer with EmitValue.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001522 AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1523 AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1524 AddrSpace);
1525}
1526
1527/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1528void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1529 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1530 if (Size)
1531 EmitGlobalConstantImpl(CV, AddrSpace, *this);
1532 else if (MAI->hasSubsectionsViaSymbols()) {
1533 // If the global has zero size, emit a single byte so that two labels don't
1534 // look like they are at the same location.
1535 OutStreamer.EmitIntValue(0, 1, AddrSpace);
1536 }
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001537}
1538
1539void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1540 // Target doesn't support this yet!
1541 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1542}
1543
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001544void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1545 if (Offset > 0)
1546 OS << '+' << Offset;
1547 else if (Offset < 0)
1548 OS << Offset;
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001549}
1550
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001551//===----------------------------------------------------------------------===//
1552// Symbol Lowering Routines.
1553//===----------------------------------------------------------------------===//
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001554
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001555/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1556/// temporary label with the specified stem and unique ID.
1557MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1558 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1559 Name + Twine(ID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001560}
1561
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001562/// GetTempSymbol - Return an assembler temporary label with the specified
1563/// stem.
1564MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1565 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1566 Name);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001567}
1568
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001569
1570MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001571 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001572}
1573
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001574MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1575 return MMI->getAddrLabelSymbol(BB);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001576}
1577
1578/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1579MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001580 return OutContext.GetOrCreateSymbol
1581 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1582 + "_" + Twine(CPID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001583}
1584
1585/// GetJTISymbol - Return the symbol for the specified jump table entry.
1586MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1587 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1588}
1589
1590/// GetJTSetSymbol - Return the symbol for the specified jump table .set
1591/// FIXME: privatize to AsmPrinter.
1592MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001593 return OutContext.GetOrCreateSymbol
1594 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1595 Twine(UID) + "_set_" + Twine(MBBID));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001596}
1597
1598/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1599/// global value name as its base, with the specified suffix, and where the
1600/// symbol is forced to have private linkage if ForcePrivate is true.
1601MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1602 StringRef Suffix,
1603 bool ForcePrivate) const {
1604 SmallString<60> NameStr;
1605 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1606 NameStr.append(Suffix.begin(), Suffix.end());
1607 return OutContext.GetOrCreateSymbol(NameStr.str());
1608}
1609
1610/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1611/// ExternalSymbol.
1612MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1613 SmallString<60> NameStr;
1614 Mang->getNameWithPrefix(NameStr, Sym);
1615 return OutContext.GetOrCreateSymbol(NameStr.str());
1616}
1617
1618
1619
1620/// PrintParentLoopComment - Print comments about parent loops of this one.
1621static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1622 unsigned FunctionNumber) {
1623 if (Loop == 0) return;
1624 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1625 OS.indent(Loop->getLoopDepth()*2)
1626 << "Parent Loop BB" << FunctionNumber << "_"
1627 << Loop->getHeader()->getNumber()
1628 << " Depth=" << Loop->getLoopDepth() << '\n';
1629}
1630
1631
1632/// PrintChildLoopComment - Print comments about child loops within
1633/// the loop for this basic block, with nesting.
1634static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1635 unsigned FunctionNumber) {
1636 // Add child loop information
1637 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1638 OS.indent((*CL)->getLoopDepth()*2)
1639 << "Child Loop BB" << FunctionNumber << "_"
1640 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1641 << '\n';
1642 PrintChildLoopComment(OS, *CL, FunctionNumber);
1643 }
1644}
1645
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001646/// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1647static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1648 const MachineLoopInfo *LI,
1649 const AsmPrinter &AP) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001650 // Add loop depth information
1651 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1652 if (Loop == 0) return;
1653
1654 MachineBasicBlock *Header = Loop->getHeader();
1655 assert(Header && "No header for loop");
1656
1657 // If this block is not a loop header, just print out what is the loop header
1658 // and return.
1659 if (Header != &MBB) {
1660 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1661 Twine(AP.getFunctionNumber())+"_" +
1662 Twine(Loop->getHeader()->getNumber())+
1663 " Depth="+Twine(Loop->getLoopDepth()));
1664 return;
1665 }
1666
1667 // Otherwise, it is a loop header. Print out information about child and
1668 // parent loops.
1669 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1670
1671 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1672
1673 OS << "=>";
1674 OS.indent(Loop->getLoopDepth()*2-2);
1675
1676 OS << "This ";
1677 if (Loop->empty())
1678 OS << "Inner ";
1679 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1680
1681 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1682}
1683
1684
1685/// EmitBasicBlockStart - This method prints the label for the specified
1686/// MachineBasicBlock, an alignment (if present) and a comment describing
1687/// it if appropriate.
1688void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1689 // Emit an alignment directive for this block, if needed.
1690 if (unsigned Align = MBB->getAlignment())
1691 EmitAlignment(Log2_32(Align));
1692
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001693 // If the block has its address taken, emit any labels that were used to
1694 // reference the block. It is possible that there is more than one label
1695 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1696 // the references were generated.
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001697 if (MBB->hasAddressTaken()) {
1698 const BasicBlock *BB = MBB->getBasicBlock();
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001699 if (isVerbose())
1700 OutStreamer.AddComment("Block address taken");
1701
1702 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1703
1704 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1705 OutStreamer.EmitLabel(Syms[i]);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001706 }
1707
1708 // Print the main label for the block.
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001709 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001710 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001711 if (const BasicBlock *BB = MBB->getBasicBlock())
1712 if (BB->hasName())
1713 OutStreamer.AddComment("%" + BB->getName());
1714
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001715 EmitBasicBlockLoopComments(*MBB, LI, *this);
1716
1717 // NOTE: Want this comment at start of line, don't emit with AddComment.
1718 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1719 Twine(MBB->getNumber()) + ":");
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001720 }
1721 } else {
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001722 if (isVerbose()) {
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001723 if (const BasicBlock *BB = MBB->getBasicBlock())
1724 if (BB->hasName())
1725 OutStreamer.AddComment("%" + BB->getName());
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001726 EmitBasicBlockLoopComments(*MBB, LI, *this);
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001727 }
1728
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001729 OutStreamer.EmitLabel(MBB->getSymbol());
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001730 }
1731}
1732
1733void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1734 MCSymbolAttr Attr = MCSA_Invalid;
1735
1736 switch (Visibility) {
1737 default: break;
1738 case GlobalValue::HiddenVisibility:
1739 Attr = MAI->getHiddenVisibilityAttr();
1740 break;
1741 case GlobalValue::ProtectedVisibility:
1742 Attr = MAI->getProtectedVisibilityAttr();
1743 break;
1744 }
1745
1746 if (Attr != MCSA_Invalid)
1747 OutStreamer.EmitSymbolAttribute(Sym, Attr);
1748}
1749
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001750/// isBlockOnlyReachableByFallthough - Return true if the basic block has
1751/// exactly one predecessor and the control transfer mechanism between
1752/// the predecessor and this block is a fall-through.
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001753bool AsmPrinter::
1754isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
Shih-wei Liaoe4454322010-04-07 12:21:42 -07001755 // If this is a landing pad, it isn't a fall through. If it has no preds,
1756 // then nothing falls through to it.
1757 if (MBB->isLandingPad() || MBB->pred_empty())
1758 return false;
1759
1760 // If there isn't exactly one predecessor, it can't be a fall through.
1761 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1762 ++PI2;
1763 if (PI2 != MBB->pred_end())
1764 return false;
1765
1766 // The predecessor has to be immediately before this block.
1767 const MachineBasicBlock *Pred = *PI;
1768
1769 if (!Pred->isLayoutSuccessor(MBB))
1770 return false;
1771
1772 // If the block is completely empty, then it definitely does fall through.
1773 if (Pred->empty())
1774 return true;
1775
1776 // Otherwise, check the last instruction.
1777 const MachineInstr &LastInst = Pred->back();
1778 return !LastInst.getDesc().isBarrier();
1779}
1780
1781
1782
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001783GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1784 if (!S->usesMetadata())
1785 return 0;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001786
1787 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1788 gcp_map_type::iterator GCPI = GCMap.find(S);
1789 if (GCPI != GCMap.end())
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001790 return GCPI->second;
1791
1792 const char *Name = S->getName().c_str();
1793
1794 for (GCMetadataPrinterRegistry::iterator
1795 I = GCMetadataPrinterRegistry::begin(),
1796 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1797 if (strcmp(Name, I->getName()) == 0) {
1798 GCMetadataPrinter *GMP = I->instantiate();
1799 GMP->S = S;
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001800 GCMap.insert(std::make_pair(S, GMP));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001801 return GMP;
1802 }
1803
Shih-wei Liao7abe37e2010-04-28 01:47:00 -07001804 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
Shih-wei Liaoe264f622010-02-10 11:10:31 -08001805 return 0;
1806}
1807