blob: adc64f97d9d30ef2e1c671cd9785b26d2057e7b2 [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
Chris Lattnerd7dede22010-01-28 01:02:27 +000014#define DEBUG_TYPE "asm-printer"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000015#include "llvm/CodeGen/AsmPrinter.h"
Chris Lattnerec9a1f42010-04-05 05:11:15 +000016#include "DwarfDebug.h"
17#include "DwarfException.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018#include "llvm/Module.h"
Gordon Henriksen1aed5992008-08-17 18:44:35 +000019#include "llvm/CodeGen/GCMetadataPrinter.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "llvm/CodeGen/MachineConstantPool.h"
David Greeneca9b04b2009-11-13 21:34:57 +000021#include "llvm/CodeGen/MachineFrameInfo.h"
David Greene066ed6a2009-08-18 19:22:55 +000022#include "llvm/CodeGen/MachineFunction.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/CodeGen/MachineJumpTableInfo.h"
David Greenee52fd872009-08-10 16:38:07 +000024#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner1b989192007-12-31 04:13:23 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Dan Gohman8e0ed342010-02-08 22:02:38 +000026#include "llvm/Analysis/ConstantFolding.h"
Argiris Kirtzidis3f997f82009-05-07 13:55:51 +000027#include "llvm/Analysis/DebugInfo.h"
Chris Lattner599df3c2010-04-04 18:34:07 +000028#include "llvm/MC/MCAsmInfo.h"
Chris Lattner1eb0ad02009-07-27 21:28:04 +000029#include "llvm/MC/MCContext.h"
Chris Lattner54bfda72010-01-23 06:17:14 +000030#include "llvm/MC/MCExpr.h"
David Greene4a37a692009-07-16 22:24:20 +000031#include "llvm/MC/MCInst.h"
Chris Lattnere6ad12f2009-07-31 18:48:30 +000032#include "llvm/MC/MCSection.h"
33#include "llvm/MC/MCStreamer.h"
Chris Lattner08c97082009-09-12 23:02:08 +000034#include "llvm/MC/MCSymbol.h"
Chris Lattner31a54742010-01-16 21:57:06 +000035#include "llvm/Target/Mangler.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/Target/TargetData.h"
David Greeneca9b04b2009-11-13 21:34:57 +000037#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038#include "llvm/Target/TargetLowering.h"
Chris Lattnerc4c40a92009-07-28 03:13:23 +000039#include "llvm/Target/TargetLoweringObjectFile.h"
Evan Cheng0eeed442008-07-01 23:18:29 +000040#include "llvm/Target/TargetOptions.h"
Evan Cheng3c0eda52008-03-15 00:03:38 +000041#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner89b36582008-08-17 07:19:36 +000042#include "llvm/ADT/SmallString.h"
Chris Lattnerd7dede22010-01-28 01:02:27 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd7dede22010-01-28 01:02:27 +000044#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/Format.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046using namespace llvm;
47
Chris Lattnerd7dede22010-01-28 01:02:27 +000048STATISTIC(EmittedInsts, "Number of machine instrs printed");
49
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050char AsmPrinter::ID = 0;
Chris Lattnerf4853452010-03-13 20:55:24 +000051
Chris Lattner761dabb2010-04-04 17:57:56 +000052typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
53static gcp_map_type &getGCMap(void *&P) {
54 if (P == 0)
55 P = new gcp_map_type();
56 return *(gcp_map_type*)P;
57}
58
59
Chris Lattner3eac1ed2010-04-04 08:18:47 +000060AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
Chris Lattner761dabb2010-04-04 17:57:56 +000061 : MachineFunctionPass(&ID),
Chris Lattner017c7f92010-04-04 18:06:11 +000062 TM(tm), MAI(tm.getMCAsmInfo()),
Chris Lattnerf4853452010-03-13 20:55:24 +000063 OutContext(Streamer.getContext()),
64 OutStreamer(Streamer),
Devang Patelabc2b352010-03-29 17:20:31 +000065 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
Chris Lattnerec9a1f42010-04-05 05:11:15 +000066 DD = 0; DE = 0; MMI = 0; LI = 0;
Chris Lattner761dabb2010-04-04 17:57:56 +000067 GCMetadataPrinters = 0;
Chris Lattner8d2970b2010-02-02 23:37:42 +000068 VerboseAsm = Streamer.isVerboseAsm();
Evan Cheng42ceb472009-03-25 01:47:28 +000069}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070
Gordon Henriksen3385c9b2008-08-17 12:08:44 +000071AsmPrinter::~AsmPrinter() {
Chris Lattnerec9a1f42010-04-05 05:11:15 +000072 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
73
Chris Lattner761dabb2010-04-04 17:57:56 +000074 if (GCMetadataPrinters != 0) {
75 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
76
77 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
78 delete I->second;
79 delete &GCMap;
80 GCMetadataPrinters = 0;
81 }
Chris Lattner1eb0ad02009-07-27 21:28:04 +000082
83 delete &OutStreamer;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +000084}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085
Chris Lattner01462ba2010-01-26 04:35:26 +000086/// getFunctionNumber - Return a unique ID for the current function.
87///
88unsigned AsmPrinter::getFunctionNumber() const {
89 return MF->getFunctionNumber();
90}
91
Chris Lattner75bdd292009-08-03 19:12:26 +000092TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Chris Lattnerc4c40a92009-07-28 03:13:23 +000093 return TM.getTargetLowering()->getObjFileLowering();
94}
95
Chris Lattnerbc0027b2010-04-05 00:13:49 +000096
97/// getTargetData - Return information about data layout.
98const TargetData &AsmPrinter::getTargetData() const {
99 return *TM.getTargetData();
100}
101
Chris Lattnerd69d8ad2009-08-18 06:15:16 +0000102/// getCurrentSection() - Return the current section we are emitting to.
103const MCSection *AsmPrinter::getCurrentSection() const {
104 return OutStreamer.getCurrentSection();
105}
106
107
Chris Lattnerbc0027b2010-04-05 00:13:49 +0000108
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000109void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +0000110 AU.setPreservesAll();
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000111 MachineFunctionPass::getAnalysisUsage(AU);
Chris Lattnerf4853452010-03-13 20:55:24 +0000112 AU.addRequired<MachineModuleInfo>();
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000113 AU.addRequired<GCModuleInfo>();
Chris Lattner97c69b72010-04-04 18:52:31 +0000114 if (isVerbose())
David Greenee52fd872009-08-10 16:38:07 +0000115 AU.addRequired<MachineLoopInfo>();
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000116}
117
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118bool AsmPrinter::doInitialization(Module &M) {
Chris Lattner6608f882010-04-04 05:09:10 +0000119 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Chris Lattnerf4853452010-03-13 20:55:24 +0000120 MMI->AnalyzeModule(M);
121
Chris Lattner01316272009-07-31 17:42:42 +0000122 // Initialize TargetLoweringObjectFile.
123 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
124 .Initialize(OutContext, TM);
125
Chris Lattner2a2a6732010-03-12 20:47:28 +0000126 Mang = new Mangler(OutContext, *TM.getTargetData());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127
Bob Wilsonb5f835e2009-09-30 22:06:26 +0000128 // Allow the target to emit any magic that it wants at the start of the file.
129 EmitStartOfAsmFile(M);
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000130
Chris Lattner59be4ea2010-01-25 18:58:59 +0000131 // Very minimal debug info. It is ignored if we emit actual debug info. If we
132 // don't, this at least helps the user find where a global came from.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000133 if (MAI->hasSingleParameterDotFile()) {
Chris Lattner59be4ea2010-01-25 18:58:59 +0000134 // .file "foo.c"
135 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
Rafael Espindola5cf2e552008-12-03 11:01:37 +0000136 }
137
Bob Wilsonb5f835e2009-09-30 22:06:26 +0000138 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
139 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000140 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
141 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Chris Lattner1bf2b282010-04-04 07:39:04 +0000142 MP->beginAssembly(*this);
Chris Lattner11b3d382010-04-03 21:35:55 +0000143
144 // Emit module-level inline asm if it exists.
Chris Lattner02935a52010-04-03 21:13:18 +0000145 if (!M.getModuleInlineAsm().empty()) {
146 OutStreamer.AddComment("Start of file scope inline assembly");
147 OutStreamer.AddBlankLine();
Chris Lattner11b3d382010-04-03 21:35:55 +0000148 EmitInlineAsm(M.getModuleInlineAsm());
Chris Lattner02935a52010-04-03 21:13:18 +0000149 OutStreamer.AddComment("End of file scope inline assembly");
150 OutStreamer.AddBlankLine();
151 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152
Chris Lattnerec9a1f42010-04-05 05:11:15 +0000153 if (MAI->doesSupportDebugInformation())
154 DD = new DwarfDebug(this, &M);
155
156 if (MAI->doesSupportExceptionHandling())
157 DE = new DwarfException(this);
Devang Patel1a454842009-06-19 21:54:26 +0000158
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 return false;
160}
161
Chris Lattner32988552010-01-28 00:05:10 +0000162void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
Chris Lattner3971bfd2010-01-26 23:47:12 +0000163 switch ((GlobalValue::LinkageTypes)Linkage) {
164 case GlobalValue::CommonLinkage:
165 case GlobalValue::LinkOnceAnyLinkage:
166 case GlobalValue::LinkOnceODRLinkage:
167 case GlobalValue::WeakAnyLinkage:
168 case GlobalValue::WeakODRLinkage:
169 case GlobalValue::LinkerPrivateLinkage:
170 if (MAI->getWeakDefDirective() != 0) {
171 // .globl _foo
172 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
173 // .weak_definition _foo
174 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
175 } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
176 // .globl _foo
177 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
178 // FIXME: linkonce should be a section attribute, handled by COFF Section
179 // assignment.
180 // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
Chris Lattnerfa366052010-01-26 23:51:52 +0000181 // .linkonce discard
182 // FIXME: It would be nice to use .linkonce samesize for non-common
183 // globals.
Chris Lattner002afa92010-04-03 22:19:41 +0000184 OutStreamer.EmitRawText(StringRef(LinkOnce));
Chris Lattner3971bfd2010-01-26 23:47:12 +0000185 } else {
186 // .weak _foo
187 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
188 }
189 break;
190 case GlobalValue::DLLExportLinkage:
191 case GlobalValue::AppendingLinkage:
192 // FIXME: appending linkage variables should go into a section of
193 // their name or something. For now, just emit them as external.
194 case GlobalValue::ExternalLinkage:
195 // If external or appending, declare as a global symbol.
196 // .globl _foo
197 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
198 break;
199 case GlobalValue::PrivateLinkage:
200 case GlobalValue::InternalLinkage:
201 break;
202 default:
203 llvm_unreachable("Unknown linkage type!");
204 }
205}
206
207
Chris Lattnerd9609472010-01-19 04:39:15 +0000208/// EmitGlobalVariable - Emit the specified global variable to the .s file.
209void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
210 if (!GV->hasInitializer()) // External globals require no code.
211 return;
212
213 // Check to see if this is a special global used by LLVM, if so, emit it.
214 if (EmitSpecialLLVMGlobal(GV))
215 return;
Chris Lattner410c9472010-01-19 05:38:33 +0000216
Chris Lattner90825792010-03-12 21:09:07 +0000217 MCSymbol *GVSym = Mang->getSymbol(GV);
Chris Lattner32988552010-01-28 00:05:10 +0000218 EmitVisibility(GVSym, GV->getVisibility());
Chris Lattner410c9472010-01-19 05:38:33 +0000219
Chris Lattner9f8ef902010-01-25 18:33:40 +0000220 if (MAI->hasDotTypeDotSizeDirective())
221 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
Chris Lattnerd9609472010-01-19 04:39:15 +0000222
Chris Lattner410c9472010-01-19 05:38:33 +0000223 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
224
225 const TargetData *TD = TM.getTargetData();
226 unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
227 unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
228
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000229 // Handle common and BSS local symbols (.lcomm).
230 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
Chris Lattner410c9472010-01-19 05:38:33 +0000231 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
232
Chris Lattner97c69b72010-04-04 18:52:31 +0000233 if (isVerbose()) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000234 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
235 /*PrintType=*/false, GV->getParent());
236 OutStreamer.GetCommentOS() << '\n';
Chris Lattner410c9472010-01-19 05:38:33 +0000237 }
Chris Lattnerf26c7792010-01-19 06:25:51 +0000238
239 // Handle common symbols.
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000240 if (GVKind.isCommon()) {
241 // .comm _foo, 42, 4
Chris Lattnerecf1cdc2010-01-19 06:01:04 +0000242 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000243 return;
Chris Lattnerfdcdb2c2010-01-19 05:51:42 +0000244 }
Chris Lattnerf26c7792010-01-19 06:25:51 +0000245
246 // Handle local BSS symbols.
247 if (MAI->hasMachoZeroFillDirective()) {
248 const MCSection *TheSection =
249 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
250 // .zerofill __DATA, __bss, _foo, 400, 5
251 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
252 return;
253 }
254
Chris Lattnerd70deeb2010-01-23 07:47:02 +0000255 if (MAI->hasLCOMMDirective()) {
Chris Lattnerf26c7792010-01-19 06:25:51 +0000256 // .lcomm _foo, 42
Chris Lattnerd70deeb2010-01-23 07:47:02 +0000257 OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000258 return;
259 }
260
261 // .local _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000262 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
Chris Lattnerf26c7792010-01-19 06:25:51 +0000263 // .comm _foo, 42, 4
264 OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
Chris Lattner410c9472010-01-19 05:38:33 +0000265 return;
266 }
267
268 const MCSection *TheSection =
269 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
270
271 // Handle the zerofill directive on darwin, which is a special form of BSS
272 // emission.
273 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
274 // .globl _foo
Chris Lattner2d7c8142010-01-23 06:39:22 +0000275 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Chris Lattner410c9472010-01-19 05:38:33 +0000276 // .zerofill __DATA, __common, _foo, 400, 5
277 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
278 return;
279 }
280
281 OutStreamer.SwitchSection(TheSection);
282
Chris Lattner3971bfd2010-01-26 23:47:12 +0000283 EmitLinkage(GV->getLinkage(), GVSym);
Chris Lattner410c9472010-01-19 05:38:33 +0000284 EmitAlignment(AlignLog, GV);
Chris Lattner3971bfd2010-01-26 23:47:12 +0000285
Chris Lattner97c69b72010-04-04 18:52:31 +0000286 if (isVerbose()) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000287 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
288 /*PrintType=*/false, GV->getParent());
289 OutStreamer.GetCommentOS() << '\n';
Chris Lattner410c9472010-01-19 05:38:33 +0000290 }
Chris Lattner8c2d16d2010-01-19 06:41:24 +0000291 OutStreamer.EmitLabel(GVSym);
Chris Lattner410c9472010-01-19 05:38:33 +0000292
293 EmitGlobalConstant(GV->getInitializer());
294
295 if (MAI->hasDotTypeDotSizeDirective())
Chris Lattner53ee5d82010-01-25 07:53:05 +0000296 // .size foo, 42
Chris Lattnere13c8ac2010-01-25 07:52:13 +0000297 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
Chris Lattnerc006e1c2010-01-22 19:52:01 +0000298
299 OutStreamer.AddBlankLine();
Chris Lattnerd9609472010-01-19 04:39:15 +0000300}
301
Chris Lattnere5980672010-01-26 23:18:44 +0000302/// EmitFunctionHeader - This method emits the header for the current
303/// function.
304void AsmPrinter::EmitFunctionHeader() {
305 // Print out constants referenced by the function
Chris Lattner8559cf72010-01-28 00:19:24 +0000306 EmitConstantPool();
Chris Lattnere5980672010-01-26 23:18:44 +0000307
308 // Print the 'header' of function.
Chris Lattnere5980672010-01-26 23:18:44 +0000309 const Function *F = MF->getFunction();
310
311 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
Chris Lattner32988552010-01-28 00:05:10 +0000312 EmitVisibility(CurrentFnSym, F->getVisibility());
Chris Lattnere5980672010-01-26 23:18:44 +0000313
Chris Lattnerfa366052010-01-26 23:51:52 +0000314 EmitLinkage(F->getLinkage(), CurrentFnSym);
Chris Lattner7d7e5112010-01-26 23:41:48 +0000315 EmitAlignment(MF->getAlignment(), F);
316
Chris Lattnere5980672010-01-26 23:18:44 +0000317 if (MAI->hasDotTypeDotSizeDirective())
318 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
319
Chris Lattner97c69b72010-04-04 18:52:31 +0000320 if (isVerbose()) {
Chris Lattnerbfbae452010-01-26 23:53:39 +0000321 WriteAsOperand(OutStreamer.GetCommentOS(), F,
322 /*PrintType=*/false, F->getParent());
323 OutStreamer.GetCommentOS() << '\n';
Chris Lattnere5980672010-01-26 23:18:44 +0000324 }
Chris Lattnere5980672010-01-26 23:18:44 +0000325
Dan Gohmandf1a7ff2010-02-10 16:03:48 +0000326 // Emit the CurrentFnSym. This is a virtual function to allow targets to
Chris Lattneraec7a8a2010-01-27 07:21:55 +0000327 // do their wild and crazy things as required.
328 EmitFunctionEntryLabel();
329
Chris Lattnerf6853ff2010-03-15 20:39:00 +0000330 // If the function had address-taken blocks that got deleted, then we have
331 // references to the dangling symbols. Emit them at the start of the function
332 // so that we don't get references to undefined symbols.
333 std::vector<MCSymbol*> DeadBlockSyms;
334 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
335 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
336 OutStreamer.AddComment("Address taken block that was later removed");
337 OutStreamer.EmitLabel(DeadBlockSyms[i]);
338 }
339
Chris Lattnere5980672010-01-26 23:18:44 +0000340 // Add some workaround for linkonce linkage on Cygwin\MinGW.
341 if (MAI->getLinkOnceDirective() != 0 &&
Chris Lattner002afa92010-04-03 22:19:41 +0000342 (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
Chris Lattnerbfbae452010-01-26 23:53:39 +0000343 // FIXME: What is this?
Chris Lattner002afa92010-04-03 22:19:41 +0000344 MCSymbol *FakeStub =
345 OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
346 CurrentFnSym->getName());
347 OutStreamer.EmitLabel(FakeStub);
348 }
Chris Lattnere5980672010-01-26 23:18:44 +0000349
350 // Emit pre-function debug and/or EH information.
Chris Lattnerec9a1f42010-04-05 05:11:15 +0000351 if (DE) DE->BeginFunction(MF);
352 if (DD) DD->beginFunction(MF);
Chris Lattnere5980672010-01-26 23:18:44 +0000353}
354
Chris Lattneraec7a8a2010-01-27 07:21:55 +0000355/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
356/// function. This can be overridden by targets as required to do custom stuff.
357void AsmPrinter::EmitFunctionEntryLabel() {
358 OutStreamer.EmitLabel(CurrentFnSym);
359}
Chris Lattnere5980672010-01-26 23:18:44 +0000360
Chris Lattnerd9609472010-01-19 04:39:15 +0000361
Chris Lattner18ae8872010-02-10 00:47:53 +0000362/// EmitComments - Pretty-print comments for instructions.
363static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
364 const MachineFunction *MF = MI.getParent()->getParent();
365 const TargetMachine &TM = MF->getTarget();
366
Chris Lattnerb9692a72010-04-02 19:42:39 +0000367 DebugLoc DL = MI.getDebugLoc();
368 if (!DL.isUnknown()) { // Print source line info.
369 DIScope Scope(DL.getScope(MF->getFunction()->getContext()));
Chris Lattner18ae8872010-02-10 00:47:53 +0000370 // Omit the directory, because it's likely to be long and uninteresting.
Devang Patel9e592492010-03-08 20:52:55 +0000371 if (Scope.Verify())
Chris Lattner18ae8872010-02-10 00:47:53 +0000372 CommentOS << Scope.getFilename();
373 else
374 CommentOS << "<unknown>";
Chris Lattnerb9692a72010-04-02 19:42:39 +0000375 CommentOS << ':' << DL.getLine();
376 if (DL.getCol() != 0)
377 CommentOS << ':' << DL.getCol();
Chris Lattner18ae8872010-02-10 00:47:53 +0000378 CommentOS << '\n';
379 }
380
381 // Check for spills and reloads
382 int FI;
383
384 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
385
386 // We assume a single instruction only has a spill or reload, not
387 // both.
388 const MachineMemOperand *MMO;
389 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
390 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
391 MMO = *MI.memoperands_begin();
392 CommentOS << MMO->getSize() << "-byte Reload\n";
393 }
394 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
395 if (FrameInfo->isSpillSlotObjectIndex(FI))
396 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
397 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
398 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
399 MMO = *MI.memoperands_begin();
400 CommentOS << MMO->getSize() << "-byte Spill\n";
401 }
402 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
403 if (FrameInfo->isSpillSlotObjectIndex(FI))
404 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
405 }
406
407 // Check for spill-induced copies
408 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
409 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
410 SrcSubIdx, DstSubIdx)) {
Chris Lattnerf2f451d2010-02-10 01:23:18 +0000411 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
Chris Lattner18ae8872010-02-10 00:47:53 +0000412 CommentOS << " Reload Reuse\n";
413 }
414}
415
Chris Lattnerc143f0a2010-04-04 18:58:53 +0000416/// EmitImplicitDef - This method emits the specified machine instruction
417/// that is an implicit def.
418static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
419 unsigned RegNo = MI->getOperand(0).getReg();
420 AP.OutStreamer.AddComment(Twine("implicit-def: ") +
421 AP.TM.getRegisterInfo()->getName(RegNo));
422 AP.OutStreamer.AddBlankLine();
423}
424
425static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
426 std::string Str = "kill:";
427 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
428 const MachineOperand &Op = MI->getOperand(i);
429 assert(Op.isReg() && "KILL instruction must have only register operands");
430 Str += ' ';
431 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
432 Str += (Op.isDef() ? "<def>" : "<kill>");
433 }
434 AP.OutStreamer.AddComment(Str);
435 AP.OutStreamer.AddBlankLine();
436}
437
Chris Lattner18ae8872010-02-10 00:47:53 +0000438
439
Chris Lattnerd7dede22010-01-28 01:02:27 +0000440/// EmitFunctionBody - This method emits the body and trailer for a
441/// function.
442void AsmPrinter::EmitFunctionBody() {
Chris Lattnerfeb65e42010-01-28 01:58:58 +0000443 // Emit target-specific gunk before the function body.
444 EmitFunctionBodyStart();
445
Chris Lattnerec9a1f42010-04-05 05:11:15 +0000446 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
Chris Lattner435a7332010-04-04 18:18:51 +0000447
Chris Lattnerd7dede22010-01-28 01:02:27 +0000448 // Print out code for the function.
449 bool HasAnyRealCode = false;
450 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
451 I != E; ++I) {
452 // Print a label for the basic block.
453 EmitBasicBlockStart(I);
454 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
455 II != IE; ++II) {
456 // Print the assembly for the instruction.
457 if (!II->isLabel())
458 HasAnyRealCode = true;
459
460 ++EmittedInsts;
461
Chris Lattner435a7332010-04-04 18:18:51 +0000462 if (ShouldPrintDebugScopes)
Chris Lattnerec9a1f42010-04-05 05:11:15 +0000463 DD->beginScope(II);
Chris Lattnerd7dede22010-01-28 01:02:27 +0000464
Chris Lattner97c69b72010-04-04 18:52:31 +0000465 if (isVerbose())
Chris Lattner18ae8872010-02-10 00:47:53 +0000466 EmitComments(*II, OutStreamer.GetCommentOS());
467
Chris Lattnerff259db2010-02-03 01:00:52 +0000468 switch (II->getOpcode()) {
Chris Lattner4052b292010-02-09 19:54:29 +0000469 case TargetOpcode::DBG_LABEL:
470 case TargetOpcode::EH_LABEL:
471 case TargetOpcode::GC_LABEL:
Chris Lattner610fbcb2010-04-04 18:14:01 +0000472 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
Chris Lattnerff259db2010-02-03 01:00:52 +0000473 break;
Chris Lattner4052b292010-02-09 19:54:29 +0000474 case TargetOpcode::INLINEASM:
Chris Lattner610fbcb2010-04-04 18:14:01 +0000475 EmitInlineAsm(II);
Chris Lattnerff259db2010-02-03 01:00:52 +0000476 break;
Chris Lattner4052b292010-02-09 19:54:29 +0000477 case TargetOpcode::IMPLICIT_DEF:
Chris Lattnerc143f0a2010-04-04 18:58:53 +0000478 if (isVerbose()) EmitImplicitDef(II, *this);
Chris Lattnerff259db2010-02-03 01:00:52 +0000479 break;
Chris Lattner4052b292010-02-09 19:54:29 +0000480 case TargetOpcode::KILL:
Chris Lattnerc143f0a2010-04-04 18:58:53 +0000481 if (isVerbose()) EmitKill(II, *this);
Chris Lattnerff259db2010-02-03 01:00:52 +0000482 break;
483 default:
484 EmitInstruction(II);
485 break;
486 }
Chris Lattnerd7dede22010-01-28 01:02:27 +0000487
Chris Lattner435a7332010-04-04 18:18:51 +0000488 if (ShouldPrintDebugScopes)
Chris Lattnerec9a1f42010-04-05 05:11:15 +0000489 DD->endScope(II);
Chris Lattnerd7dede22010-01-28 01:02:27 +0000490 }
491 }
492
493 // If the function is empty and the object file uses .subsections_via_symbols,
Chris Lattner1d40b372010-01-28 01:28:58 +0000494 // then we need to emit *something* to the function body to prevent the
495 // labels from collapsing together. Just emit a 0 byte.
Chris Lattner5ab55982010-01-28 01:06:32 +0000496 if (MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)
497 OutStreamer.EmitIntValue(0, 1, 0/*addrspace*/);
Chris Lattnerd7dede22010-01-28 01:02:27 +0000498
Chris Lattnerfeb65e42010-01-28 01:58:58 +0000499 // Emit target-specific gunk after the function body.
500 EmitFunctionBodyEnd();
501
Chris Lattner002afa92010-04-03 22:19:41 +0000502 // If the target wants a .size directive for the size of the function, emit
503 // it.
504 if (MAI->hasDotTypeDotSizeDirective()) {
Chris Lattner6d718812010-04-03 22:28:33 +0000505 // Create a symbol for the end of function, so we can get the size as
506 // difference between the function label and the temp label.
507 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
508 OutStreamer.EmitLabel(FnEndLabel);
509
510 const MCExpr *SizeExp =
511 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
512 MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
513 OutContext);
514 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
Chris Lattner002afa92010-04-03 22:19:41 +0000515 }
Chris Lattnerd7dede22010-01-28 01:02:27 +0000516
517 // Emit post-function debug information.
Chris Lattnerec9a1f42010-04-05 05:11:15 +0000518 if (DD) DD->endFunction(MF);
519 if (DE) DE->EndFunction();
520 MMI->EndFunction();
Chris Lattnerd7dede22010-01-28 01:02:27 +0000521
522 // Print out jump tables referenced by the function.
523 EmitJumpTableInfo();
Chris Lattner32b33f12010-02-03 01:49:49 +0000524
525 OutStreamer.AddBlankLine();
Chris Lattnerd7dede22010-01-28 01:02:27 +0000526}
527
528
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000529bool AsmPrinter::doFinalization(Module &M) {
Chris Lattnerae982212009-07-21 18:38:57 +0000530 // Emit global variables.
531 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
532 I != E; ++I)
Chris Lattnerd9609472010-01-19 04:39:15 +0000533 EmitGlobalVariable(I);
Chris Lattnerae982212009-07-21 18:38:57 +0000534
Chris Lattnerec9a1f42010-04-05 05:11:15 +0000535 // Finalize debug and EH information.
536 if (DE) {
537 DE->EndModule();
538 delete DE; DE = 0;
539 }
540 if (DD) {
541 DD->endModule();
542 delete DD; DD = 0;
543 }
Chris Lattnere1225cc2009-06-24 18:54:37 +0000544
Chris Lattnerdb191f02009-06-24 18:52:01 +0000545 // If the target wants to know about weak references, print them all.
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000546 if (MAI->getWeakRefDirective()) {
Chris Lattnerdb191f02009-06-24 18:52:01 +0000547 // FIXME: This is not lazy, it would be nice to only print weak references
548 // to stuff that is actually used. Note that doing so would require targets
549 // to notice uses in operands (due to constant exprs etc). This should
550 // happen with the MC stuff eventually.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000551
Chris Lattnerdb191f02009-06-24 18:52:01 +0000552 // Print out module-level global variables here.
553 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
554 I != E; ++I) {
Chris Lattnercbfe4062010-01-16 18:17:26 +0000555 if (!I->hasExternalWeakLinkage()) continue;
Chris Lattner90825792010-03-12 21:09:07 +0000556 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Chris Lattnerdb191f02009-06-24 18:52:01 +0000557 }
558
Chris Lattner0f98c332009-08-03 23:10:34 +0000559 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
Chris Lattnercbfe4062010-01-16 18:17:26 +0000560 if (!I->hasExternalWeakLinkage()) continue;
Chris Lattner90825792010-03-12 21:09:07 +0000561 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
Chris Lattnerdb191f02009-06-24 18:52:01 +0000562 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563 }
564
Chris Lattner5e969572010-01-26 20:40:54 +0000565 if (MAI->hasSetDirective()) {
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000566 OutStreamer.AddBlankLine();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
Chris Lattnerdb191f02009-06-24 18:52:01 +0000568 I != E; ++I) {
Chris Lattner90825792010-03-12 21:09:07 +0000569 MCSymbol *Name = Mang->getSymbol(I);
Anton Korobeynikov6d2c5062007-09-06 17:21:48 +0000570
571 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
Chris Lattner90825792010-03-12 21:09:07 +0000572 MCSymbol *Target = Mang->getSymbol(GV);
Anton Korobeynikovb191f5c2008-09-24 22:21:04 +0000573
Chris Lattnerce409842010-01-17 21:43:43 +0000574 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
Chris Lattner2d7c8142010-01-23 06:39:22 +0000575 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
Chris Lattnerce409842010-01-17 21:43:43 +0000576 else if (I->hasWeakLinkage())
Chris Lattner2d7c8142010-01-23 06:39:22 +0000577 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
Chris Lattnerce409842010-01-17 21:43:43 +0000578 else
Chris Lattner1ff31942010-01-16 01:37:14 +0000579 assert(I->hasLocalLinkage() && "Invalid alias linkage");
Anton Korobeynikova6f01832008-03-11 21:41:14 +0000580
Chris Lattner32988552010-01-28 00:05:10 +0000581 EmitVisibility(Name, I->getVisibility());
Anton Korobeynikova6f01832008-03-11 21:41:14 +0000582
Chris Lattnerca419032010-01-26 21:53:08 +0000583 // Emit the directives as assignments aka .set:
584 OutStreamer.EmitAssignment(Name,
585 MCSymbolRefExpr::Create(Target, OutContext));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 }
587 }
588
Duncan Sands4e0d6a72009-01-28 13:14:17 +0000589 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
Gordon Henriksen1aed5992008-08-17 18:44:35 +0000590 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
591 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
592 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Chris Lattner1bf2b282010-04-04 07:39:04 +0000593 MP->finishAssembly(*this);
Gordon Henriksendf87fdc2008-01-07 01:30:38 +0000594
Dan Gohmana65530a2008-05-05 00:28:39 +0000595 // If we don't have any trampolines, then we don't require stack memory
596 // to be executable. Some targets have a directive to declare this.
Chris Lattnerdb191f02009-06-24 18:52:01 +0000597 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
Dan Gohmana65530a2008-05-05 00:28:39 +0000598 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Chris Lattner2dc6ddd2010-01-23 07:21:06 +0000599 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
600 OutStreamer.SwitchSection(S);
Chris Lattnerb6113072009-09-18 20:17:03 +0000601
602 // Allow the target to emit any magic that it wants at the end of the file,
603 // after everything else has gone out.
604 EmitEndOfAsmFile(M);
605
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 delete Mang; Mang = 0;
Chris Lattnerec9a1f42010-04-05 05:11:15 +0000607 MMI = 0;
Chris Lattner1eb0ad02009-07-27 21:28:04 +0000608
609 OutStreamer.Finish();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610 return false;
611}
612
613void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
Chris Lattner01462ba2010-01-26 04:35:26 +0000614 this->MF = &MF;
Chris Lattnerac5a6ad2010-01-16 01:24:10 +0000615 // Get the function symbol.
Chris Lattner90825792010-03-12 21:09:07 +0000616 CurrentFnSym = Mang->getSymbol(MF.getFunction());
David Greenee52fd872009-08-10 16:38:07 +0000617
Chris Lattner97c69b72010-04-04 18:52:31 +0000618 if (isVerbose())
David Greenee52fd872009-08-10 16:38:07 +0000619 LI = &getAnalysis<MachineLoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620}
621
Evan Cheng68c18682009-03-13 07:51:59 +0000622namespace {
623 // SectionCPs - Keep track the alignment, constpool entries per Section.
624 struct SectionCPs {
Chris Lattnere6ad12f2009-07-31 18:48:30 +0000625 const MCSection *S;
Evan Cheng68c18682009-03-13 07:51:59 +0000626 unsigned Alignment;
627 SmallVector<unsigned, 4> CPEs;
Douglas Gregor8cb41382009-12-19 07:05:23 +0000628 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
Evan Cheng68c18682009-03-13 07:51:59 +0000629 };
630}
631
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632/// EmitConstantPool - Print to the current output stream assembly
633/// representations of the constants in the constant pool MCP. This is
634/// used to print out constants which have been "spilled to memory" by
635/// the code generator.
636///
Chris Lattner8559cf72010-01-28 00:19:24 +0000637void AsmPrinter::EmitConstantPool() {
638 const MachineConstantPool *MCP = MF->getConstantPool();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
640 if (CP.empty()) return;
641
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000642 // Calculate sections for constant pool entries. We collect entries to go into
643 // the same section together to reduce amount of section switch statements.
Evan Cheng68c18682009-03-13 07:51:59 +0000644 SmallVector<SectionCPs, 4> CPSections;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Chris Lattner680c6f62009-07-22 00:28:43 +0000646 const MachineConstantPoolEntry &CPE = CP[i];
Evan Cheng68c18682009-03-13 07:51:59 +0000647 unsigned Align = CPE.getAlignment();
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000648
649 SectionKind Kind;
650 switch (CPE.getRelocationInfo()) {
651 default: llvm_unreachable("Unknown section kind");
Chris Lattnera9453412009-08-01 23:57:16 +0000652 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000653 case 1:
Chris Lattnera9453412009-08-01 23:57:16 +0000654 Kind = SectionKind::getReadOnlyWithRelLocal();
Chris Lattnered0c6762009-07-26 07:00:12 +0000655 break;
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000656 case 0:
Chris Lattnered0c6762009-07-26 07:00:12 +0000657 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
Chris Lattnera9453412009-08-01 23:57:16 +0000658 case 4: Kind = SectionKind::getMergeableConst4(); break;
659 case 8: Kind = SectionKind::getMergeableConst8(); break;
660 case 16: Kind = SectionKind::getMergeableConst16();break;
661 default: Kind = SectionKind::getMergeableConst(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000662 }
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000663 }
664
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000665 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
Chris Lattner680c6f62009-07-22 00:28:43 +0000666
Evan Cheng68c18682009-03-13 07:51:59 +0000667 // The number of sections are small, just do a linear search from the
668 // last section to the first.
669 bool Found = false;
670 unsigned SecIdx = CPSections.size();
671 while (SecIdx != 0) {
672 if (CPSections[--SecIdx].S == S) {
673 Found = true;
674 break;
675 }
676 }
677 if (!Found) {
678 SecIdx = CPSections.size();
679 CPSections.push_back(SectionCPs(S, Align));
680 }
681
682 if (Align > CPSections[SecIdx].Alignment)
683 CPSections[SecIdx].Alignment = Align;
684 CPSections[SecIdx].CPEs.push_back(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685 }
686
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000687 // Now print stuff into the calculated sections.
Evan Cheng68c18682009-03-13 07:51:59 +0000688 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
Chris Lattner73266f92009-08-19 05:49:37 +0000689 OutStreamer.SwitchSection(CPSections[i].S);
Evan Cheng68c18682009-03-13 07:51:59 +0000690 EmitAlignment(Log2_32(CPSections[i].Alignment));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691
Evan Cheng68c18682009-03-13 07:51:59 +0000692 unsigned Offset = 0;
693 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
694 unsigned CPI = CPSections[i].CPEs[j];
695 MachineConstantPoolEntry CPE = CP[CPI];
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000696
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697 // Emit inter-object padding for alignment.
Evan Cheng68c18682009-03-13 07:51:59 +0000698 unsigned AlignMask = CPE.getAlignment() - 1;
699 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
Chris Lattnera71dc602010-01-19 19:46:13 +0000700 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
Evan Cheng68c18682009-03-13 07:51:59 +0000701
702 const Type *Ty = CPE.getType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000703 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
Evan Cheng68c18682009-03-13 07:51:59 +0000704
Chris Lattner77e356c2010-01-23 05:19:23 +0000705 // Emit the label with a comment on it.
Chris Lattner97c69b72010-04-04 18:52:31 +0000706 if (isVerbose()) {
Chris Lattner77e356c2010-01-23 05:19:23 +0000707 OutStreamer.GetCommentOS() << "constant pool ";
708 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
709 MF->getFunction()->getParent());
710 OutStreamer.GetCommentOS() << '\n';
Anton Korobeynikovb866b252008-09-24 22:17:59 +0000711 }
Chris Lattner77e356c2010-01-23 05:19:23 +0000712 OutStreamer.EmitLabel(GetCPISymbol(CPI));
713
Evan Cheng68c18682009-03-13 07:51:59 +0000714 if (CPE.isMachineConstantPoolEntry())
715 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
716 else
717 EmitGlobalConstant(CPE.Val.ConstVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 }
719 }
720}
721
722/// EmitJumpTableInfo - Print assembly representations of the jump tables used
723/// by the current function to the current output stream.
724///
Chris Lattnerd7dede22010-01-28 01:02:27 +0000725void AsmPrinter::EmitJumpTableInfo() {
726 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattner1f8c8922010-01-25 22:41:33 +0000727 if (MJTI == 0) return;
Richard Osborne9f3cfe62010-03-11 14:58:16 +0000728 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
730 if (JT.empty()) return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000731
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 // Pick the directive to use to print the jump table entries, and switch to
733 // the appropriate section.
Chris Lattnerd7dede22010-01-28 01:02:27 +0000734 const Function *F = MF->getFunction();
Evan Chengccca6f72009-06-18 20:37:15 +0000735 bool JTInDiffSection = false;
Chris Lattneraf706422010-01-26 06:53:37 +0000736 if (// In PIC mode, we need to emit the jump table to the same section as the
737 // function body itself, otherwise the label differences won't make sense.
738 // FIXME: Need a better predicate for this: what about custom entries?
739 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
740 // We should also do if the section name is NULL or function is declared
741 // in discardable section
742 // FIXME: this isn't the right predicate, should be based on the MCSection
743 // for the function.
744 F->isWeakForLinker()) {
Chris Lattnerd7dede22010-01-28 01:02:27 +0000745 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 } else {
Chris Lattnerd7f8c0a2009-08-01 23:46:12 +0000747 // Otherwise, drop it in the readonly section.
748 const MCSection *ReadOnlySection =
Chris Lattnera9453412009-08-01 23:57:16 +0000749 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
Chris Lattner73266f92009-08-19 05:49:37 +0000750 OutStreamer.SwitchSection(ReadOnlySection);
Evan Chengccca6f72009-06-18 20:37:15 +0000751 JTInDiffSection = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 }
Chris Lattner1d196bc2010-01-25 23:26:13 +0000753
Chris Lattner1d196bc2010-01-25 23:26:13 +0000754 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755
Chris Lattnerc077d722010-01-26 06:42:44 +0000756 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
757 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758
759 // If this jump table was deleted, ignore it.
760 if (JTBBs.empty()) continue;
761
Chris Lattnerb494ccd2010-01-26 05:15:20 +0000762 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
763 // .set directive for each unique entry. This reduces the number of
764 // relocations the assembler will generate for the jump table.
765 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
Chris Lattner5e969572010-01-26 20:40:54 +0000766 MAI->hasSetDirective()) {
Chris Lattnerc077d722010-01-26 06:42:44 +0000767 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
768 const TargetLowering *TLI = TM.getTargetLowering();
Chris Lattnerd7dede22010-01-28 01:02:27 +0000769 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
Chris Lattnerc077d722010-01-26 06:42:44 +0000770 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
771 const MachineBasicBlock *MBB = JTBBs[ii];
772 if (!EmittedSets.insert(MBB)) continue;
773
Chris Lattnerca419032010-01-26 21:53:08 +0000774 // .set LJTSet, LBB32-base
775 const MCExpr *LHS =
Chris Lattnerd13daf82010-03-13 21:04:28 +0000776 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattnerca419032010-01-26 21:53:08 +0000777 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
778 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
Chris Lattnerc077d722010-01-26 06:42:44 +0000779 }
780 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781
Chris Lattner149495f2009-09-13 19:02:16 +0000782 // On some targets (e.g. Darwin) we want to emit two consequtive labels
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 // before each jump table. The first label is never referenced, but tells
784 // the assembler and linker the extents of the jump table object. The
785 // second label is actually referenced by the code.
Chris Lattner77e356c2010-01-23 05:19:23 +0000786 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
Chris Lattner978b9772010-01-26 05:58:28 +0000787 // FIXME: This doesn't have to have any specific name, just any randomly
788 // named and numbered 'l' label would work. Simplify GetJTISymbol.
Chris Lattnerc077d722010-01-26 06:42:44 +0000789 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
Chris Lattner77e356c2010-01-23 05:19:23 +0000790
Chris Lattnerc077d722010-01-26 06:42:44 +0000791 OutStreamer.EmitLabel(GetJTISymbol(JTI));
Chris Lattner77e356c2010-01-23 05:19:23 +0000792
Chris Lattner3d680c02010-01-26 05:10:10 +0000793 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Chris Lattnerc077d722010-01-26 06:42:44 +0000794 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 }
796}
797
Chris Lattner3d680c02010-01-26 05:10:10 +0000798/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
799/// current stream.
800void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
801 const MachineBasicBlock *MBB,
802 unsigned UID) const {
Chris Lattner06b01dd2010-01-26 03:43:22 +0000803 const MCExpr *Value = 0;
804 switch (MJTI->getEntryKind()) {
Richard Osborne9f3cfe62010-03-11 14:58:16 +0000805 case MachineJumpTableInfo::EK_Inline:
806 llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
Chris Lattner8ef60fc2010-01-26 04:05:28 +0000807 case MachineJumpTableInfo::EK_Custom32:
Chris Lattner3d680c02010-01-26 05:10:10 +0000808 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
Chris Lattner8ef60fc2010-01-26 04:05:28 +0000809 OutContext);
810 break;
Chris Lattner06b01dd2010-01-26 03:43:22 +0000811 case MachineJumpTableInfo::EK_BlockAddress:
812 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
813 // .word LBB123
Chris Lattnerd13daf82010-03-13 21:04:28 +0000814 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattner06b01dd2010-01-26 03:43:22 +0000815 break;
Chris Lattner06b01dd2010-01-26 03:43:22 +0000816 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
817 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
818 // with a relocation as gp-relative, e.g.:
819 // .gprel32 LBB123
Chris Lattnerd13daf82010-03-13 21:04:28 +0000820 MCSymbol *MBBSym = MBB->getSymbol();
Chris Lattner3dac3412010-01-25 21:28:50 +0000821 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
Chris Lattner48b139f2010-01-25 21:10:10 +0000822 return;
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000823 }
Chris Lattner8ef60fc2010-01-26 04:05:28 +0000824
Chris Lattner06b01dd2010-01-26 03:43:22 +0000825 case MachineJumpTableInfo::EK_LabelDifference32: {
826 // EK_LabelDifference32 - Each entry is the address of the block minus
827 // the address of the jump table. This is used for PIC jump tables where
828 // gprel32 is not supported. e.g.:
829 // .word LBB123 - LJTI1_2
830 // If the .set directive is supported, this is emitted as:
831 // .set L4_5_set_123, LBB123 - LJTI1_2
832 // .word L4_5_set_123
833
834 // If we have emitted set directives for the jump table entries, print
835 // them rather than the entries themselves. If we're emitting PIC, then
836 // emit the table entries as differences between two text section labels.
Chris Lattner5e969572010-01-26 20:40:54 +0000837 if (MAI->hasSetDirective()) {
Chris Lattner06b01dd2010-01-26 03:43:22 +0000838 // If we used .set, reference the .set's symbol.
Chris Lattner3d680c02010-01-26 05:10:10 +0000839 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
Chris Lattner06b01dd2010-01-26 03:43:22 +0000840 OutContext);
841 break;
842 }
Chris Lattner7eba6722010-01-25 21:22:22 +0000843 // Otherwise, use the difference as the jump table entry.
Chris Lattnerd13daf82010-03-13 21:04:28 +0000844 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattner3d680c02010-01-26 05:10:10 +0000845 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
Chris Lattner06b01dd2010-01-26 03:43:22 +0000846 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
847 break;
848 }
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000849 }
Chris Lattner7eba6722010-01-25 21:22:22 +0000850
Chris Lattner06b01dd2010-01-26 03:43:22 +0000851 assert(Value && "Unknown entry kind!");
852
Chris Lattner1d196bc2010-01-25 23:26:13 +0000853 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
Chris Lattner06b01dd2010-01-26 03:43:22 +0000854 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
Anton Korobeynikov5772c672007-11-14 09:18:41 +0000855}
856
857
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
859/// special global used by LLVM. If so, emit it and return true, otherwise
860/// do nothing and return false.
861bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Daniel Dunbare03513b2009-07-25 23:55:21 +0000862 if (GV->getName() == "llvm.used") {
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000863 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
Andrew Lenharth61d35f52007-08-22 19:33:11 +0000864 EmitLLVMUsedList(GV->getInitializer());
865 return true;
866 }
867
Chris Lattner1e0e0d12009-07-20 06:14:25 +0000868 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
Chris Lattner68433442009-04-13 05:44:34 +0000869 if (GV->getSection() == "llvm.metadata" ||
870 GV->hasAvailableExternallyLinkage())
871 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872
873 if (!GV->hasAppendingLinkage()) return false;
874
875 assert(GV->hasInitializer() && "Not a special LLVM global!");
876
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 const TargetData *TD = TM.getTargetData();
878 unsigned Align = Log2_32(TD->getPointerPrefAlignment());
Chris Lattner0c433e92009-03-09 05:52:15 +0000879 if (GV->getName() == "llvm.global_ctors") {
Chris Lattner73266f92009-08-19 05:49:37 +0000880 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
Chris Lattner1e0e4892009-03-09 08:18:48 +0000881 EmitAlignment(Align, 0);
882 EmitXXStructorList(GV->getInitializer());
Chris Lattner2f2fe052010-01-19 04:34:02 +0000883
884 if (TM.getRelocationModel() == Reloc::Static &&
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000885 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
886 StringRef Sym(".constructors_used");
887 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
Chris Lattner2d7c8142010-01-23 06:39:22 +0000888 MCSA_Reference);
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000889 }
Chris Lattner1e0e4892009-03-09 08:18:48 +0000890 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 }
892
Chris Lattner0c433e92009-03-09 05:52:15 +0000893 if (GV->getName() == "llvm.global_dtors") {
Chris Lattner73266f92009-08-19 05:49:37 +0000894 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
Chris Lattner1e0e4892009-03-09 08:18:48 +0000895 EmitAlignment(Align, 0);
896 EmitXXStructorList(GV->getInitializer());
Chris Lattner2f2fe052010-01-19 04:34:02 +0000897
898 if (TM.getRelocationModel() == Reloc::Static &&
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000899 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
900 StringRef Sym(".destructors_used");
901 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
Chris Lattner2d7c8142010-01-23 06:39:22 +0000902 MCSA_Reference);
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000903 }
Chris Lattner1e0e4892009-03-09 08:18:48 +0000904 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 }
906
907 return false;
908}
909
Chris Lattnera5ef4d32009-08-22 21:43:10 +0000910/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
Dale Johannesen60567622008-09-09 22:29:13 +0000911/// global in the specified llvm.used list for which emitUsedDirectiveFor
912/// is true, as being used with this directive.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913void AsmPrinter::EmitLLVMUsedList(Constant *List) {
Dan Gohman9e1657f2009-06-14 23:30:43 +0000914 // Should be an array of 'i8*'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 ConstantArray *InitList = dyn_cast<ConstantArray>(List);
916 if (InitList == 0) return;
917
918 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner3f621b32009-07-17 22:00:23 +0000919 const GlobalValue *GV =
920 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
Chris Lattnerd7b6c9c2010-01-23 05:51:36 +0000921 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
Chris Lattner90825792010-03-12 21:09:07 +0000922 OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 }
924}
925
926/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the
927/// function pointers, ignoring the init priority.
928void AsmPrinter::EmitXXStructorList(Constant *List) {
929 // Should be an array of '{ int, void ()* }' structs. The first value is the
930 // init priority, which we ignore.
931 if (!isa<ConstantArray>(List)) return;
932 ConstantArray *InitList = cast<ConstantArray>(List);
933 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
934 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
935 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
936
937 if (CS->getOperand(1)->isNullValue())
938 return; // Found a null terminator, exit printing.
939 // Emit the function pointer.
940 EmitGlobalConstant(CS->getOperand(1));
941 }
942}
943
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944//===--------------------------------------------------------------------===//
945// Emission and print routines
946//
947
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948/// EmitInt8 - Emit a byte directive and value.
949///
950void AsmPrinter::EmitInt8(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000951 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952}
953
954/// EmitInt16 - Emit a short directive and value.
955///
956void AsmPrinter::EmitInt16(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000957 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958}
959
960/// EmitInt32 - Emit a long directive and value.
961///
962void AsmPrinter::EmitInt32(int Value) const {
Chris Lattnera39bf4e2010-01-20 06:45:39 +0000963 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964}
965
Chris Lattnerd317fef2010-03-08 23:58:37 +0000966/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
967/// in bytes of the directive is specified by Size and Hi/Lo specify the
968/// labels. This implicitly uses .set if it is available.
969void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
970 unsigned Size) const {
971 // Get the Hi-Lo expression.
972 const MCExpr *Diff =
973 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
974 MCSymbolRefExpr::Create(Lo, OutContext),
975 OutContext);
976
977 if (!MAI->hasSetDirective()) {
978 OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
979 return;
980 }
981
982 // Otherwise, emit with .set (aka assignment).
Chris Lattnerb93558d2010-04-04 19:25:43 +0000983 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
Chris Lattnerd317fef2010-03-08 23:58:37 +0000984 OutStreamer.EmitAssignment(SetLabel, Diff);
Chris Lattner2ab0c442010-03-09 00:39:24 +0000985 OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
Chris Lattnerd317fef2010-03-08 23:58:37 +0000986}
987
988
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989//===----------------------------------------------------------------------===//
990
991// EmitAlignment - Emit an alignment directive to the specified power of
992// two boundary. For example, if you pass in 3 here, you will get an 8
993// byte alignment. If a global value is specified, and if that global has
994// an explicit alignment requested, it will unconditionally override the
995// alignment request. However, if ForcedAlignBits is specified, this value
996// has final say: the ultimate alignment will be the max of ForcedAlignBits
997// and the alignment computed with NumBits and the global.
998//
999// The algorithm is:
1000// Align = NumBits;
1001// if (GV && GV->hasalignment) Align = GV->getalignment();
1002// Align = std::max(Align, ForcedAlignBits);
1003//
1004void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
Evan Cheng7e7d1942008-02-29 19:36:59 +00001005 unsigned ForcedAlignBits,
1006 bool UseFillExpr) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007 if (GV && GV->getAlignment())
1008 NumBits = Log2_32(GV->getAlignment());
1009 NumBits = std::max(NumBits, ForcedAlignBits);
1010
1011 if (NumBits == 0) return; // No need to emit alignment.
Chris Lattner4891d142009-08-19 06:12:02 +00001012
Chris Lattnerd69d8ad2009-08-18 06:15:16 +00001013 if (getCurrentSection()->getKind().isText())
Chris Lattnera6e2dad2010-02-23 18:46:22 +00001014 OutStreamer.EmitCodeAlignment(1 << NumBits);
1015 else
1016 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001017}
David Greenecdc2de32009-08-05 21:00:52 +00001018
Chris Lattner54bfda72010-01-23 06:17:14 +00001019/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1020///
1021static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1022 MCContext &Ctx = AP.OutContext;
1023
1024 if (CV->isNullValue() || isa<UndefValue>(CV))
1025 return MCConstantExpr::Create(0, Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +00001026
Chris Lattner54bfda72010-01-23 06:17:14 +00001027 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1028 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +00001029
Chris Lattner54bfda72010-01-23 06:17:14 +00001030 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Chris Lattner90825792010-03-12 21:09:07 +00001031 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
Chris Lattner54bfda72010-01-23 06:17:14 +00001032 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1033 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +00001034
1035 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1036 if (CE == 0) {
Chris Lattner54bfda72010-01-23 06:17:14 +00001037 llvm_unreachable("Unknown constant value to lower!");
1038 return MCConstantExpr::Create(0, Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +00001039 }
1040
1041 switch (CE->getOpcode()) {
Dan Gohman8e0ed342010-02-08 22:02:38 +00001042 default:
1043 // If the code isn't optimized, there may be outstanding folding
1044 // opportunities. Attempt to fold the expression using TargetData as a
1045 // last resort before giving up.
Dan Gohman933f1932010-02-08 22:19:11 +00001046 if (Constant *C =
1047 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1048 if (C != CE)
1049 return LowerConstant(C, AP);
Dan Gohman8e0ed342010-02-08 22:02:38 +00001050#ifndef NDEBUG
1051 CE->dump();
1052#endif
1053 llvm_unreachable("FIXME: Don't support this constant expr");
Chris Lattner458c8772010-01-13 04:29:19 +00001054 case Instruction::GetElementPtr: {
Chris Lattner54bfda72010-01-23 06:17:14 +00001055 const TargetData &TD = *AP.TM.getTargetData();
1056 // Generate a symbolic expression for the byte address
1057 const Constant *PtrVal = CE->getOperand(0);
1058 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1059 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1060 IdxVec.size());
1061
1062 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
Chris Lattner458c8772010-01-13 04:29:19 +00001063 if (Offset == 0)
Chris Lattner54bfda72010-01-23 06:17:14 +00001064 return Base;
Chris Lattner458c8772010-01-13 04:29:19 +00001065
1066 // Truncate/sext the offset to the pointer size.
Chris Lattner54bfda72010-01-23 06:17:14 +00001067 if (TD.getPointerSizeInBits() != 64) {
1068 int SExtAmount = 64-TD.getPointerSizeInBits();
Chris Lattner458c8772010-01-13 04:29:19 +00001069 Offset = (Offset << SExtAmount) >> SExtAmount;
1070 }
1071
Chris Lattner54bfda72010-01-23 06:17:14 +00001072 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1073 Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +00001074 }
1075
1076 case Instruction::Trunc:
1077 // We emit the value and depend on the assembler to truncate the generated
1078 // expression properly. This is important for differences between
1079 // blockaddress labels. Since the two labels are in the same function, it
1080 // is reasonable to treat their delta as a 32-bit value.
Chris Lattner54bfda72010-01-23 06:17:14 +00001081 // FALL THROUGH.
1082 case Instruction::BitCast:
1083 return LowerConstant(CE->getOperand(0), AP);
1084
1085 case Instruction::IntToPtr: {
1086 const TargetData &TD = *AP.TM.getTargetData();
1087 // Handle casts to pointers by changing them into casts to the appropriate
1088 // integer type. This promotes constant folding and simplifies this code.
1089 Constant *Op = CE->getOperand(0);
1090 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1091 false/*ZExt*/);
1092 return LowerConstant(Op, AP);
1093 }
1094
1095 case Instruction::PtrToInt: {
1096 const TargetData &TD = *AP.TM.getTargetData();
1097 // Support only foldable casts to/from pointers that can be eliminated by
1098 // changing the pointer to the appropriately sized integer type.
1099 Constant *Op = CE->getOperand(0);
1100 const Type *Ty = CE->getType();
1101
1102 const MCExpr *OpExpr = LowerConstant(Op, AP);
1103
1104 // We can emit the pointer value into this slot if the slot is an
1105 // integer slot equal to the size of the pointer.
1106 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1107 return OpExpr;
1108
1109 // Otherwise the pointer is smaller than the resultant integer, mask off
1110 // the high bits so we are sure to get a proper truncation if the input is
1111 // a constant expr.
1112 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1113 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1114 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1115 }
Chris Lattner458c8772010-01-13 04:29:19 +00001116
Dan Gohman69003fc2010-02-09 00:02:37 +00001117 // The MC library also has a right-shift operator, but it isn't consistently
1118 // signed or unsigned between different targets.
Chris Lattner458c8772010-01-13 04:29:19 +00001119 case Instruction::Add:
1120 case Instruction::Sub:
Dan Gohman69003fc2010-02-09 00:02:37 +00001121 case Instruction::Mul:
1122 case Instruction::SDiv:
1123 case Instruction::SRem:
1124 case Instruction::Shl:
Chris Lattner458c8772010-01-13 04:29:19 +00001125 case Instruction::And:
1126 case Instruction::Or:
Chris Lattner54bfda72010-01-23 06:17:14 +00001127 case Instruction::Xor: {
1128 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1129 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
Chris Lattner458c8772010-01-13 04:29:19 +00001130 switch (CE->getOpcode()) {
Chris Lattner54bfda72010-01-23 06:17:14 +00001131 default: llvm_unreachable("Unknown binary operator constant cast expr");
1132 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1133 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
Dan Gohman69003fc2010-02-09 00:02:37 +00001134 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1135 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1136 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1137 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
Chris Lattner54bfda72010-01-23 06:17:14 +00001138 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1139 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1140 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
Chris Lattner458c8772010-01-13 04:29:19 +00001141 }
Chris Lattner54bfda72010-01-23 06:17:14 +00001142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 }
1144}
1145
Chris Lattnere72333d2010-01-19 19:10:44 +00001146static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1147 AsmPrinter &AP) {
Chris Lattnera68112c2010-01-23 04:54:10 +00001148 if (AddrSpace != 0 || !CA->isString()) {
1149 // Not a string. Print the values in successive locations
Chris Lattnere72333d2010-01-19 19:10:44 +00001150 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1151 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
Chris Lattnera68112c2010-01-23 04:54:10 +00001152 return;
Dan Gohmane78b0c72008-12-22 21:14:27 +00001153 }
Chris Lattnera68112c2010-01-23 04:54:10 +00001154
1155 // Otherwise, it can be emitted as .ascii.
1156 SmallVector<char, 128> TmpVec;
1157 TmpVec.reserve(CA->getNumOperands());
1158 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1159 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1160
1161 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001162}
1163
Chris Lattnere72333d2010-01-19 19:10:44 +00001164static void EmitGlobalConstantVector(const ConstantVector *CV,
1165 unsigned AddrSpace, AsmPrinter &AP) {
Chris Lattnerd3544672010-01-20 07:41:15 +00001166 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Chris Lattnere72333d2010-01-19 19:10:44 +00001167 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001168}
1169
Chris Lattnere72333d2010-01-19 19:10:44 +00001170static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1171 unsigned AddrSpace, AsmPrinter &AP) {
Dan Gohmane78b0c72008-12-22 21:14:27 +00001172 // Print the fields in successive locations. Pad to align if needed!
Chris Lattnere72333d2010-01-19 19:10:44 +00001173 const TargetData *TD = AP.TM.getTargetData();
1174 unsigned Size = TD->getTypeAllocSize(CS->getType());
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001175 const StructLayout *Layout = TD->getStructLayout(CS->getType());
Chris Lattnere72333d2010-01-19 19:10:44 +00001176 uint64_t SizeSoFar = 0;
1177 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattnerd3544672010-01-20 07:41:15 +00001178 const Constant *Field = CS->getOperand(i);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001179
1180 // Check if padding is needed and insert one or more 0s.
Chris Lattnerd3544672010-01-20 07:41:15 +00001181 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001182 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1183 - Layout->getElementOffset(i)) - FieldSize;
1184 SizeSoFar += FieldSize + PadSize;
Dan Gohmane78b0c72008-12-22 21:14:27 +00001185
1186 // Now print the actual field value.
Chris Lattnerd3544672010-01-20 07:41:15 +00001187 AP.EmitGlobalConstant(Field, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001188
1189 // Insert padding - this may include padding to increase the size of the
1190 // current field up to the ABI size (if the struct is not packed) as well
1191 // as padding to ensure that the next field starts at the right offset.
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001192 AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001193 }
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001194 assert(SizeSoFar == Layout->getSizeInBytes() &&
Dan Gohmane78b0c72008-12-22 21:14:27 +00001195 "Layout of constant struct may be incorrect!");
1196}
1197
Chris Lattner535969b2010-03-16 21:25:55 +00001198static void EmitGlobalConstantUnion(const ConstantUnion *CU,
1199 unsigned AddrSpace, AsmPrinter &AP) {
1200 const TargetData *TD = AP.TM.getTargetData();
1201 unsigned Size = TD->getTypeAllocSize(CU->getType());
1202
1203 const Constant *Contents = CU->getOperand(0);
1204 unsigned FilledSize = TD->getTypeAllocSize(Contents->getType());
1205
1206 // Print the actually filled part
1207 AP.EmitGlobalConstant(Contents, AddrSpace);
1208
1209 // And pad with enough zeroes
1210 AP.OutStreamer.EmitZeros(Size-FilledSize, AddrSpace);
1211}
1212
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001213static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1214 AsmPrinter &AP) {
Dan Gohmane78b0c72008-12-22 21:14:27 +00001215 // FP Constants are printed as integer constants to avoid losing
Chris Lattner41fd4b12010-01-20 06:53:37 +00001216 // precision.
Chris Lattner82cdc062009-10-05 05:54:46 +00001217 if (CFP->getType()->isDoubleTy()) {
Chris Lattner97c69b72010-04-04 18:52:31 +00001218 if (AP.isVerbose()) {
Chris Lattner49d74392010-01-22 19:17:48 +00001219 double Val = CFP->getValueAPF().convertToDouble();
1220 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
Chris Lattner4e789282010-01-19 22:16:33 +00001221 }
1222
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001223 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1224 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001225 return;
Chris Lattner82cdc062009-10-05 05:54:46 +00001226 }
1227
1228 if (CFP->getType()->isFloatTy()) {
Chris Lattner97c69b72010-04-04 18:52:31 +00001229 if (AP.isVerbose()) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001230 float Val = CFP->getValueAPF().convertToFloat();
1231 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
Dan Gohman87581eb2009-08-12 18:32:22 +00001232 }
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001233 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1234 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001235 return;
Chris Lattner82cdc062009-10-05 05:54:46 +00001236 }
1237
1238 if (CFP->getType()->isX86_FP80Ty()) {
Dan Gohmane78b0c72008-12-22 21:14:27 +00001239 // all long double variants are printed as hex
1240 // api needed to prevent premature destruction
Chris Lattner4e789282010-01-19 22:16:33 +00001241 APInt API = CFP->getValueAPF().bitcastToAPInt();
1242 const uint64_t *p = API.getRawData();
Chris Lattner97c69b72010-04-04 18:52:31 +00001243 if (AP.isVerbose()) {
Chris Lattner84382d22010-01-19 22:11:05 +00001244 // Convert to double so we can print the approximate val as a comment.
1245 APFloat DoubleVal = CFP->getValueAPF();
1246 bool ignored;
1247 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1248 &ignored);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001249 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1250 << DoubleVal.convertToDouble() << '\n';
Chris Lattner84382d22010-01-19 22:11:05 +00001251 }
1252
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001253 if (AP.TM.getTargetData()->isBigEndian()) {
1254 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1255 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
Chris Lattner84382d22010-01-19 22:11:05 +00001256 } else {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001257 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1258 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001259 }
Chris Lattner41fd4b12010-01-20 06:53:37 +00001260
1261 // Emit the tail padding for the long double.
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001262 const TargetData &TD = *AP.TM.getTargetData();
1263 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1264 TD.getTypeStoreSize(CFP->getType()), AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001265 return;
Chris Lattner82cdc062009-10-05 05:54:46 +00001266 }
1267
Chris Lattner4e789282010-01-19 22:16:33 +00001268 assert(CFP->getType()->isPPC_FP128Ty() &&
1269 "Floating point constant type not handled");
1270 // All long double variants are printed as hex api needed to prevent
1271 // premature destruction.
1272 APInt API = CFP->getValueAPF().bitcastToAPInt();
1273 const uint64_t *p = API.getRawData();
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001274 if (AP.TM.getTargetData()->isBigEndian()) {
1275 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1276 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
Chris Lattner41fd4b12010-01-20 06:53:37 +00001277 } else {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001278 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1279 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
Chris Lattner4e789282010-01-19 22:16:33 +00001280 }
Dan Gohmane78b0c72008-12-22 21:14:27 +00001281}
1282
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001283static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1284 unsigned AddrSpace, AsmPrinter &AP) {
1285 const TargetData *TD = AP.TM.getTargetData();
Dan Gohmane78b0c72008-12-22 21:14:27 +00001286 unsigned BitWidth = CI->getBitWidth();
Chris Lattner50340312010-01-13 04:39:46 +00001287 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
Dan Gohmane78b0c72008-12-22 21:14:27 +00001288
1289 // We don't expect assemblers to support integer data directives
1290 // for more than 64 bits, so we emit the data in at most 64-bit
1291 // quantities at a time.
1292 const uint64_t *RawData = CI->getValue().getRawData();
1293 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001294 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1295 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
Dan Gohmane78b0c72008-12-22 21:14:27 +00001296 }
1297}
1298
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Sanjiv Guptadc2943d2009-01-30 04:25:10 +00001300void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
Chris Lattnere795ca52010-01-20 07:19:19 +00001301 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001302 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
Bill Wendling380d4a22010-02-05 00:17:02 +00001303 if (Size == 0) Size = 1; // An empty "_foo:" followed by a section is undef.
Chris Lattner030176b2010-01-19 21:51:22 +00001304 return OutStreamer.EmitZeros(Size, AddrSpace);
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001305 }
1306
1307 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1308 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1309 switch (Size) {
1310 case 1:
1311 case 2:
1312 case 4:
1313 case 8:
Chris Lattner97c69b72010-04-04 18:52:31 +00001314 if (isVerbose())
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001315 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001316 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1317 return;
1318 default:
1319 EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1320 return;
1321 }
1322 }
Chris Lattner9d767d82010-01-13 04:34:19 +00001323
Chris Lattnere72333d2010-01-19 19:10:44 +00001324 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1325 return EmitGlobalConstantArray(CVA, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001326
Chris Lattnere72333d2010-01-19 19:10:44 +00001327 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1328 return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
Chris Lattner9d767d82010-01-13 04:34:19 +00001329
Chris Lattnere72333d2010-01-19 19:10:44 +00001330 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Chris Lattnerf2fc2762010-01-20 07:11:32 +00001331 return EmitGlobalConstantFP(CFP, AddrSpace, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332
Chris Lattner4fb5a132010-01-20 17:57:50 +00001333 if (isa<ConstantPointerNull>(CV)) {
1334 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1335 OutStreamer.EmitIntValue(0, Size, AddrSpace);
1336 return;
1337 }
1338
Chris Lattner535969b2010-03-16 21:25:55 +00001339 if (const ConstantUnion *CVU = dyn_cast<ConstantUnion>(CV))
1340 return EmitGlobalConstantUnion(CVU, AddrSpace, *this);
1341
1342 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1343 return EmitGlobalConstantVector(V, AddrSpace, *this);
1344
Chris Lattner54bfda72010-01-23 06:17:14 +00001345 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1346 // thread the streamer with EmitValue.
1347 OutStreamer.EmitValue(LowerConstant(CV, *this),
1348 TM.getTargetData()->getTypeAllocSize(CV->getType()),
1349 AddrSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350}
1351
Chris Lattner89b36582008-08-17 07:19:36 +00001352void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 // Target doesn't support this yet!
Edwin Törökbd448e32009-07-14 16:55:14 +00001354 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355}
1356
Chris Lattner49318552010-04-04 18:16:38 +00001357void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1358 if (Offset > 0)
1359 OS << '+' << Offset;
1360 else if (Offset < 0)
1361 OS << Offset;
1362}
1363
Chris Lattnerb93558d2010-04-04 19:25:43 +00001364//===----------------------------------------------------------------------===//
1365// Symbol Lowering Routines.
1366//===----------------------------------------------------------------------===//
1367
1368/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1369/// temporary label with the specified stem and unique ID.
1370MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
Chris Lattner66f71702010-04-04 19:28:59 +00001371 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
Chris Lattnerb93558d2010-04-04 19:25:43 +00001372 Name + Twine(ID));
1373}
1374
1375/// GetTempSymbol - Return an assembler temporary label with the specified
1376/// stem.
1377MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1378 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1379 Name);
1380}
1381
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382
Chris Lattner32748822010-02-08 23:10:08 +00001383MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
Chris Lattner44894142010-03-14 17:53:23 +00001384 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
Dan Gohman91057512009-10-30 01:27:03 +00001385}
1386
Chris Lattner44894142010-03-14 17:53:23 +00001387MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1388 return MMI->getAddrLabelSymbol(BB);
Dan Gohman91057512009-10-30 01:27:03 +00001389}
1390
Chris Lattner77e356c2010-01-23 05:19:23 +00001391/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1392MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
Chris Lattner3b197832010-03-30 18:10:53 +00001393 return OutContext.GetOrCreateSymbol
Chris Lattner72121e42010-03-10 02:25:11 +00001394 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1395 + "_" + Twine(CPID));
Chris Lattner77e356c2010-01-23 05:19:23 +00001396}
1397
1398/// GetJTISymbol - Return the symbol for the specified jump table entry.
1399MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
Chris Lattner541d8902010-01-26 06:28:43 +00001400 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
Chris Lattner08c97082009-09-12 23:02:08 +00001401}
1402
Chris Lattnerda1416d2010-01-25 21:17:10 +00001403/// GetJTSetSymbol - Return the symbol for the specified jump table .set
1404/// FIXME: privatize to AsmPrinter.
1405MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
Chris Lattner3b197832010-03-30 18:10:53 +00001406 return OutContext.GetOrCreateSymbol
Chris Lattner72121e42010-03-10 02:25:11 +00001407 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1408 Twine(UID) + "_set_" + Twine(MBBID));
Chris Lattnerda1416d2010-01-25 21:17:10 +00001409}
1410
Chris Lattnera6f2a102010-01-16 18:37:32 +00001411/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
Chris Lattnerf7871d12010-01-15 23:25:11 +00001412/// global value name as its base, with the specified suffix, and where the
Chris Lattnera6f2a102010-01-16 18:37:32 +00001413/// symbol is forced to have private linkage if ForcePrivate is true.
1414MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1415 StringRef Suffix,
1416 bool ForcePrivate) const {
Chris Lattnerf7871d12010-01-15 23:25:11 +00001417 SmallString<60> NameStr;
Chris Lattnera6f2a102010-01-16 18:37:32 +00001418 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
Chris Lattnerf7871d12010-01-15 23:25:11 +00001419 NameStr.append(Suffix.begin(), Suffix.end());
Chris Lattner3b197832010-03-30 18:10:53 +00001420 return OutContext.GetOrCreateSymbol(NameStr.str());
Chris Lattnerf7871d12010-01-15 23:25:11 +00001421}
1422
Chris Lattner2eb781d2010-01-15 23:18:17 +00001423/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1424/// ExternalSymbol.
1425MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1426 SmallString<60> NameStr;
1427 Mang->getNameWithPrefix(NameStr, Sym);
1428 return OutContext.GetOrCreateSymbol(NameStr.str());
1429}
1430
Chris Lattner08c97082009-09-12 23:02:08 +00001431
Chris Lattner5abc72c2010-01-22 21:50:41 +00001432
1433/// PrintParentLoopComment - Print comments about parent loops of this one.
1434static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1435 unsigned FunctionNumber) {
1436 if (Loop == 0) return;
1437 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1438 OS.indent(Loop->getLoopDepth()*2)
1439 << "Parent Loop BB" << FunctionNumber << "_"
1440 << Loop->getHeader()->getNumber()
1441 << " Depth=" << Loop->getLoopDepth() << '\n';
1442}
1443
1444
1445/// PrintChildLoopComment - Print comments about child loops within
1446/// the loop for this basic block, with nesting.
1447static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1448 unsigned FunctionNumber) {
1449 // Add child loop information
1450 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1451 OS.indent((*CL)->getLoopDepth()*2)
1452 << "Child Loop BB" << FunctionNumber << "_"
1453 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1454 << '\n';
1455 PrintChildLoopComment(OS, *CL, FunctionNumber);
1456 }
1457}
1458
Chris Lattner49318552010-04-04 18:16:38 +00001459/// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1460static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1461 const MachineLoopInfo *LI,
1462 const AsmPrinter &AP) {
Chris Lattner5abc72c2010-01-22 21:50:41 +00001463 // Add loop depth information
1464 const MachineLoop *Loop = LI->getLoopFor(&MBB);
1465 if (Loop == 0) return;
1466
1467 MachineBasicBlock *Header = Loop->getHeader();
1468 assert(Header && "No header for loop");
1469
1470 // If this block is not a loop header, just print out what is the loop header
1471 // and return.
1472 if (Header != &MBB) {
1473 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
1474 Twine(AP.getFunctionNumber())+"_" +
1475 Twine(Loop->getHeader()->getNumber())+
1476 " Depth="+Twine(Loop->getLoopDepth()));
1477 return;
1478 }
1479
1480 // Otherwise, it is a loop header. Print out information about child and
1481 // parent loops.
1482 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1483
1484 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1485
1486 OS << "=>";
1487 OS.indent(Loop->getLoopDepth()*2-2);
1488
1489 OS << "This ";
1490 if (Loop->empty())
1491 OS << "Inner ";
1492 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1493
1494 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1495}
1496
1497
Chris Lattner2faa4ef2009-09-13 18:25:37 +00001498/// EmitBasicBlockStart - This method prints the label for the specified
1499/// MachineBasicBlock, an alignment (if present) and a comment describing
1500/// it if appropriate.
Chris Lattnerda5fb6d2009-09-14 03:15:54 +00001501void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001502 // Emit an alignment directive for this block, if needed.
Chris Lattner2faa4ef2009-09-13 18:25:37 +00001503 if (unsigned Align = MBB->getAlignment())
1504 EmitAlignment(Log2_32(Align));
Evan Cheng45c1edb2008-02-28 00:43:03 +00001505
Chris Lattnercc1205d2010-03-16 00:29:39 +00001506 // If the block has its address taken, emit any labels that were used to
1507 // reference the block. It is possible that there is more than one label
1508 // here, because multiple LLVM BB's may have been RAUW'd to this block after
1509 // the references were generated.
Dan Gohman91057512009-10-30 01:27:03 +00001510 if (MBB->hasAddressTaken()) {
Chris Lattner8bae1052010-01-20 07:24:05 +00001511 const BasicBlock *BB = MBB->getBasicBlock();
Chris Lattner97c69b72010-04-04 18:52:31 +00001512 if (isVerbose())
Chris Lattnercc1205d2010-03-16 00:29:39 +00001513 OutStreamer.AddComment("Block address taken");
1514
1515 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1516
1517 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1518 OutStreamer.EmitLabel(Syms[i]);
Dan Gohman91057512009-10-30 01:27:03 +00001519 }
1520
Dan Gohman65e3b3e2009-10-30 01:34:35 +00001521 // Print the main label for the block.
Chris Lattner04740c82010-02-17 18:52:56 +00001522 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
Chris Lattner97c69b72010-04-04 18:52:31 +00001523 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001524 if (const BasicBlock *BB = MBB->getBasicBlock())
1525 if (BB->hasName())
1526 OutStreamer.AddComment("%" + BB->getName());
Chris Lattner82be51c2010-01-22 21:00:45 +00001527
Chris Lattner49318552010-04-04 18:16:38 +00001528 EmitBasicBlockLoopComments(*MBB, LI, *this);
Chris Lattnerc468b2b2010-04-03 22:12:35 +00001529
1530 // NOTE: Want this comment at start of line, don't emit with AddComment.
1531 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1532 Twine(MBB->getNumber()) + ":");
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001533 }
Dan Gohman5fda4342009-10-06 17:38:38 +00001534 } else {
Chris Lattner97c69b72010-04-04 18:52:31 +00001535 if (isVerbose()) {
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001536 if (const BasicBlock *BB = MBB->getBasicBlock())
1537 if (BB->hasName())
1538 OutStreamer.AddComment("%" + BB->getName());
Chris Lattner49318552010-04-04 18:16:38 +00001539 EmitBasicBlockLoopComments(*MBB, LI, *this);
Chris Lattnerc006e1c2010-01-22 19:52:01 +00001540 }
Chris Lattner82be51c2010-01-22 21:00:45 +00001541
Chris Lattnerd13daf82010-03-13 21:04:28 +00001542 OutStreamer.EmitLabel(MBB->getSymbol());
Dan Gohman5fda4342009-10-06 17:38:38 +00001543 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001544}
1545
Chris Lattner32988552010-01-28 00:05:10 +00001546void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
Chris Lattner10bcc6b2010-01-23 06:53:23 +00001547 MCSymbolAttr Attr = MCSA_Invalid;
1548
1549 switch (Visibility) {
1550 default: break;
1551 case GlobalValue::HiddenVisibility:
1552 Attr = MAI->getHiddenVisibilityAttr();
1553 break;
1554 case GlobalValue::ProtectedVisibility:
1555 Attr = MAI->getProtectedVisibilityAttr();
1556 break;
Chris Lattner67cce682010-01-15 23:38:51 +00001557 }
Chris Lattner10bcc6b2010-01-23 06:53:23 +00001558
1559 if (Attr != MCSA_Invalid)
1560 OutStreamer.EmitSymbolAttribute(Sym, Attr);
Chris Lattner67cce682010-01-15 23:38:51 +00001561}
1562
Chris Lattner04740c82010-02-17 18:52:56 +00001563/// isBlockOnlyReachableByFallthough - Return true if the basic block has
1564/// exactly one predecessor and the control transfer mechanism between
1565/// the predecessor and this block is a fall-through.
Chris Lattner761dabb2010-04-04 17:57:56 +00001566bool AsmPrinter::
1567isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
Chris Lattner04740c82010-02-17 18:52:56 +00001568 // If this is a landing pad, it isn't a fall through. If it has no preds,
1569 // then nothing falls through to it.
1570 if (MBB->isLandingPad() || MBB->pred_empty())
1571 return false;
1572
1573 // If there isn't exactly one predecessor, it can't be a fall through.
1574 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1575 ++PI2;
1576 if (PI2 != MBB->pred_end())
1577 return false;
1578
1579 // The predecessor has to be immediately before this block.
1580 const MachineBasicBlock *Pred = *PI;
1581
1582 if (!Pred->isLayoutSuccessor(MBB))
1583 return false;
1584
1585 // If the block is completely empty, then it definitely does fall through.
1586 if (Pred->empty())
1587 return true;
1588
1589 // Otherwise, check the last instruction.
1590 const MachineInstr &LastInst = Pred->back();
1591 return !LastInst.getDesc().isBarrier();
1592}
1593
1594
1595
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001596GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1597 if (!S->usesMetadata())
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001598 return 0;
Chris Lattner761dabb2010-04-04 17:57:56 +00001599
1600 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1601 gcp_map_type::iterator GCPI = GCMap.find(S);
1602 if (GCPI != GCMap.end())
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001603 return GCPI->second;
1604
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001605 const char *Name = S->getName().c_str();
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001606
1607 for (GCMetadataPrinterRegistry::iterator
1608 I = GCMetadataPrinterRegistry::begin(),
1609 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1610 if (strcmp(Name, I->getName()) == 0) {
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001611 GCMetadataPrinter *GMP = I->instantiate();
1612 GMP->S = S;
Chris Lattner761dabb2010-04-04 17:57:56 +00001613 GCMap.insert(std::make_pair(S, GMP));
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001614 return GMP;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001615 }
1616
Chris Lattner54bfda72010-01-23 06:17:14 +00001617 llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1618 return 0;
Gordon Henriksen3385c9b2008-08-17 12:08:44 +00001619}
David Greene63486122009-07-13 20:25:48 +00001620