blob: 41d83beb5f2f67ae5f0d66c6f331905d97232b62 [file] [log] [blame]
Chris Lattnerc0561f22010-04-07 18:10:38 +00001//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
Chris Lattnera80ba712004-08-16 23:15:22 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera80ba712004-08-16 23:15:22 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner14c38ec2010-01-28 01:02:27 +000014#define DEBUG_TYPE "asm-printer"
Evan Cheng932f0222006-03-03 02:04:29 +000015#include "llvm/CodeGen/AsmPrinter.h"
Chris Lattner49cd6642010-04-05 05:11:15 +000016#include "DwarfDebug.h"
17#include "DwarfException.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/ConstantFolding.h"
21#include "llvm/Assembly/Writer.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000022#include "llvm/CodeGen/GCMetadataPrinter.h"
Chris Lattner3b4fd322005-11-21 08:25:09 +000023#include "llvm/CodeGen/MachineConstantPool.h"
David Greene1924aab2009-11-13 21:34:57 +000024#include "llvm/CodeGen/MachineFrameInfo.h"
David Greenefe37ab32009-08-18 19:22:55 +000025#include "llvm/CodeGen/MachineFunction.h"
Nate Begeman37efe672006-04-22 18:53:45 +000026#include "llvm/CodeGen/MachineJumpTableInfo.h"
David Greeneb71d1b22009-08-10 16:38:07 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000028#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/DebugInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Operator.h"
Chris Lattner736e31d2010-04-04 18:34:07 +000033#include "llvm/MC/MCAsmInfo.h"
Chris Lattner2b2954f2009-07-27 21:28:04 +000034#include "llvm/MC/MCContext.h"
Chris Lattner52492ac2010-01-23 06:17:14 +000035#include "llvm/MC/MCExpr.h"
David Greene3ac1ab82009-07-16 22:24:20 +000036#include "llvm/MC/MCInst.h"
Chris Lattnera87dea42009-07-31 18:48:30 +000037#include "llvm/MC/MCSection.h"
38#include "llvm/MC/MCStreamer.h"
Chris Lattner7cb384d2009-09-12 23:02:08 +000039#include "llvm/MC/MCSymbol.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/Format.h"
42#include "llvm/Support/MathExtras.h"
43#include "llvm/Support/Timer.h"
Chris Lattner45111d12010-01-16 21:57:06 +000044#include "llvm/Target/Mangler.h"
David Blaikie6d9dbd52013-06-16 20:34:15 +000045#include "llvm/Target/TargetFrameLowering.h"
David Greene1924aab2009-11-13 21:34:57 +000046#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner0336fdb2006-10-06 22:50:56 +000047#include "llvm/Target/TargetLowering.h"
Chris Lattnerf0144122009-07-28 03:13:23 +000048#include "llvm/Target/TargetLoweringObjectFile.h"
Rafael Espindolaa4329972011-04-29 14:14:06 +000049#include "llvm/Target/TargetOptions.h"
Evan Chengda47e6e2008-03-15 00:03:38 +000050#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattnera80ba712004-08-16 23:15:22 +000051using namespace llvm;
52
Craig Topper4172a8a2013-07-16 01:17:10 +000053static const char *const DWARFGroupName = "DWARF Emission";
54static const char *const DbgTimerName = "DWARF Debug Writer";
55static const char *const EHTimerName = "DWARF Exception Writer";
Torok Edwin9c421072010-04-07 10:44:46 +000056
Chris Lattner14c38ec2010-01-28 01:02:27 +000057STATISTIC(EmittedInsts, "Number of machine instrs printed");
58
Devang Patel19974732007-05-03 01:11:54 +000059char AsmPrinter::ID = 0;
Chris Lattner11d53c12010-03-13 20:55:24 +000060
Chris Lattnere00b59f2010-04-04 17:57:56 +000061typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
62static gcp_map_type &getGCMap(void *&P) {
63 if (P == 0)
64 P = new gcp_map_type();
65 return *(gcp_map_type*)P;
66}
67
68
Chris Lattnere87f7bb2010-04-28 19:58:07 +000069/// getGVAlignmentLog2 - Return the alignment to use for the specified global
70/// value in log2 form. This rounds up to the preferred alignment if possible
71/// and legal.
Micah Villmow3574eca2012-10-08 16:38:25 +000072static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
Chris Lattnere87f7bb2010-04-28 19:58:07 +000073 unsigned InBits = 0) {
74 unsigned NumBits = 0;
75 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
76 NumBits = TD.getPreferredAlignmentLog(GVar);
Jim Grosbach83d80832011-03-29 23:20:22 +000077
Chris Lattnere87f7bb2010-04-28 19:58:07 +000078 // If InBits is specified, round it to it.
79 if (InBits > NumBits)
80 NumBits = InBits;
Jim Grosbach83d80832011-03-29 23:20:22 +000081
Chris Lattnere87f7bb2010-04-28 19:58:07 +000082 // If the GV has a specified alignment, take it into account.
83 if (GV->getAlignment() == 0)
84 return NumBits;
Jim Grosbach83d80832011-03-29 23:20:22 +000085
Chris Lattnere87f7bb2010-04-28 19:58:07 +000086 unsigned GVAlign = Log2_32(GV->getAlignment());
Jim Grosbach83d80832011-03-29 23:20:22 +000087
Chris Lattnere87f7bb2010-04-28 19:58:07 +000088 // If the GVAlign is larger than NumBits, or if we are required to obey
89 // NumBits because the GV has an assigned section, obey it.
90 if (GVAlign > NumBits || GV->hasSection())
91 NumBits = GVAlign;
92 return NumBits;
93}
94
Chris Lattnerb23569a2010-04-04 08:18:47 +000095AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
Owen Anderson90c579d2010-08-06 18:33:48 +000096 : MachineFunctionPass(ID),
Joey Gouly715d98d2013-09-12 10:28:05 +000097 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
Chris Lattner11d53c12010-03-13 20:55:24 +000098 OutContext(Streamer.getContext()),
99 OutStreamer(Streamer),
Devang Patel553881b2010-03-29 17:20:31 +0000100 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
Hal Finkel6cf88c92013-07-11 06:41:14 +0000101 DD = 0; DE = 0; MMI = 0; LI = 0; MF = 0;
Hal Finkeld55a2662012-02-22 21:11:47 +0000102 CurrentFnSym = CurrentFnSymForSize = 0;
Chris Lattnere00b59f2010-04-04 17:57:56 +0000103 GCMetadataPrinters = 0;
Chris Lattner56591ab2010-02-02 23:37:42 +0000104 VerboseAsm = Streamer.isVerboseAsm();
Evan Cheng42bf74b2009-03-25 01:47:28 +0000105}
Chris Lattnered138932005-12-13 06:32:10 +0000106
Gordon Henriksenc317a602008-08-17 12:08:44 +0000107AsmPrinter::~AsmPrinter() {
Chris Lattner49cd6642010-04-05 05:11:15 +0000108 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
Jim Grosbach83d80832011-03-29 23:20:22 +0000109
Chris Lattnere00b59f2010-04-04 17:57:56 +0000110 if (GCMetadataPrinters != 0) {
111 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
Jim Grosbach83d80832011-03-29 23:20:22 +0000112
Chris Lattnere00b59f2010-04-04 17:57:56 +0000113 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
114 delete I->second;
115 delete &GCMap;
116 GCMetadataPrinters = 0;
117 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000118
Chris Lattner2b2954f2009-07-27 21:28:04 +0000119 delete &OutStreamer;
Gordon Henriksenc317a602008-08-17 12:08:44 +0000120}
Chris Lattnered138932005-12-13 06:32:10 +0000121
Chris Lattnerb84822f2010-01-26 04:35:26 +0000122/// getFunctionNumber - Return a unique ID for the current function.
123///
124unsigned AsmPrinter::getFunctionNumber() const {
125 return MF->getFunctionNumber();
126}
127
Dan Gohman0d805c32010-04-17 16:44:48 +0000128const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
Chris Lattnerf0144122009-07-28 03:13:23 +0000129 return TM.getTargetLowering()->getObjFileLowering();
130}
131
Micah Villmow3574eca2012-10-08 16:38:25 +0000132/// getDataLayout - Return information about data layout.
133const DataLayout &AsmPrinter::getDataLayout() const {
134 return *TM.getDataLayout();
Chris Lattnerd38fee82010-04-05 00:13:49 +0000135}
136
Eric Christopher00297ba2013-04-27 01:07:52 +0000137StringRef AsmPrinter::getTargetTriple() const {
138 return TM.getTargetTriple();
139}
140
Chris Lattnerdabf07c2009-08-18 06:15:16 +0000141/// getCurrentSection() - Return the current section we are emitting to.
142const MCSection *AsmPrinter::getCurrentSection() const {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000143 return OutStreamer.getCurrentSection().first;
Chris Lattnerdabf07c2009-08-18 06:15:16 +0000144}
145
146
Chris Lattnerd38fee82010-04-05 00:13:49 +0000147
Gordon Henriksence224772008-01-07 01:30:38 +0000148void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000149 AU.setPreservesAll();
Gordon Henriksence224772008-01-07 01:30:38 +0000150 MachineFunctionPass::getAnalysisUsage(AU);
Chris Lattner11d53c12010-03-13 20:55:24 +0000151 AU.addRequired<MachineModuleInfo>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000152 AU.addRequired<GCModuleInfo>();
Chris Lattner3f53c832010-04-04 18:52:31 +0000153 if (isVerbose())
David Greeneb71d1b22009-08-10 16:38:07 +0000154 AU.addRequired<MachineLoopInfo>();
Gordon Henriksence224772008-01-07 01:30:38 +0000155}
156
Chris Lattnera80ba712004-08-16 23:15:22 +0000157bool AsmPrinter::doInitialization(Module &M) {
Chris Lattnerd32c8a52010-04-04 05:09:10 +0000158 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Chris Lattner11d53c12010-03-13 20:55:24 +0000159 MMI->AnalyzeModule(M);
160
Chris Lattnerf26e03b2009-07-31 17:42:42 +0000161 // Initialize TargetLoweringObjectFile.
162 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
163 .Initialize(OutContext, TM);
Jim Grosbach83d80832011-03-29 23:20:22 +0000164
Nico Rieck25746dd2013-07-04 21:37:26 +0000165 OutStreamer.InitStreamer();
166
Rafael Espindola93cf0932013-10-29 17:28:26 +0000167 Mang = new Mangler(&TM);
Jim Grosbach83d80832011-03-29 23:20:22 +0000168
Bob Wilson812209a2009-09-30 22:06:26 +0000169 // Allow the target to emit any magic that it wants at the start of the file.
170 EmitStartOfAsmFile(M);
Rafael Espindola952b8392008-12-03 11:01:37 +0000171
Chris Lattnera6594fc2010-01-25 18:58:59 +0000172 // Very minimal debug info. It is ignored if we emit actual debug info. If we
173 // don't, this at least helps the user find where a global came from.
Chris Lattner33adcfb2009-08-22 21:43:10 +0000174 if (MAI->hasSingleParameterDotFile()) {
Chris Lattnera6594fc2010-01-25 18:58:59 +0000175 // .file "foo.c"
176 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
Rafael Espindola952b8392008-12-03 11:01:37 +0000177 }
178
Bob Wilson812209a2009-09-30 22:06:26 +0000179 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
180 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000181 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
182 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
Chris Lattner7d73c7f2010-04-04 07:39:04 +0000183 MP->beginAssembly(*this);
Chris Lattner91bead72010-04-03 21:35:55 +0000184
185 // Emit module-level inline asm if it exists.
Chris Lattner47b7e5d2010-04-03 21:13:18 +0000186 if (!M.getModuleInlineAsm().empty()) {
187 OutStreamer.AddComment("Start of file scope inline assembly");
188 OutStreamer.AddBlankLine();
Chris Lattnera38941d2010-11-17 07:53:40 +0000189 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
Chris Lattner47b7e5d2010-04-03 21:13:18 +0000190 OutStreamer.AddComment("End of file scope inline assembly");
191 OutStreamer.AddBlankLine();
192 }
Chris Lattner2c1b1592006-01-23 23:47:53 +0000193
Chris Lattner49cd6642010-04-05 05:11:15 +0000194 if (MAI->doesSupportDebugInformation())
195 DD = new DwarfDebug(this, &M);
Anton Korobeynikovd7e8ddc2011-01-14 21:57:45 +0000196
Rafael Espindola2d57a642011-05-05 19:48:34 +0000197 switch (MAI->getExceptionHandlingType()) {
198 case ExceptionHandling::None:
199 return false;
200 case ExceptionHandling::SjLj:
Rafael Espindola2d57a642011-05-05 19:48:34 +0000201 case ExceptionHandling::DwarfCFI:
202 DE = new DwarfCFIException(this);
203 return false;
204 case ExceptionHandling::ARM:
205 DE = new ARMException(this);
206 return false;
Charles Davisd652b132011-05-27 23:47:32 +0000207 case ExceptionHandling::Win64:
208 DE = new Win64Exception(this);
209 return false;
Rafael Espindola2d57a642011-05-05 19:48:34 +0000210 }
Devang Patel14a55d92009-06-19 21:54:26 +0000211
Rafael Espindola2d57a642011-05-05 19:48:34 +0000212 llvm_unreachable("Unknown exception type.");
Chris Lattnera80ba712004-08-16 23:15:22 +0000213}
214
Rafael Espindola38733612013-10-23 21:24:34 +0000215void AsmPrinter::EmitLinkage(unsigned L, MCSymbol *GVSym) const {
216 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes)L;
217
218 switch (Linkage) {
Chris Lattnera3e88832010-01-26 23:47:12 +0000219 case GlobalValue::CommonLinkage:
220 case GlobalValue::LinkOnceAnyLinkage:
221 case GlobalValue::LinkOnceODRLinkage:
Bill Wendling32811be2012-08-17 18:33:14 +0000222 case GlobalValue::LinkOnceODRAutoHideLinkage:
Chris Lattnera3e88832010-01-26 23:47:12 +0000223 case GlobalValue::WeakAnyLinkage:
224 case GlobalValue::WeakODRLinkage:
Bill Wendling5e721d72010-07-01 21:55:59 +0000225 case GlobalValue::LinkerPrivateWeakLinkage:
Chris Lattnera3e88832010-01-26 23:47:12 +0000226 if (MAI->getWeakDefDirective() != 0) {
227 // .globl _foo
228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Bill Wendling55ae5152010-08-20 22:05:50 +0000229
Rafael Espindola38733612013-10-23 21:24:34 +0000230 if (Linkage != GlobalValue::LinkOnceODRAutoHideLinkage)
Bill Wendling55ae5152010-08-20 22:05:50 +0000231 // .weak_definition _foo
232 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
233 else
234 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
Duncan Sands5b1b3b72010-05-12 07:11:33 +0000235 } else if (MAI->getLinkOnceDirective() != 0) {
Chris Lattnera3e88832010-01-26 23:47:12 +0000236 // .globl _foo
237 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Duncan Sands5b1b3b72010-05-12 07:11:33 +0000238 //NOTE: linkonce is handled by the section the symbol was assigned to.
Chris Lattnera3e88832010-01-26 23:47:12 +0000239 } else {
240 // .weak _foo
241 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
242 }
Rafael Espindola38733612013-10-23 21:24:34 +0000243 return;
Chris Lattnera3e88832010-01-26 23:47:12 +0000244 case GlobalValue::DLLExportLinkage:
245 case GlobalValue::AppendingLinkage:
246 // FIXME: appending linkage variables should go into a section of
247 // their name or something. For now, just emit them as external.
248 case GlobalValue::ExternalLinkage:
249 // If external or appending, declare as a global symbol.
250 // .globl _foo
251 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Rafael Espindola38733612013-10-23 21:24:34 +0000252 return;
Chris Lattnera3e88832010-01-26 23:47:12 +0000253 case GlobalValue::PrivateLinkage:
254 case GlobalValue::InternalLinkage:
Bill Wendlingeabd7352010-07-01 22:38:24 +0000255 case GlobalValue::LinkerPrivateLinkage:
Rafael Espindola38733612013-10-23 21:24:34 +0000256 return;
257 case GlobalValue::AvailableExternallyLinkage:
258 llvm_unreachable("Should never emit this");
259 case GlobalValue::DLLImportLinkage:
260 case GlobalValue::ExternalWeakLinkage:
261 llvm_unreachable("Don't know how to emit these");
Chris Lattnera3e88832010-01-26 23:47:12 +0000262 }
Rafael Espindola38733612013-10-23 21:24:34 +0000263 llvm_unreachable("Unknown linkage type!");
Chris Lattnera3e88832010-01-26 23:47:12 +0000264}
265
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000266MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
Rafael Espindola93cf0932013-10-29 17:28:26 +0000267 return getObjFileLowering().getSymbol(*Mang, GV);
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000268}
Chris Lattnera3e88832010-01-26 23:47:12 +0000269
Chris Lattner48d64ba2010-01-19 04:39:15 +0000270/// EmitGlobalVariable - Emit the specified global variable to the .s file.
271void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
Rafael Espindola84397472011-04-05 15:51:32 +0000272 if (GV->hasInitializer()) {
273 // Check to see if this is a special global used by LLVM, if so, emit it.
274 if (EmitSpecialLLVMGlobal(GV))
275 return;
Jim Grosbach83d80832011-03-29 23:20:22 +0000276
Rafael Espindola84397472011-04-05 15:51:32 +0000277 if (isVerbose()) {
278 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
279 /*PrintType=*/false, GV->getParent());
280 OutStreamer.GetCommentOS() << '\n';
281 }
Eric Christopher04386ca2010-05-25 21:49:43 +0000282 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000283
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000284 MCSymbol *GVSym = getSymbol(GV);
Chad Rosier348d5422011-06-10 00:53:15 +0000285 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
Chris Lattner74bfe212010-01-19 05:38:33 +0000286
Rafael Espindola84397472011-04-05 15:51:32 +0000287 if (!GV->hasInitializer()) // External globals require no extra code.
288 return;
289
Chris Lattnera800f7c2010-01-25 18:33:40 +0000290 if (MAI->hasDotTypeDotSizeDirective())
291 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
Jim Grosbach83d80832011-03-29 23:20:22 +0000292
Chris Lattner74bfe212010-01-19 05:38:33 +0000293 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
294
Matt Arsenaultcee51c42013-10-03 19:50:01 +0000295 const DataLayout *DL = TM.getDataLayout();
296 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
Jim Grosbach83d80832011-03-29 23:20:22 +0000297
Chris Lattner567dd1f2010-04-26 18:46:46 +0000298 // If the alignment is specified, we *must* obey it. Overaligning a global
299 // with a specified alignment is a prompt way to break globals emitted to
300 // sections and expected to be contiguous (e.g. ObjC metadata).
Matt Arsenaultcee51c42013-10-03 19:50:01 +0000301 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
Jim Grosbach83d80832011-03-29 23:20:22 +0000302
Richard Mittoneb46def2013-09-23 17:56:20 +0000303 if (DD)
304 DD->setSymbolSize(GVSym, Size);
305
Chris Lattner9744d612010-01-19 05:51:42 +0000306 // Handle common and BSS local symbols (.lcomm).
307 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
Chris Lattner74bfe212010-01-19 05:38:33 +0000308 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
Benjamin Kramer36a16012011-09-01 23:04:27 +0000309 unsigned Align = 1 << AlignLog;
Jim Grosbach83d80832011-03-29 23:20:22 +0000310
Chris Lattner814819f2010-01-19 06:25:51 +0000311 // Handle common symbols.
Chris Lattner9744d612010-01-19 05:51:42 +0000312 if (GVKind.isCommon()) {
Chris Lattner8048ebe2010-09-27 06:44:54 +0000313 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
314 Align = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000315
Chris Lattner9744d612010-01-19 05:51:42 +0000316 // .comm _foo, 42, 4
Chris Lattner8048ebe2010-09-27 06:44:54 +0000317 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
Chris Lattner814819f2010-01-19 06:25:51 +0000318 return;
Chris Lattner9744d612010-01-19 05:51:42 +0000319 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000320
Chris Lattner814819f2010-01-19 06:25:51 +0000321 // Handle local BSS symbols.
322 if (MAI->hasMachoZeroFillDirective()) {
323 const MCSection *TheSection =
324 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
325 // .zerofill __DATA, __bss, _foo, 400, 5
Benjamin Kramer36a16012011-09-01 23:04:27 +0000326 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
Chris Lattner814819f2010-01-19 06:25:51 +0000327 return;
328 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000329
Ulrich Weiganddba37a32012-11-27 16:11:16 +0000330 // Use .lcomm only if it supports user-specified alignment.
331 // Otherwise, while it would still be correct to use .lcomm in some
332 // cases (e.g. when Align == 1), the external assembler might enfore
333 // some -unknown- default alignment behavior, which could cause
334 // spurious differences between external and integrated assembler.
335 // Prefer to simply fall back to .local / .comm in this case.
336 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
Chris Lattner814819f2010-01-19 06:25:51 +0000337 // .lcomm _foo, 42
Benjamin Kramer36a16012011-09-01 23:04:27 +0000338 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
Chris Lattner814819f2010-01-19 06:25:51 +0000339 return;
340 }
Chris Lattner8048ebe2010-09-27 06:44:54 +0000341
Chris Lattner8048ebe2010-09-27 06:44:54 +0000342 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
343 Align = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000344
Chris Lattner814819f2010-01-19 06:25:51 +0000345 // .local _foo
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000346 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
Chris Lattner814819f2010-01-19 06:25:51 +0000347 // .comm _foo, 42, 4
Chris Lattner8048ebe2010-09-27 06:44:54 +0000348 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
Chris Lattner74bfe212010-01-19 05:38:33 +0000349 return;
350 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000351
Chris Lattner74bfe212010-01-19 05:38:33 +0000352 const MCSection *TheSection =
353 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
354
355 // Handle the zerofill directive on darwin, which is a special form of BSS
356 // emission.
357 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
Chris Lattner4c4d0c02010-04-27 07:41:44 +0000358 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
Jim Grosbach83d80832011-03-29 23:20:22 +0000359
Chris Lattner74bfe212010-01-19 05:38:33 +0000360 // .globl _foo
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000361 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
Chris Lattner74bfe212010-01-19 05:38:33 +0000362 // .zerofill __DATA, __common, _foo, 400, 5
363 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
364 return;
365 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000366
Eric Christopher02b46bc2010-05-25 21:28:50 +0000367 // Handle thread local data for mach-o which requires us to output an
368 // additional structure of data and mangle the original symbol so that we
369 // can reference it later.
Chris Lattnerdfe254b2010-09-05 20:33:40 +0000370 //
371 // TODO: This should become an "emit thread local global" method on TLOF.
372 // All of this macho specific stuff should be sunk down into TLOFMachO and
373 // stuff like "TLSExtraDataSection" should no longer be part of the parent
374 // TLOF class. This will also make it more obvious that stuff like
375 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
376 // specific code.
Eric Christopher02b46bc2010-05-25 21:28:50 +0000377 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
Eric Christopher8116ca52010-05-22 00:10:22 +0000378 // Emit the .tbss symbol
Jim Grosbach83d80832011-03-29 23:20:22 +0000379 MCSymbol *MangSym =
Eric Christopher8116ca52010-05-22 00:10:22 +0000380 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
Jim Grosbach83d80832011-03-29 23:20:22 +0000381
Eric Christopher10251752013-08-07 21:13:06 +0000382 if (GVKind.isThreadBSS()) {
383 TheSection = getObjFileLowering().getTLSBSSSection();
Eric Christopher02b46bc2010-05-25 21:28:50 +0000384 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
Eric Christopher10251752013-08-07 21:13:06 +0000385 } else if (GVKind.isThreadData()) {
Eric Christopher02b46bc2010-05-25 21:28:50 +0000386 OutStreamer.SwitchSection(TheSection);
387
Jim Grosbach83d80832011-03-29 23:20:22 +0000388 EmitAlignment(AlignLog, GV);
Eric Christopher02b46bc2010-05-25 21:28:50 +0000389 OutStreamer.EmitLabel(MangSym);
Jim Grosbach83d80832011-03-29 23:20:22 +0000390
Eric Christopher02b46bc2010-05-25 21:28:50 +0000391 EmitGlobalConstant(GV->getInitializer());
392 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000393
Eric Christopher8116ca52010-05-22 00:10:22 +0000394 OutStreamer.AddBlankLine();
Jim Grosbach83d80832011-03-29 23:20:22 +0000395
Eric Christopher8116ca52010-05-22 00:10:22 +0000396 // Emit the variable struct for the runtime.
Jim Grosbach83d80832011-03-29 23:20:22 +0000397 const MCSection *TLVSect
Eric Christopher8116ca52010-05-22 00:10:22 +0000398 = getObjFileLowering().getTLSExtraDataSection();
Jim Grosbach83d80832011-03-29 23:20:22 +0000399
Eric Christopher8116ca52010-05-22 00:10:22 +0000400 OutStreamer.SwitchSection(TLVSect);
401 // Emit the linkage here.
402 EmitLinkage(GV->getLinkage(), GVSym);
403 OutStreamer.EmitLabel(GVSym);
Jim Grosbach83d80832011-03-29 23:20:22 +0000404
Eric Christopher8116ca52010-05-22 00:10:22 +0000405 // Three pointers in size:
406 // - __tlv_bootstrap - used to make sure support exists
407 // - spare pointer, used when mapped by the runtime
408 // - pointer to mangled symbol above with initializer
Matt Arsenaultcee51c42013-10-03 19:50:01 +0000409 unsigned PtrSize = DL->getPointerSizeInBits()/8;
Eric Christopher73100642010-06-03 04:02:59 +0000410 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
Eric Christopherfdfc81f2013-06-24 23:20:02 +0000411 PtrSize);
Eric Christopher68ca5622013-01-09 01:57:54 +0000412 OutStreamer.EmitIntValue(0, PtrSize);
413 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
Jim Grosbach83d80832011-03-29 23:20:22 +0000414
Eric Christopher8116ca52010-05-22 00:10:22 +0000415 OutStreamer.AddBlankLine();
Eric Christopherc1a887d2010-05-20 00:49:07 +0000416 return;
417 }
Chris Lattner74bfe212010-01-19 05:38:33 +0000418
419 OutStreamer.SwitchSection(TheSection);
420
Chris Lattnera3e88832010-01-26 23:47:12 +0000421 EmitLinkage(GV->getLinkage(), GVSym);
Chris Lattnerf74e25f2010-04-26 18:30:45 +0000422 EmitAlignment(AlignLog, GV);
Chris Lattnera3e88832010-01-26 23:47:12 +0000423
Chris Lattner4c8c6682010-01-19 06:41:24 +0000424 OutStreamer.EmitLabel(GVSym);
Chris Lattner74bfe212010-01-19 05:38:33 +0000425
426 EmitGlobalConstant(GV->getInitializer());
427
428 if (MAI->hasDotTypeDotSizeDirective())
Chris Lattner1947f242010-01-25 07:53:05 +0000429 // .size foo, 42
Chris Lattner99328ad2010-01-25 07:52:13 +0000430 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
Jim Grosbach83d80832011-03-29 23:20:22 +0000431
Chris Lattner0fd90fd2010-01-22 19:52:01 +0000432 OutStreamer.AddBlankLine();
Chris Lattner48d64ba2010-01-19 04:39:15 +0000433}
434
Chris Lattnerb11caed2010-01-26 23:18:44 +0000435/// EmitFunctionHeader - This method emits the header for the current
436/// function.
437void AsmPrinter::EmitFunctionHeader() {
438 // Print out constants referenced by the function
Chris Lattnera2406192010-01-28 00:19:24 +0000439 EmitConstantPool();
Jim Grosbach83d80832011-03-29 23:20:22 +0000440
Chris Lattnerb11caed2010-01-26 23:18:44 +0000441 // Print the 'header' of function.
Chris Lattnerb11caed2010-01-26 23:18:44 +0000442 const Function *F = MF->getFunction();
443
444 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
Chris Lattnerbe9dfce2010-01-28 00:05:10 +0000445 EmitVisibility(CurrentFnSym, F->getVisibility());
Chris Lattnerb11caed2010-01-26 23:18:44 +0000446
Chris Lattner111a3192010-01-26 23:51:52 +0000447 EmitLinkage(F->getLinkage(), CurrentFnSym);
Chris Lattnerb406a812010-01-26 23:41:48 +0000448 EmitAlignment(MF->getAlignment(), F);
449
Chris Lattnerb11caed2010-01-26 23:18:44 +0000450 if (MAI->hasDotTypeDotSizeDirective())
451 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
452
Chris Lattner3f53c832010-04-04 18:52:31 +0000453 if (isVerbose()) {
Chris Lattner9bc20ab2010-01-26 23:53:39 +0000454 WriteAsOperand(OutStreamer.GetCommentOS(), F,
455 /*PrintType=*/false, F->getParent());
456 OutStreamer.GetCommentOS() << '\n';
Chris Lattnerb11caed2010-01-26 23:18:44 +0000457 }
Chris Lattnerb11caed2010-01-26 23:18:44 +0000458
Dan Gohmanf451cb82010-02-10 16:03:48 +0000459 // Emit the CurrentFnSym. This is a virtual function to allow targets to
Chris Lattner2cf72512010-01-27 07:21:55 +0000460 // do their wild and crazy things as required.
461 EmitFunctionEntryLabel();
Jim Grosbach83d80832011-03-29 23:20:22 +0000462
Chris Lattner9cc0da92010-03-15 20:39:00 +0000463 // If the function had address-taken blocks that got deleted, then we have
464 // references to the dangling symbols. Emit them at the start of the function
465 // so that we don't get references to undefined symbols.
466 std::vector<MCSymbol*> DeadBlockSyms;
467 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
468 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
469 OutStreamer.AddComment("Address taken block that was later removed");
470 OutStreamer.EmitLabel(DeadBlockSyms[i]);
471 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000472
Chris Lattnerb11caed2010-01-26 23:18:44 +0000473 // Emit pre-function debug and/or EH information.
Torok Edwin9c421072010-04-07 10:44:46 +0000474 if (DE) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000475 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
476 DE->BeginFunction(MF);
Torok Edwin9c421072010-04-07 10:44:46 +0000477 }
478 if (DD) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000479 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
480 DD->beginFunction(MF);
Torok Edwin9c421072010-04-07 10:44:46 +0000481 }
Peter Collingbourne0abc3622013-10-20 02:16:21 +0000482
483 // Emit the prefix data.
484 if (F->hasPrefixData())
485 EmitGlobalConstant(F->getPrefixData());
Chris Lattnerb11caed2010-01-26 23:18:44 +0000486}
487
Chris Lattner2cf72512010-01-27 07:21:55 +0000488/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
489/// function. This can be overridden by targets as required to do custom stuff.
490void AsmPrinter::EmitFunctionEntryLabel() {
Chris Lattnerb4202db2010-05-06 00:05:37 +0000491 // The function label could have already been emitted if two symbols end up
492 // conflicting due to asm renaming. Detect this and emit an error.
Jim Grosbach3e965312012-05-18 19:12:01 +0000493 if (CurrentFnSym->isUndefined())
Chris Lattnerb4202db2010-05-06 00:05:37 +0000494 return OutStreamer.EmitLabel(CurrentFnSym);
495
496 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
497 "' label emitted multiple times to assembly file");
Chris Lattner2cf72512010-01-27 07:21:55 +0000498}
Chris Lattnerb11caed2010-01-26 23:18:44 +0000499
Chad Rosierc53ade22012-09-07 18:16:38 +0000500/// emitComments - Pretty-print comments for instructions.
501static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
Devang Patele025e962010-06-29 22:29:15 +0000502 const MachineFunction *MF = MI.getParent()->getParent();
503 const TargetMachine &TM = MF->getTarget();
Jim Grosbach83d80832011-03-29 23:20:22 +0000504
Chris Lattner47529c92010-02-10 00:47:53 +0000505 // Check for spills and reloads
506 int FI;
Jim Grosbach83d80832011-03-29 23:20:22 +0000507
Chris Lattner47529c92010-02-10 00:47:53 +0000508 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000509
Chris Lattner47529c92010-02-10 00:47:53 +0000510 // We assume a single instruction only has a spill or reload, not
511 // both.
512 const MachineMemOperand *MMO;
513 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
514 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
515 MMO = *MI.memoperands_begin();
516 CommentOS << MMO->getSize() << "-byte Reload\n";
517 }
518 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
519 if (FrameInfo->isSpillSlotObjectIndex(FI))
520 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
521 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
522 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
523 MMO = *MI.memoperands_begin();
524 CommentOS << MMO->getSize() << "-byte Spill\n";
525 }
526 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
527 if (FrameInfo->isSpillSlotObjectIndex(FI))
528 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
529 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000530
Chris Lattner47529c92010-02-10 00:47:53 +0000531 // Check for spill-induced copies
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000532 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
533 CommentOS << " Reload Reuse\n";
Chris Lattner47529c92010-02-10 00:47:53 +0000534}
535
Chad Rosierc53ade22012-09-07 18:16:38 +0000536/// emitImplicitDef - This method emits the specified machine instruction
Chris Lattner17fedf22010-04-04 18:58:53 +0000537/// that is an implicit def.
Justin Holewinski43777c32013-10-11 12:39:36 +0000538void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
Chris Lattner17fedf22010-04-04 18:58:53 +0000539 unsigned RegNo = MI->getOperand(0).getReg();
Justin Holewinski43777c32013-10-11 12:39:36 +0000540 OutStreamer.AddComment(Twine("implicit-def: ") +
541 TM.getRegisterInfo()->getName(RegNo));
542 OutStreamer.AddBlankLine();
Chris Lattner17fedf22010-04-04 18:58:53 +0000543}
544
Chad Rosierc53ade22012-09-07 18:16:38 +0000545static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
Chris Lattner17fedf22010-04-04 18:58:53 +0000546 std::string Str = "kill:";
547 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
548 const MachineOperand &Op = MI->getOperand(i);
549 assert(Op.isReg() && "KILL instruction must have only register operands");
550 Str += ' ';
551 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
552 Str += (Op.isDef() ? "<def>" : "<kill>");
553 }
554 AP.OutStreamer.AddComment(Str);
555 AP.OutStreamer.AddBlankLine();
556}
557
Chad Rosierc53ade22012-09-07 18:16:38 +0000558/// emitDebugValueComment - This method handles the target-independent form
Dale Johannesen343b42e2010-04-07 01:15:14 +0000559/// of DBG_VALUE, returning true if it was able to do so. A false return
560/// means the target will need to handle MI in EmitInstruction.
Chad Rosierc53ade22012-09-07 18:16:38 +0000561static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
Dale Johannesen343b42e2010-04-07 01:15:14 +0000562 // This code handles only the 3-operand target-independent form.
563 if (MI->getNumOperands() != 3)
564 return false;
Chris Lattner47529c92010-02-10 00:47:53 +0000565
Benjamin Kramera592e672010-04-07 09:26:51 +0000566 SmallString<128> Str;
567 raw_svector_ostream OS(Str);
568 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
569
Dale Johannesen343b42e2010-04-07 01:15:14 +0000570 // cast away const; DIetc do not take const operands for some reason.
Chris Lattner00d13902010-04-07 22:29:10 +0000571 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
David Blaikie702ff962013-06-15 00:33:47 +0000572 if (V.getContext().isSubprogram()) {
573 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
574 if (!Name.empty())
575 OS << Name << ":";
576 }
Benjamin Kramera592e672010-04-07 09:26:51 +0000577 OS << V.getName() << " <- ";
Dale Johannesen343b42e2010-04-07 01:15:14 +0000578
Adrian Prantl35176402013-07-09 20:28:37 +0000579 // The second operand is only an offset if it's an immediate.
580 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
581 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
582
Dale Johannesen343b42e2010-04-07 01:15:14 +0000583 // Register or immediate value. Register 0 means undef.
584 if (MI->getOperand(0).isFPImm()) {
585 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
586 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
Benjamin Kramera592e672010-04-07 09:26:51 +0000587 OS << (double)APF.convertToFloat();
Dale Johannesen343b42e2010-04-07 01:15:14 +0000588 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
Benjamin Kramera592e672010-04-07 09:26:51 +0000589 OS << APF.convertToDouble();
Dale Johannesen343b42e2010-04-07 01:15:14 +0000590 } else {
591 // There is no good way to print long double. Convert a copy to
592 // double. Ah well, it's only a comment.
593 bool ignored;
594 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
595 &ignored);
Benjamin Kramera592e672010-04-07 09:26:51 +0000596 OS << "(long double) " << APF.convertToDouble();
Dale Johannesen343b42e2010-04-07 01:15:14 +0000597 }
598 } else if (MI->getOperand(0).isImm()) {
Benjamin Kramera592e672010-04-07 09:26:51 +0000599 OS << MI->getOperand(0).getImm();
Devang Patel8594d422011-06-24 20:46:11 +0000600 } else if (MI->getOperand(0).isCImm()) {
601 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
Chris Lattner00d13902010-04-07 22:29:10 +0000602 } else {
David Blaikie6d9dbd52013-06-16 20:34:15 +0000603 unsigned Reg;
604 if (MI->getOperand(0).isReg()) {
605 Reg = MI->getOperand(0).getReg();
David Blaikie6d9dbd52013-06-16 20:34:15 +0000606 } else {
607 assert(MI->getOperand(0).isFI() && "Unknown operand type");
608 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
Eric Christopherfdfc81f2013-06-24 23:20:02 +0000609 Offset += TFI->getFrameIndexReference(*AP.MF,
610 MI->getOperand(0).getIndex(), Reg);
David Blaikie6d9dbd52013-06-16 20:34:15 +0000611 Deref = true;
612 }
David Blaikief14b44c2013-06-15 15:52:58 +0000613 if (Reg == 0) {
Dale Johannesen343b42e2010-04-07 01:15:14 +0000614 // Suppress offset, it is not meaningful here.
Benjamin Kramera592e672010-04-07 09:26:51 +0000615 OS << "undef";
Dale Johannesen343b42e2010-04-07 01:15:14 +0000616 // NOTE: Want this comment at start of line, don't emit with AddComment.
Benjamin Kramera592e672010-04-07 09:26:51 +0000617 AP.OutStreamer.EmitRawText(OS.str());
Dale Johannesen343b42e2010-04-07 01:15:14 +0000618 return true;
619 }
David Blaikief14b44c2013-06-15 15:52:58 +0000620 if (Deref)
621 OS << '[';
622 OS << AP.TM.getRegisterInfo()->getName(Reg);
Chris Lattner00d13902010-04-07 22:29:10 +0000623 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000624
David Blaikief14b44c2013-06-15 15:52:58 +0000625 if (Deref)
Adrian Prantl35176402013-07-09 20:28:37 +0000626 OS << '+' << Offset << ']';
627
Dale Johannesen343b42e2010-04-07 01:15:14 +0000628 // NOTE: Want this comment at start of line, don't emit with AddComment.
Benjamin Kramera592e672010-04-07 09:26:51 +0000629 AP.OutStreamer.EmitRawText(OS.str());
Dale Johannesen343b42e2010-04-07 01:15:14 +0000630 return true;
631}
Chris Lattner47529c92010-02-10 00:47:53 +0000632
Rafael Espindolae29887b2011-05-10 18:39:09 +0000633AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000634 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
635 MF->getFunction()->needsUnwindTableEntry())
636 return CFI_M_EH;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000637
Rafael Espindolaf2b04232011-05-06 14:56:22 +0000638 if (MMI->hasDebugInfo())
Rafael Espindolae29887b2011-05-10 18:39:09 +0000639 return CFI_M_Debug;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000640
Rafael Espindolae29887b2011-05-10 18:39:09 +0000641 return CFI_M_None;
Rafael Espindolaa4329972011-04-29 14:14:06 +0000642}
643
Charles Davisf4633702011-05-28 04:21:04 +0000644bool AsmPrinter::needsSEHMoves() {
645 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
646 MF->getFunction()->needsUnwindTableEntry();
647}
648
Nick Lewycky390c40d2011-10-27 06:44:11 +0000649bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
Rafael Espindola9cfc7992012-06-22 13:32:49 +0000650 return MAI->doesDwarfUseRelocationsAcrossSections();
Nick Lewycky390c40d2011-10-27 06:44:11 +0000651}
652
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000653void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
Bill Wendling873e3922013-08-15 20:25:44 +0000654 const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
Rafael Espindolafea8fea2011-04-26 19:26:53 +0000655
Rafael Espindolaf2b04232011-05-06 14:56:22 +0000656 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000657 return;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000658
Rafael Espindolae29887b2011-05-10 18:39:09 +0000659 if (needsCFIMoves() == CFI_M_None)
Rafael Espindolaa4329972011-04-29 14:14:06 +0000660 return;
661
Bill Wendlinge060a5c2011-07-19 00:02:51 +0000662 if (MMI->getCompactUnwindEncoding() != 0)
663 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
664
Bill Wendling873e3922013-08-15 20:25:44 +0000665 const MachineModuleInfo &MMI = MF->getMMI();
Bill Wendling7d938ad2013-08-15 20:21:49 +0000666 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000667 bool FoundOne = false;
668 (void)FoundOne;
Bill Wendling7d938ad2013-08-15 20:21:49 +0000669 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
670 E = Instrs.end(); I != E; ++I) {
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000671 if (I->getLabel() == Label) {
Rafael Espindola4a971702013-05-13 01:16:13 +0000672 emitCFIInstruction(*I);
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000673 FoundOne = true;
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000674 }
675 }
Rafael Espindolab28d4f12011-04-26 03:58:56 +0000676 assert(FoundOne);
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000677}
678
Chris Lattner14c38ec2010-01-28 01:02:27 +0000679/// EmitFunctionBody - This method emits the body and trailer for a
680/// function.
681void AsmPrinter::EmitFunctionBody() {
Chris Lattneredfe7762010-01-28 01:58:58 +0000682 // Emit target-specific gunk before the function body.
683 EmitFunctionBodyStart();
Jim Grosbach83d80832011-03-29 23:20:22 +0000684
Chris Lattner49cd6642010-04-05 05:11:15 +0000685 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000686
Chris Lattner14c38ec2010-01-28 01:02:27 +0000687 // Print out code for the function.
688 bool HasAnyRealCode = false;
Bill Wendlingdc867042010-07-16 22:51:10 +0000689 const MachineInstr *LastMI = 0;
Chris Lattner14c38ec2010-01-28 01:02:27 +0000690 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
691 I != E; ++I) {
692 // Print a label for the basic block.
693 EmitBasicBlockStart(I);
694 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
695 II != IE; ++II) {
Bill Wendlingdc867042010-07-16 22:51:10 +0000696 LastMI = II;
697
Chris Lattner14c38ec2010-01-28 01:02:27 +0000698 // Print the assembly for the instruction.
Dale Johannesend0147612010-05-01 16:41:11 +0000699 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
700 !II->isDebugValue()) {
Chris Lattner14c38ec2010-01-28 01:02:27 +0000701 HasAnyRealCode = true;
Evan Chenged33b132010-04-27 19:38:45 +0000702 ++EmittedInsts;
703 }
704
Torok Edwin9c421072010-04-07 10:44:46 +0000705 if (ShouldPrintDebugScopes) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000706 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Devang Patelcbbe2872010-10-26 17:49:02 +0000707 DD->beginInstruction(II);
Torok Edwin9c421072010-04-07 10:44:46 +0000708 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000709
Chris Lattner3f53c832010-04-04 18:52:31 +0000710 if (isVerbose())
Chad Rosierc53ade22012-09-07 18:16:38 +0000711 emitComments(*II, OutStreamer.GetCommentOS());
Chris Lattner47529c92010-02-10 00:47:53 +0000712
Chris Lattner0d883e32010-02-03 01:00:52 +0000713 switch (II->getOpcode()) {
Bill Wendling7431bea2010-07-16 22:20:36 +0000714 case TargetOpcode::PROLOG_LABEL:
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000715 emitPrologLabel(*II);
716 break;
717
Chris Lattner518bb532010-02-09 19:54:29 +0000718 case TargetOpcode::EH_LABEL:
719 case TargetOpcode::GC_LABEL:
Chris Lattner300a4c52010-04-04 18:14:01 +0000720 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
Chris Lattner0d883e32010-02-03 01:00:52 +0000721 break;
Chris Lattner518bb532010-02-09 19:54:29 +0000722 case TargetOpcode::INLINEASM:
Chris Lattner300a4c52010-04-04 18:14:01 +0000723 EmitInlineAsm(II);
Chris Lattner0d883e32010-02-03 01:00:52 +0000724 break;
Dale Johannesen343b42e2010-04-07 01:15:14 +0000725 case TargetOpcode::DBG_VALUE:
726 if (isVerbose()) {
Chad Rosierc53ade22012-09-07 18:16:38 +0000727 if (!emitDebugValueComment(II, *this))
Dale Johannesen343b42e2010-04-07 01:15:14 +0000728 EmitInstruction(II);
729 }
730 break;
Chris Lattner518bb532010-02-09 19:54:29 +0000731 case TargetOpcode::IMPLICIT_DEF:
Justin Holewinski43777c32013-10-11 12:39:36 +0000732 if (isVerbose()) emitImplicitDef(II);
Chris Lattner0d883e32010-02-03 01:00:52 +0000733 break;
Chris Lattner518bb532010-02-09 19:54:29 +0000734 case TargetOpcode::KILL:
Chad Rosierc53ade22012-09-07 18:16:38 +0000735 if (isVerbose()) emitKill(II, *this);
Chris Lattner0d883e32010-02-03 01:00:52 +0000736 break;
737 default:
Devang Patel49a3ff92011-04-29 18:00:54 +0000738 if (!TM.hasMCUseLoc())
739 MCLineEntry::Make(&OutStreamer, getCurrentSection());
740
Chris Lattner0d883e32010-02-03 01:00:52 +0000741 EmitInstruction(II);
742 break;
743 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000744
Torok Edwin9c421072010-04-07 10:44:46 +0000745 if (ShouldPrintDebugScopes) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000746 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Devang Patelcbbe2872010-10-26 17:49:02 +0000747 DD->endInstruction(II);
Torok Edwin9c421072010-04-07 10:44:46 +0000748 }
Chris Lattner14c38ec2010-01-28 01:02:27 +0000749 }
750 }
Bill Wendlingdc867042010-07-16 22:51:10 +0000751
752 // If the last instruction was a prolog label, then we have a situation where
753 // we emitted a prolog but no function body. This results in the ending prolog
754 // label equaling the end of function label and an invalid "row" in the
755 // FDE. We need to emit a noop in this situation so that the FDE's rows are
756 // valid.
Bill Wendling74908962010-07-17 19:18:44 +0000757 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
Bill Wendlingdc867042010-07-16 22:51:10 +0000758
Chris Lattner14c38ec2010-01-28 01:02:27 +0000759 // If the function is empty and the object file uses .subsections_via_symbols,
Chris Lattnerd49fe1b2010-01-28 01:28:58 +0000760 // then we need to emit *something* to the function body to prevent the
Chris Lattneree9eb412010-04-26 23:37:21 +0000761 // labels from collapsing together. Just emit a noop.
Bill Wendlingdc867042010-07-16 22:51:10 +0000762 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
Chris Lattneree9eb412010-04-26 23:37:21 +0000763 MCInst Noop;
764 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
Chris Lattnerd61647d2010-04-26 23:41:43 +0000765 if (Noop.getOpcode()) {
766 OutStreamer.AddComment("avoids zero-length function");
Chris Lattneree9eb412010-04-26 23:37:21 +0000767 OutStreamer.EmitInstruction(Noop);
Chris Lattnerd61647d2010-04-26 23:41:43 +0000768 } else // Target not mc-ized yet.
Chris Lattneree9eb412010-04-26 23:37:21 +0000769 OutStreamer.EmitRawText(StringRef("\tnop\n"));
770 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000771
Rafael Espindola6c5b2dc2011-11-15 19:08:46 +0000772 const Function *F = MF->getFunction();
773 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
774 const BasicBlock *BB = i;
775 if (!BB->hasAddressTaken())
776 continue;
777 MCSymbol *Sym = GetBlockAddressSymbol(BB);
778 if (Sym->isDefined())
779 continue;
780 OutStreamer.AddComment("Address of block that was removed by CodeGen");
781 OutStreamer.EmitLabel(Sym);
782 }
783
Chris Lattneredfe7762010-01-28 01:58:58 +0000784 // Emit target-specific gunk after the function body.
785 EmitFunctionBodyEnd();
Jim Grosbach83d80832011-03-29 23:20:22 +0000786
Chris Lattnerfd60b8b2010-04-03 22:19:41 +0000787 // If the target wants a .size directive for the size of the function, emit
788 // it.
789 if (MAI->hasDotTypeDotSizeDirective()) {
Chris Lattner0c08d092010-04-03 22:28:33 +0000790 // Create a symbol for the end of function, so we can get the size as
791 // difference between the function label and the temp label.
792 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
793 OutStreamer.EmitLabel(FnEndLabel);
Jim Grosbach83d80832011-03-29 23:20:22 +0000794
Chris Lattner0c08d092010-04-03 22:28:33 +0000795 const MCExpr *SizeExp =
796 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
Hal Finkeld55a2662012-02-22 21:11:47 +0000797 MCSymbolRefExpr::Create(CurrentFnSymForSize,
798 OutContext),
Chris Lattner0c08d092010-04-03 22:28:33 +0000799 OutContext);
800 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
Chris Lattnerfd60b8b2010-04-03 22:19:41 +0000801 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000802
Chris Lattner14c38ec2010-01-28 01:02:27 +0000803 // Emit post-function debug information.
Torok Edwin9c421072010-04-07 10:44:46 +0000804 if (DD) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000805 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
806 DD->endFunction(MF);
Torok Edwin9c421072010-04-07 10:44:46 +0000807 }
808 if (DE) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000809 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
810 DE->EndFunction();
Torok Edwin9c421072010-04-07 10:44:46 +0000811 }
Chris Lattner49cd6642010-04-05 05:11:15 +0000812 MMI->EndFunction();
Jim Grosbach83d80832011-03-29 23:20:22 +0000813
Chris Lattner14c38ec2010-01-28 01:02:27 +0000814 // Print out jump tables referenced by the function.
815 EmitJumpTableInfo();
Jim Grosbach83d80832011-03-29 23:20:22 +0000816
Chris Lattnerd26a80f2010-02-03 01:49:49 +0000817 OutStreamer.AddBlankLine();
Chris Lattner14c38ec2010-01-28 01:02:27 +0000818}
819
Devang Patelacc381b2011-04-21 21:07:35 +0000820/// EmitDwarfRegOp - Emit dwarf register operation.
David Blaikie0159ae42013-06-19 21:55:13 +0000821void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
822 bool Indirect) const {
Devang Patelc26f5442011-04-28 02:22:40 +0000823 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Rafael Espindola37afca12011-05-27 22:15:01 +0000824 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
825
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000826 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
827 ++SR) {
Rafael Espindola37afca12011-05-27 22:15:01 +0000828 Reg = TRI->getDwarfRegNum(*SR, false);
829 // FIXME: Get the bit range this register uses of the superregister
830 // so that we can produce a DW_OP_bit_piece
831 }
832
833 // FIXME: Handle cases like a super register being encoded as
834 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
835
836 // FIXME: We have no reasonable way of handling errors in here. The
837 // caller might be in the middle of an dwarf expression. We should
838 // probably assert that Reg >= 0 once debug info generation is more mature.
839
David Blaikie0159ae42013-06-19 21:55:13 +0000840 if (MLoc.isIndirect() || Indirect) {
Devang Patelc26f5442011-04-28 02:22:40 +0000841 if (Reg < 32) {
842 OutStreamer.AddComment(
843 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
844 EmitInt8(dwarf::DW_OP_breg0 + Reg);
845 } else {
846 OutStreamer.AddComment("DW_OP_bregx");
847 EmitInt8(dwarf::DW_OP_bregx);
848 OutStreamer.AddComment(Twine(Reg));
849 EmitULEB128(Reg);
850 }
David Blaikie0159ae42013-06-19 21:55:13 +0000851 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
852 if (MLoc.isIndirect() && Indirect)
853 EmitInt8(dwarf::DW_OP_deref);
Devang Patelacc381b2011-04-21 21:07:35 +0000854 } else {
855 if (Reg < 32) {
Devang Patelacc381b2011-04-21 21:07:35 +0000856 OutStreamer.AddComment(
857 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
858 EmitInt8(dwarf::DW_OP_reg0 + Reg);
859 } else {
Devang Patelc26f5442011-04-28 02:22:40 +0000860 OutStreamer.AddComment("DW_OP_regx");
Devang Patelacc381b2011-04-21 21:07:35 +0000861 EmitInt8(dwarf::DW_OP_regx);
862 OutStreamer.AddComment(Twine(Reg));
863 EmitULEB128(Reg);
864 }
865 }
Rafael Espindola37afca12011-05-27 22:15:01 +0000866
867 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
Devang Patelacc381b2011-04-21 21:07:35 +0000868}
869
Chris Lattnera80ba712004-08-16 23:15:22 +0000870bool AsmPrinter::doFinalization(Module &M) {
Chris Lattner40bbebd2009-07-21 18:38:57 +0000871 // Emit global variables.
872 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
873 I != E; ++I)
Chris Lattner48d64ba2010-01-19 04:39:15 +0000874 EmitGlobalVariable(I);
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000875
876 // Emit visibility info for declarations
877 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
878 const Function &F = *I;
879 if (!F.isDeclaration())
880 continue;
881 GlobalValue::VisibilityTypes V = F.getVisibility();
882 if (V == GlobalValue::DefaultVisibility)
883 continue;
884
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000885 MCSymbol *Name = getSymbol(&F);
Stuart Hastings5129bde2011-02-23 02:27:05 +0000886 EmitVisibility(Name, V, false);
Rafael Espindola1ffb5332011-01-28 03:20:10 +0000887 }
888
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000889 // Emit module flags.
Bill Wendling057d5212012-02-15 22:36:15 +0000890 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
891 M.getModuleFlagsMetadata(ModuleFlags);
892 if (!ModuleFlags.empty())
893 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000894
Richard Mitton5cc319a2013-09-19 23:21:01 +0000895 // Make sure we wrote out everything we need.
896 OutStreamer.Flush();
897
Chris Lattner49cd6642010-04-05 05:11:15 +0000898 // Finalize debug and EH information.
899 if (DE) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000900 {
901 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
Torok Edwin9c421072010-04-07 10:44:46 +0000902 DE->EndModule();
903 }
Chris Lattner49cd6642010-04-05 05:11:15 +0000904 delete DE; DE = 0;
905 }
906 if (DD) {
Dan Gohman03c3dc72010-06-18 15:56:31 +0000907 {
908 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
Torok Edwin9c421072010-04-07 10:44:46 +0000909 DD->endModule();
910 }
Chris Lattner49cd6642010-04-05 05:11:15 +0000911 delete DD; DD = 0;
912 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000913
Chris Lattner0a7befa2009-06-24 18:52:01 +0000914 // If the target wants to know about weak references, print them all.
Chris Lattner33adcfb2009-08-22 21:43:10 +0000915 if (MAI->getWeakRefDirective()) {
Chris Lattner0a7befa2009-06-24 18:52:01 +0000916 // FIXME: This is not lazy, it would be nice to only print weak references
917 // to stuff that is actually used. Note that doing so would require targets
918 // to notice uses in operands (due to constant exprs etc). This should
919 // happen with the MC stuff eventually.
Rafael Espindola15404d02006-12-18 03:37:18 +0000920
Chris Lattner0a7befa2009-06-24 18:52:01 +0000921 // Print out module-level global variables here.
922 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
923 I != E; ++I) {
Chris Lattner08ce3b42010-01-16 18:17:26 +0000924 if (!I->hasExternalWeakLinkage()) continue;
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000925 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
Chris Lattner0a7befa2009-06-24 18:52:01 +0000926 }
Jim Grosbach83d80832011-03-29 23:20:22 +0000927
Chris Lattnerc6fdced2009-08-03 23:10:34 +0000928 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
Chris Lattner08ce3b42010-01-16 18:17:26 +0000929 if (!I->hasExternalWeakLinkage()) continue;
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000930 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
Chris Lattner0a7befa2009-06-24 18:52:01 +0000931 }
Rafael Espindola15404d02006-12-18 03:37:18 +0000932 }
933
Chris Lattnercee63322010-01-26 20:40:54 +0000934 if (MAI->hasSetDirective()) {
Chris Lattner3a9be0e2010-01-23 05:51:36 +0000935 OutStreamer.AddBlankLine();
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +0000936 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
Chris Lattner0a7befa2009-06-24 18:52:01 +0000937 I != E; ++I) {
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000938 MCSymbol *Name = getSymbol(I);
Anton Korobeynikov325be7c2007-09-06 17:21:48 +0000939
Jay Foadb899d952011-08-01 12:27:15 +0000940 const GlobalValue *GV = I->getAliasedGlobal();
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000941 MCSymbol *Target = getSymbol(GV);
Anton Korobeynikov541af7f2008-09-24 22:21:04 +0000942
Chris Lattner10b318b2010-01-17 21:43:43 +0000943 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000944 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
Rafael Espindola2def1792013-10-06 15:10:43 +0000945 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
Chris Lattnera5ad93a2010-01-23 06:39:22 +0000946 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
Chris Lattner10b318b2010-01-17 21:43:43 +0000947 else
Chris Lattner10595492010-01-16 01:37:14 +0000948 assert(I->hasLocalLinkage() && "Invalid alias linkage");
Anton Korobeynikov22c9e652008-03-11 21:41:14 +0000949
Chris Lattnerbe9dfce2010-01-28 00:05:10 +0000950 EmitVisibility(Name, I->getVisibility());
Anton Korobeynikov22c9e652008-03-11 21:41:14 +0000951
Chris Lattnerc618c8a2010-01-26 21:53:08 +0000952 // Emit the directives as assignments aka .set:
Jim Grosbach83d80832011-03-29 23:20:22 +0000953 OutStreamer.EmitAssignment(Name,
Chris Lattnerc618c8a2010-01-26 21:53:08 +0000954 MCSymbolRefExpr::Create(Target, OutContext));
Anton Korobeynikov8b0a8c82007-04-25 14:27:10 +0000955 }
956 }
957
Duncan Sands1465d612009-01-28 13:14:17 +0000958 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000959 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
960 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
961 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
Chris Lattner7d73c7f2010-04-04 07:39:04 +0000962 MP->finishAssembly(*this);
Gordon Henriksence224772008-01-07 01:30:38 +0000963
Rafael Espindola3aa342b2013-10-16 01:49:05 +0000964 // Emit llvm.ident metadata in an '.ident' directive.
965 EmitModuleIdents(M);
966
Dan Gohmana779a982008-05-05 00:28:39 +0000967 // If we don't have any trampolines, then we don't require stack memory
968 // to be executable. Some targets have a directive to declare this.
Chris Lattner0a7befa2009-06-24 18:52:01 +0000969 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
Dan Gohmana779a982008-05-05 00:28:39 +0000970 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
Chris Lattner74aae472010-04-08 21:26:26 +0000971 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
Chris Lattnerf9f93e42010-01-23 07:21:06 +0000972 OutStreamer.SwitchSection(S);
Jim Grosbach83d80832011-03-29 23:20:22 +0000973
Chris Lattnerbd23d5f2009-09-18 20:17:03 +0000974 // Allow the target to emit any magic that it wants at the end of the file,
975 // after everything else has gone out.
976 EmitEndOfAsmFile(M);
Jim Grosbach83d80832011-03-29 23:20:22 +0000977
Chris Lattnera80ba712004-08-16 23:15:22 +0000978 delete Mang; Mang = 0;
Chris Lattner49cd6642010-04-05 05:11:15 +0000979 MMI = 0;
Jim Grosbach83d80832011-03-29 23:20:22 +0000980
Chris Lattner2b2954f2009-07-27 21:28:04 +0000981 OutStreamer.Finish();
Pedro Artigas5399d252012-12-12 22:59:46 +0000982 OutStreamer.reset();
983
Chris Lattnera80ba712004-08-16 23:15:22 +0000984 return false;
985}
986
Chris Lattner25045bd2005-11-21 07:51:36 +0000987void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
Chris Lattnerb84822f2010-01-26 04:35:26 +0000988 this->MF = &MF;
Chris Lattner412c3a52010-01-16 01:24:10 +0000989 // Get the function symbol.
Rafael Espindolaffc7dca2013-10-29 17:07:16 +0000990 CurrentFnSym = getSymbol(MF.getFunction());
Hal Finkeld55a2662012-02-22 21:11:47 +0000991 CurrentFnSymForSize = CurrentFnSym;
David Greeneb71d1b22009-08-10 16:38:07 +0000992
Chris Lattner3f53c832010-04-04 18:52:31 +0000993 if (isVerbose())
David Greeneb71d1b22009-08-10 16:38:07 +0000994 LI = &getAnalysis<MachineLoopInfo>();
Chris Lattnera80ba712004-08-16 23:15:22 +0000995}
996
Evan Cheng1606e8e2009-03-13 07:51:59 +0000997namespace {
998 // SectionCPs - Keep track the alignment, constpool entries per Section.
999 struct SectionCPs {
Chris Lattnera87dea42009-07-31 18:48:30 +00001000 const MCSection *S;
Evan Cheng1606e8e2009-03-13 07:51:59 +00001001 unsigned Alignment;
1002 SmallVector<unsigned, 4> CPEs;
Douglas Gregorcabdd742009-12-19 07:05:23 +00001003 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
Evan Cheng1606e8e2009-03-13 07:51:59 +00001004 };
1005}
1006
Chris Lattner3b4fd322005-11-21 08:25:09 +00001007/// EmitConstantPool - Print to the current output stream assembly
1008/// representations of the constants in the constant pool MCP. This is
1009/// used to print out constants which have been "spilled to memory" by
1010/// the code generator.
1011///
Chris Lattnera2406192010-01-28 00:19:24 +00001012void AsmPrinter::EmitConstantPool() {
1013 const MachineConstantPool *MCP = MF->getConstantPool();
Chris Lattnerfa77d432006-02-09 04:22:52 +00001014 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
Chris Lattner3b4fd322005-11-21 08:25:09 +00001015 if (CP.empty()) return;
Evan Cheng2d2cec12006-06-29 00:26:09 +00001016
Anton Korobeynikov088ae832008-09-24 22:17:59 +00001017 // Calculate sections for constant pool entries. We collect entries to go into
1018 // the same section together to reduce amount of section switch statements.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001019 SmallVector<SectionCPs, 4> CPSections;
Chris Lattner3b4fd322005-11-21 08:25:09 +00001020 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
Chris Lattner298414e2009-07-22 00:28:43 +00001021 const MachineConstantPoolEntry &CPE = CP[i];
Evan Cheng1606e8e2009-03-13 07:51:59 +00001022 unsigned Align = CPE.getAlignment();
Jim Grosbach83d80832011-03-29 23:20:22 +00001023
Chris Lattner5c2f7892009-07-26 06:26:55 +00001024 SectionKind Kind;
1025 switch (CPE.getRelocationInfo()) {
1026 default: llvm_unreachable("Unknown section kind");
Chris Lattner27981192009-08-01 23:57:16 +00001027 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
Chris Lattner4c509222009-07-26 07:00:12 +00001028 case 1:
Chris Lattner27981192009-08-01 23:57:16 +00001029 Kind = SectionKind::getReadOnlyWithRelLocal();
Chris Lattner4c509222009-07-26 07:00:12 +00001030 break;
Chris Lattner5c2f7892009-07-26 06:26:55 +00001031 case 0:
Micah Villmow3574eca2012-10-08 16:38:25 +00001032 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
Chris Lattner27981192009-08-01 23:57:16 +00001033 case 4: Kind = SectionKind::getMergeableConst4(); break;
1034 case 8: Kind = SectionKind::getMergeableConst8(); break;
1035 case 16: Kind = SectionKind::getMergeableConst16();break;
1036 default: Kind = SectionKind::getMergeableConst(); break;
Chris Lattner4c509222009-07-26 07:00:12 +00001037 }
Chris Lattner5c2f7892009-07-26 06:26:55 +00001038 }
1039
Chris Lattner83d77fa2009-08-01 23:46:12 +00001040 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
Jim Grosbach83d80832011-03-29 23:20:22 +00001041
Evan Cheng1606e8e2009-03-13 07:51:59 +00001042 // The number of sections are small, just do a linear search from the
1043 // last section to the first.
1044 bool Found = false;
1045 unsigned SecIdx = CPSections.size();
1046 while (SecIdx != 0) {
1047 if (CPSections[--SecIdx].S == S) {
1048 Found = true;
1049 break;
1050 }
1051 }
1052 if (!Found) {
1053 SecIdx = CPSections.size();
1054 CPSections.push_back(SectionCPs(S, Align));
1055 }
1056
1057 if (Align > CPSections[SecIdx].Alignment)
1058 CPSections[SecIdx].Alignment = Align;
1059 CPSections[SecIdx].CPEs.push_back(i);
Evan Cheng2d2cec12006-06-29 00:26:09 +00001060 }
1061
Anton Korobeynikov088ae832008-09-24 22:17:59 +00001062 // Now print stuff into the calculated sections.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001063 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001064 OutStreamer.SwitchSection(CPSections[i].S);
Evan Cheng1606e8e2009-03-13 07:51:59 +00001065 EmitAlignment(Log2_32(CPSections[i].Alignment));
Evan Cheng2d2cec12006-06-29 00:26:09 +00001066
Evan Cheng1606e8e2009-03-13 07:51:59 +00001067 unsigned Offset = 0;
1068 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1069 unsigned CPI = CPSections[i].CPEs[j];
1070 MachineConstantPoolEntry CPE = CP[CPI];
Anton Korobeynikov088ae832008-09-24 22:17:59 +00001071
Chris Lattner3029f922006-02-09 04:46:04 +00001072 // Emit inter-object padding for alignment.
Evan Cheng1606e8e2009-03-13 07:51:59 +00001073 unsigned AlignMask = CPE.getAlignment() - 1;
1074 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
Eric Christopherca1dd052013-01-09 01:35:34 +00001075 OutStreamer.EmitZeros(NewOffset - Offset);
Evan Cheng1606e8e2009-03-13 07:51:59 +00001076
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001077 Type *Ty = CPE.getType();
Micah Villmow3574eca2012-10-08 16:38:25 +00001078 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
Chris Lattner39248682010-01-23 05:19:23 +00001079 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1080
Evan Cheng1606e8e2009-03-13 07:51:59 +00001081 if (CPE.isMachineConstantPoolEntry())
1082 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1083 else
1084 EmitGlobalConstant(CPE.Val.ConstVal);
Chris Lattner3029f922006-02-09 04:46:04 +00001085 }
Chris Lattner3b4fd322005-11-21 08:25:09 +00001086 }
1087}
1088
Nate Begeman37efe672006-04-22 18:53:45 +00001089/// EmitJumpTableInfo - Print assembly representations of the jump tables used
Jim Grosbach83d80832011-03-29 23:20:22 +00001090/// by the current function to the current output stream.
Nate Begeman37efe672006-04-22 18:53:45 +00001091///
Chris Lattner14c38ec2010-01-28 01:02:27 +00001092void AsmPrinter::EmitJumpTableInfo() {
1093 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
Chris Lattner44e87252010-01-25 22:41:33 +00001094 if (MJTI == 0) return;
Richard Osborne95da6052010-03-11 14:58:16 +00001095 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
Nate Begeman37efe672006-04-22 18:53:45 +00001096 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1097 if (JT.empty()) return;
Anton Korobeynikov9de19342007-11-14 09:18:41 +00001098
Jim Grosbach83d80832011-03-29 23:20:22 +00001099 // Pick the directive to use to print the jump table entries, and switch to
Nate Begeman2f1ae882006-07-27 01:13:04 +00001100 // the appropriate section.
Chris Lattner14c38ec2010-01-28 01:02:27 +00001101 const Function *F = MF->getFunction();
Evan Chengb13bafe2009-06-18 20:37:15 +00001102 bool JTInDiffSection = false;
Chris Lattnerf1214cb2010-01-26 06:53:37 +00001103 if (// In PIC mode, we need to emit the jump table to the same section as the
1104 // function body itself, otherwise the label differences won't make sense.
1105 // FIXME: Need a better predicate for this: what about custom entries?
1106 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1107 // We should also do if the section name is NULL or function is declared
1108 // in discardable section
1109 // FIXME: this isn't the right predicate, should be based on the MCSection
1110 // for the function.
1111 F->isWeakForLinker()) {
Chris Lattner14c38ec2010-01-28 01:02:27 +00001112 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
Nate Begeman2f1ae882006-07-27 01:13:04 +00001113 } else {
Chris Lattner83d77fa2009-08-01 23:46:12 +00001114 // Otherwise, drop it in the readonly section.
Jim Grosbach83d80832011-03-29 23:20:22 +00001115 const MCSection *ReadOnlySection =
Chris Lattner27981192009-08-01 23:57:16 +00001116 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
Chris Lattner6c2f9e12009-08-19 05:49:37 +00001117 OutStreamer.SwitchSection(ReadOnlySection);
Evan Chengb13bafe2009-06-18 20:37:15 +00001118 JTInDiffSection = true;
Nate Begeman2f1ae882006-07-27 01:13:04 +00001119 }
Chris Lattner071c62f2010-01-25 23:26:13 +00001120
Micah Villmow3574eca2012-10-08 16:38:25 +00001121 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
Jim Grosbach83d80832011-03-29 23:20:22 +00001122
Jim Grosbache9525d82012-09-24 23:06:27 +00001123 // Jump tables in code sections are marked with a data_region directive
1124 // where that's supported.
1125 if (!JTInDiffSection)
1126 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1127
Chris Lattner3b131d72010-01-26 06:42:44 +00001128 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1129 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
Jim Grosbach83d80832011-03-29 23:20:22 +00001130
1131 // If this jump table was deleted, ignore it.
Chris Lattner07371882006-10-28 18:10:06 +00001132 if (JTBBs.empty()) continue;
Nate Begeman52a51e382006-08-12 21:29:52 +00001133
Chris Lattnere35df922010-01-26 05:15:20 +00001134 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1135 // .set directive for each unique entry. This reduces the number of
1136 // relocations the assembler will generate for the jump table.
1137 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
Chris Lattnercee63322010-01-26 20:40:54 +00001138 MAI->hasSetDirective()) {
Chris Lattner3b131d72010-01-26 06:42:44 +00001139 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1140 const TargetLowering *TLI = TM.getTargetLowering();
Chris Lattner14c38ec2010-01-28 01:02:27 +00001141 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
Chris Lattner3b131d72010-01-26 06:42:44 +00001142 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1143 const MachineBasicBlock *MBB = JTBBs[ii];
1144 if (!EmittedSets.insert(MBB)) continue;
Jim Grosbach83d80832011-03-29 23:20:22 +00001145
Chris Lattnerc618c8a2010-01-26 21:53:08 +00001146 // .set LJTSet, LBB32-base
1147 const MCExpr *LHS =
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00001148 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattnerc618c8a2010-01-26 21:53:08 +00001149 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1150 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
Chris Lattner3b131d72010-01-26 06:42:44 +00001151 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001152 }
1153
Duncan Sandsab4c3662011-02-15 09:23:02 +00001154 // On some targets (e.g. Darwin) we want to emit two consecutive labels
Chris Lattner393a8ee2007-01-18 01:12:56 +00001155 // before each jump table. The first label is never referenced, but tells
1156 // the assembler and linker the extents of the jump table object. The
1157 // second label is actually referenced by the code.
Chris Lattner39248682010-01-23 05:19:23 +00001158 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
Chris Lattnerbeeb93e2010-01-26 05:58:28 +00001159 // FIXME: This doesn't have to have any specific name, just any randomly
1160 // named and numbered 'l' label would work. Simplify GetJTISymbol.
Chris Lattner3b131d72010-01-26 06:42:44 +00001161 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
Chris Lattner39248682010-01-23 05:19:23 +00001162
Chris Lattner3b131d72010-01-26 06:42:44 +00001163 OutStreamer.EmitLabel(GetJTISymbol(JTI));
Chris Lattner39248682010-01-23 05:19:23 +00001164
Chris Lattner6bf1def2010-01-26 05:10:10 +00001165 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
Chris Lattner3b131d72010-01-26 06:42:44 +00001166 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
Nate Begeman37efe672006-04-22 18:53:45 +00001167 }
Jim Grosbache9525d82012-09-24 23:06:27 +00001168 if (!JTInDiffSection)
1169 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
Nate Begeman37efe672006-04-22 18:53:45 +00001170}
1171
Chris Lattner6bf1def2010-01-26 05:10:10 +00001172/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1173/// current stream.
1174void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1175 const MachineBasicBlock *MBB,
1176 unsigned UID) const {
Jakob Stoklund Olesene5005d02011-02-09 21:52:06 +00001177 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
Chris Lattnerff537ce2010-01-26 03:43:22 +00001178 const MCExpr *Value = 0;
1179 switch (MJTI->getEntryKind()) {
Richard Osborne95da6052010-03-11 14:58:16 +00001180 case MachineJumpTableInfo::EK_Inline:
David Blaikie4d6ccb52012-01-20 21:51:11 +00001181 llvm_unreachable("Cannot emit EK_Inline jump table entry");
Chris Lattner85fe0782010-01-26 04:05:28 +00001182 case MachineJumpTableInfo::EK_Custom32:
Chris Lattner6bf1def2010-01-26 05:10:10 +00001183 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
Chris Lattner85fe0782010-01-26 04:05:28 +00001184 OutContext);
1185 break;
Chris Lattnerff537ce2010-01-26 03:43:22 +00001186 case MachineJumpTableInfo::EK_BlockAddress:
1187 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1188 // .word LBB123
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00001189 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattnerff537ce2010-01-26 03:43:22 +00001190 break;
Chris Lattnerff537ce2010-01-26 03:43:22 +00001191 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1192 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1193 // with a relocation as gp-relative, e.g.:
1194 // .gprel32 LBB123
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00001195 MCSymbol *MBBSym = MBB->getSymbol();
Chris Lattner718fb592010-01-25 21:28:50 +00001196 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
Chris Lattner78f485a2010-01-25 21:10:10 +00001197 return;
Anton Korobeynikov9de19342007-11-14 09:18:41 +00001198 }
Chris Lattner85fe0782010-01-26 04:05:28 +00001199
Akira Hatanaka6c2cf8b2012-02-03 04:33:00 +00001200 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1201 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1202 // with a relocation as gp-relative, e.g.:
1203 // .gpdword LBB123
1204 MCSymbol *MBBSym = MBB->getSymbol();
1205 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1206 return;
1207 }
1208
Chris Lattnerff537ce2010-01-26 03:43:22 +00001209 case MachineJumpTableInfo::EK_LabelDifference32: {
1210 // EK_LabelDifference32 - Each entry is the address of the block minus
1211 // the address of the jump table. This is used for PIC jump tables where
1212 // gprel32 is not supported. e.g.:
1213 // .word LBB123 - LJTI1_2
1214 // If the .set directive is supported, this is emitted as:
1215 // .set L4_5_set_123, LBB123 - LJTI1_2
1216 // .word L4_5_set_123
Jim Grosbach83d80832011-03-29 23:20:22 +00001217
1218 // If we have emitted set directives for the jump table entries, print
Chris Lattnerff537ce2010-01-26 03:43:22 +00001219 // them rather than the entries themselves. If we're emitting PIC, then
1220 // emit the table entries as differences between two text section labels.
Chris Lattnercee63322010-01-26 20:40:54 +00001221 if (MAI->hasSetDirective()) {
Chris Lattnerff537ce2010-01-26 03:43:22 +00001222 // If we used .set, reference the .set's symbol.
Chris Lattner6bf1def2010-01-26 05:10:10 +00001223 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
Chris Lattnerff537ce2010-01-26 03:43:22 +00001224 OutContext);
1225 break;
1226 }
Chris Lattner1aca2492010-01-25 21:22:22 +00001227 // Otherwise, use the difference as the jump table entry.
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00001228 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
Chris Lattner6bf1def2010-01-26 05:10:10 +00001229 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
Chris Lattnerff537ce2010-01-26 03:43:22 +00001230 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1231 break;
1232 }
Anton Korobeynikov9de19342007-11-14 09:18:41 +00001233 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001234
Chris Lattnerff537ce2010-01-26 03:43:22 +00001235 assert(Value && "Unknown entry kind!");
Jim Grosbach83d80832011-03-29 23:20:22 +00001236
Micah Villmow3574eca2012-10-08 16:38:25 +00001237 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
Eric Christopherca1dd052013-01-09 01:35:34 +00001238 OutStreamer.EmitValue(Value, EntrySize);
Anton Korobeynikov9de19342007-11-14 09:18:41 +00001239}
1240
1241
Chris Lattnered138932005-12-13 06:32:10 +00001242/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1243/// special global used by LLVM. If so, emit it and return true, otherwise
1244/// do nothing and return false.
1245bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
Daniel Dunbar03d76512009-07-25 23:55:21 +00001246 if (GV->getName() == "llvm.used") {
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001247 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
Rafael Espindolacde25b42013-04-22 14:58:02 +00001248 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
Andrew Lenharthb753a9b2007-08-22 19:33:11 +00001249 return true;
1250 }
1251
Chris Lattner401e10c2009-07-20 06:14:25 +00001252 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
Chris Lattner266c7bb2009-04-13 05:44:34 +00001253 if (GV->getSection() == "llvm.metadata" ||
1254 GV->hasAvailableExternallyLinkage())
1255 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00001256
Jim Laskey78098112006-03-07 22:00:35 +00001257 if (!GV->hasAppendingLinkage()) return false;
1258
1259 assert(GV->hasInitializer() && "Not a special LLVM global!");
Jim Grosbach83d80832011-03-29 23:20:22 +00001260
Chris Lattnerf231c072009-03-09 05:52:15 +00001261 if (GV->getName() == "llvm.global_ctors") {
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001262 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
Jim Grosbach83d80832011-03-29 23:20:22 +00001263
Chris Lattner71eae712010-01-19 04:34:02 +00001264 if (TM.getRelocationModel() == Reloc::Static &&
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001265 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1266 StringRef Sym(".constructors_used");
1267 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001268 MCSA_Reference);
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001269 }
Chris Lattnerea3a9ff2009-03-09 08:18:48 +00001270 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00001271 }
1272
Chris Lattnerf231c072009-03-09 05:52:15 +00001273 if (GV->getName() == "llvm.global_dtors") {
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001274 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
Chris Lattner71eae712010-01-19 04:34:02 +00001275
1276 if (TM.getRelocationModel() == Reloc::Static &&
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001277 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1278 StringRef Sym(".destructors_used");
1279 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001280 MCSA_Reference);
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001281 }
Chris Lattnerea3a9ff2009-03-09 08:18:48 +00001282 return true;
Chris Lattnered138932005-12-13 06:32:10 +00001283 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001284
Chris Lattnered138932005-12-13 06:32:10 +00001285 return false;
1286}
1287
Chris Lattner33adcfb2009-08-22 21:43:10 +00001288/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
Dale Johannesend2e51af2008-09-09 22:29:13 +00001289/// global in the specified llvm.used list for which emitUsedDirectiveFor
1290/// is true, as being used with this directive.
Rafael Espindolacde25b42013-04-22 14:58:02 +00001291void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
Dan Gohmana119de82009-06-14 23:30:43 +00001292 // Should be an array of 'i8*'.
Chris Lattnercb05af82006-09-26 03:38:18 +00001293 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner16fe9902009-07-17 22:00:23 +00001294 const GlobalValue *GV =
1295 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
Chris Lattner3a9be0e2010-01-23 05:51:36 +00001296 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
Rafael Espindolaffc7dca2013-10-29 17:07:16 +00001297 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
Chris Lattnercb05af82006-09-26 03:38:18 +00001298 }
1299}
1300
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001301/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1302/// priority.
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001303void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
Chris Lattnered138932005-12-13 06:32:10 +00001304 // Should be an array of '{ int, void ()* }' structs. The first value is the
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001305 // init priority.
Chris Lattnered138932005-12-13 06:32:10 +00001306 if (!isa<ConstantArray>(List)) return;
Chris Lattner8de324b2005-12-21 01:17:37 +00001307
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001308 // Sanity check the structors list.
1309 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1310 if (!InitList) return; // Not an array!
1311 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1312 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1313 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1314 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1315
1316 // Gather the structors in a form that's convenient for sorting by priority.
Benjamin Kramer0b6962f2013-08-24 12:54:27 +00001317 typedef std::pair<unsigned, Constant *> Structor;
Duncan Sandsfd9c4f72011-08-28 13:17:22 +00001318 SmallVector<Structor, 8> Structors;
1319 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1320 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1321 if (!CS) continue; // Malformed.
1322 if (CS->getOperand(1)->isNullValue())
1323 break; // Found a null terminator, skip the rest.
1324 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1325 if (!Priority) continue; // Malformed.
1326 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1327 CS->getOperand(1)));
1328 }
1329
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001330 // Emit the function pointers in the target-specific order
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001331 const DataLayout *DL = TM.getDataLayout();
1332 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
Benjamin Kramer0b6962f2013-08-24 12:54:27 +00001333 std::stable_sort(Structors.begin(), Structors.end(), less_first());
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001334 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1335 const MCSection *OutputSection =
1336 (isCtor ?
1337 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1338 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1339 OutStreamer.SwitchSection(OutputSection);
1340 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1341 EmitAlignment(Align);
James Molloy34982572012-01-26 09:25:43 +00001342 EmitXXStructor(Structors[i].second);
Anton Korobeynikov4a99f592012-01-25 22:24:19 +00001343 }
Chris Lattnered138932005-12-13 06:32:10 +00001344}
Chris Lattner3b4fd322005-11-21 08:25:09 +00001345
Rafael Espindola3aa342b2013-10-16 01:49:05 +00001346void AsmPrinter::EmitModuleIdents(Module &M) {
1347 if (!MAI->hasIdentDirective())
1348 return;
1349
1350 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1351 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1352 const MDNode *N = NMD->getOperand(i);
1353 assert(N->getNumOperands() == 1 &&
1354 "llvm.ident metadata entry can have only one operand");
1355 const MDString *S = cast<MDString>(N->getOperand(0));
1356 OutStreamer.EmitIdent(S->getString());
1357 }
1358 }
1359}
1360
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001361//===--------------------------------------------------------------------===//
1362// Emission and print routines
1363//
1364
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001365/// EmitInt8 - Emit a byte directive and value.
1366///
1367void AsmPrinter::EmitInt8(int Value) const {
Eric Christopherca1dd052013-01-09 01:35:34 +00001368 OutStreamer.EmitIntValue(Value, 1);
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001369}
1370
1371/// EmitInt16 - Emit a short directive and value.
1372///
1373void AsmPrinter::EmitInt16(int Value) const {
Eric Christopherca1dd052013-01-09 01:35:34 +00001374 OutStreamer.EmitIntValue(Value, 2);
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001375}
1376
1377/// EmitInt32 - Emit a long directive and value.
1378///
1379void AsmPrinter::EmitInt32(int Value) const {
Eric Christopherca1dd052013-01-09 01:35:34 +00001380 OutStreamer.EmitIntValue(Value, 4);
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001381}
1382
Chris Lattner0d50c762010-03-08 23:58:37 +00001383/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1384/// in bytes of the directive is specified by Size and Hi/Lo specify the
1385/// labels. This implicitly uses .set if it is available.
1386void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1387 unsigned Size) const {
1388 // Get the Hi-Lo expression.
Jim Grosbach83d80832011-03-29 23:20:22 +00001389 const MCExpr *Diff =
Chris Lattner0d50c762010-03-08 23:58:37 +00001390 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1391 MCSymbolRefExpr::Create(Lo, OutContext),
1392 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001393
Chris Lattner0d50c762010-03-08 23:58:37 +00001394 if (!MAI->hasSetDirective()) {
Eric Christopherca1dd052013-01-09 01:35:34 +00001395 OutStreamer.EmitValue(Diff, Size);
Chris Lattner0d50c762010-03-08 23:58:37 +00001396 return;
1397 }
1398
1399 // Otherwise, emit with .set (aka assignment).
Chris Lattnerc0215722010-04-04 19:25:43 +00001400 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
Chris Lattner0d50c762010-03-08 23:58:37 +00001401 OutStreamer.EmitAssignment(SetLabel, Diff);
Eric Christopherca1dd052013-01-09 01:35:34 +00001402 OutStreamer.EmitSymbolValue(SetLabel, Size);
Chris Lattner0d50c762010-03-08 23:58:37 +00001403}
1404
Jim Grosbach83d80832011-03-29 23:20:22 +00001405/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
Devang Patelf2548ca2010-04-16 23:33:45 +00001406/// where the size in bytes of the directive is specified by Size and Hi/Lo
1407/// specify the labels. This implicitly uses .set if it is available.
1408void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
Jim Grosbach83d80832011-03-29 23:20:22 +00001409 const MCSymbol *Lo, unsigned Size)
Devang Patelf2548ca2010-04-16 23:33:45 +00001410 const {
Jim Grosbach83d80832011-03-29 23:20:22 +00001411
Devang Patelf2548ca2010-04-16 23:33:45 +00001412 // Emit Hi+Offset - Lo
1413 // Get the Hi+Offset expression.
1414 const MCExpr *Plus =
Jim Grosbach83d80832011-03-29 23:20:22 +00001415 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
Devang Patelf2548ca2010-04-16 23:33:45 +00001416 MCConstantExpr::Create(Offset, OutContext),
1417 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001418
Devang Patelf2548ca2010-04-16 23:33:45 +00001419 // Get the Hi+Offset-Lo expression.
Jim Grosbach83d80832011-03-29 23:20:22 +00001420 const MCExpr *Diff =
Devang Patelf2548ca2010-04-16 23:33:45 +00001421 MCBinaryExpr::CreateSub(Plus,
1422 MCSymbolRefExpr::Create(Lo, OutContext),
1423 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001424
1425 if (!MAI->hasSetDirective())
Manman Ren38856f82013-10-29 23:14:15 +00001426 OutStreamer.EmitValue(Diff, Size);
Devang Patelf2548ca2010-04-16 23:33:45 +00001427 else {
1428 // Otherwise, emit with .set (aka assignment).
1429 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1430 OutStreamer.EmitAssignment(SetLabel, Diff);
Manman Ren38856f82013-10-29 23:14:15 +00001431 OutStreamer.EmitSymbolValue(SetLabel, Size);
Devang Patelf2548ca2010-04-16 23:33:45 +00001432 }
1433}
Devang Patelb1fcfbe2010-09-02 16:43:44 +00001434
Jim Grosbach83d80832011-03-29 23:20:22 +00001435/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
Devang Patelb1fcfbe2010-09-02 16:43:44 +00001436/// where the size in bytes of the directive is specified by Size and Label
1437/// specifies the label. This implicitly uses .set if it is available.
1438void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
Carlo Koke05a3042013-08-13 17:45:53 +00001439 unsigned Size, bool IsSectionRelative)
Devang Patelb1fcfbe2010-09-02 16:43:44 +00001440 const {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001441 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
Carlo Kokfdabd9f2013-08-02 16:14:15 +00001442 OutStreamer.EmitCOFFSecRel32(Label);
1443 return;
1444 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001445
Nick Lewyckyffccd922012-06-22 01:25:12 +00001446 // Emit Label+Offset (or just Label if Offset is zero)
1447 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1448 if (Offset)
1449 Expr = MCBinaryExpr::CreateAdd(Expr,
1450 MCConstantExpr::Create(Offset, OutContext),
1451 OutContext);
Jim Grosbach83d80832011-03-29 23:20:22 +00001452
Eric Christopherca1dd052013-01-09 01:35:34 +00001453 OutStreamer.EmitValue(Expr, Size);
Devang Patelb1fcfbe2010-09-02 16:43:44 +00001454}
Jim Grosbach83d80832011-03-29 23:20:22 +00001455
Chris Lattner0d50c762010-03-08 23:58:37 +00001456
Jim Laskeyf1cdea12007-01-25 15:12:02 +00001457//===----------------------------------------------------------------------===//
1458
Chris Lattner3a420532007-05-31 18:57:45 +00001459// EmitAlignment - Emit an alignment directive to the specified power of
1460// two boundary. For example, if you pass in 3 here, you will get an 8
1461// byte alignment. If a global value is specified, and if that global has
Chris Lattnere87f7bb2010-04-28 19:58:07 +00001462// an explicit alignment requested, it will override the alignment request
1463// if required for correctness.
Chris Lattner3a420532007-05-31 18:57:45 +00001464//
Chris Lattnera7b611c2010-04-28 01:08:40 +00001465void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
Micah Villmow3574eca2012-10-08 16:38:25 +00001466 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
Jim Grosbach83d80832011-03-29 23:20:22 +00001467
Chris Lattnere87f7bb2010-04-28 19:58:07 +00001468 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
Jim Grosbach83d80832011-03-29 23:20:22 +00001469
Chris Lattnerdabf07c2009-08-18 06:15:16 +00001470 if (getCurrentSection()->getKind().isText())
Chris Lattner2cce3712010-02-23 18:46:22 +00001471 OutStreamer.EmitCodeAlignment(1 << NumBits);
1472 else
1473 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
Chris Lattnerbfddc202004-08-17 19:14:29 +00001474}
David Greenea5bb59f2009-08-05 21:00:52 +00001475
Chris Lattner44e05082010-04-20 06:20:21 +00001476//===----------------------------------------------------------------------===//
1477// Constant emission.
1478//===----------------------------------------------------------------------===//
1479
Chad Rosierc53ade22012-09-07 18:16:38 +00001480/// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
Chris Lattner52492ac2010-01-23 06:17:14 +00001481///
Chad Rosierc53ade22012-09-07 18:16:38 +00001482static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
Chris Lattner52492ac2010-01-23 06:17:14 +00001483 MCContext &Ctx = AP.OutContext;
Jim Grosbach83d80832011-03-29 23:20:22 +00001484
Chris Lattner52492ac2010-01-23 06:17:14 +00001485 if (CV->isNullValue() || isa<UndefValue>(CV))
1486 return MCConstantExpr::Create(0, Ctx);
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001487
Chris Lattner52492ac2010-01-23 06:17:14 +00001488 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1489 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
Jim Grosbach83d80832011-03-29 23:20:22 +00001490
Chris Lattner52492ac2010-01-23 06:17:14 +00001491 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Rafael Espindolaffc7dca2013-10-29 17:07:16 +00001492 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
Bill Wendling3d7ff082010-08-18 18:41:13 +00001493
Chris Lattner52492ac2010-01-23 06:17:14 +00001494 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1495 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
Jim Grosbach83d80832011-03-29 23:20:22 +00001496
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001497 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1498 if (CE == 0) {
Chris Lattner52492ac2010-01-23 06:17:14 +00001499 llvm_unreachable("Unknown constant value to lower!");
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001500 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001501
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001502 switch (CE->getOpcode()) {
Dan Gohman618f1772010-02-08 22:02:38 +00001503 default:
1504 // If the code isn't optimized, there may be outstanding folding
Micah Villmow3574eca2012-10-08 16:38:25 +00001505 // opportunities. Attempt to fold the expression using DataLayout as a
Dan Gohman618f1772010-02-08 22:02:38 +00001506 // last resort before giving up.
Dan Gohman54e72ec2010-02-08 22:19:11 +00001507 if (Constant *C =
Micah Villmow3574eca2012-10-08 16:38:25 +00001508 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
Dan Gohman54e72ec2010-02-08 22:19:11 +00001509 if (C != CE)
Chad Rosierc53ade22012-09-07 18:16:38 +00001510 return lowerConstant(C, AP);
Dan Gohman9f6a68622010-08-04 18:51:09 +00001511
1512 // Otherwise report the problem to the user.
1513 {
1514 std::string S;
1515 raw_string_ostream OS(S);
1516 OS << "Unsupported expression in static initializer: ";
1517 WriteAsOperand(OS, CE, /*PrintType=*/false,
1518 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1519 report_fatal_error(OS.str());
1520 }
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001521 case Instruction::GetElementPtr: {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001522 const DataLayout &DL = *AP.TM.getDataLayout();
Chris Lattner52492ac2010-01-23 06:17:14 +00001523 // Generate a symbolic expression for the byte address
Matt Arsenaultff718122013-10-21 20:03:54 +00001524 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001525 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
Jim Grosbach83d80832011-03-29 23:20:22 +00001526
Chad Rosierc53ade22012-09-07 18:16:38 +00001527 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
Nuno Lopes98281a22012-12-30 16:25:48 +00001528 if (!OffsetAI)
Chris Lattner52492ac2010-01-23 06:17:14 +00001529 return Base;
Jim Grosbach83d80832011-03-29 23:20:22 +00001530
Nuno Lopes98281a22012-12-30 16:25:48 +00001531 int64_t Offset = OffsetAI.getSExtValue();
Chris Lattner52492ac2010-01-23 06:17:14 +00001532 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1533 Ctx);
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001534 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001535
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001536 case Instruction::Trunc:
1537 // We emit the value and depend on the assembler to truncate the generated
1538 // expression properly. This is important for differences between
1539 // blockaddress labels. Since the two labels are in the same function, it
1540 // is reasonable to treat their delta as a 32-bit value.
Chris Lattner52492ac2010-01-23 06:17:14 +00001541 // FALL THROUGH.
1542 case Instruction::BitCast:
Chad Rosierc53ade22012-09-07 18:16:38 +00001543 return lowerConstant(CE->getOperand(0), AP);
Chris Lattner52492ac2010-01-23 06:17:14 +00001544
1545 case Instruction::IntToPtr: {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001546 const DataLayout &DL = *AP.TM.getDataLayout();
Chris Lattner52492ac2010-01-23 06:17:14 +00001547 // Handle casts to pointers by changing them into casts to the appropriate
1548 // integer type. This promotes constant folding and simplifies this code.
1549 Constant *Op = CE->getOperand(0);
Matt Arsenaultff718122013-10-21 20:03:54 +00001550 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
Chris Lattner52492ac2010-01-23 06:17:14 +00001551 false/*ZExt*/);
Chad Rosierc53ade22012-09-07 18:16:38 +00001552 return lowerConstant(Op, AP);
Chris Lattner52492ac2010-01-23 06:17:14 +00001553 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001554
Chris Lattner52492ac2010-01-23 06:17:14 +00001555 case Instruction::PtrToInt: {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001556 const DataLayout &DL = *AP.TM.getDataLayout();
Chris Lattner52492ac2010-01-23 06:17:14 +00001557 // Support only foldable casts to/from pointers that can be eliminated by
1558 // changing the pointer to the appropriately sized integer type.
1559 Constant *Op = CE->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001560 Type *Ty = CE->getType();
Chris Lattner52492ac2010-01-23 06:17:14 +00001561
Chad Rosierc53ade22012-09-07 18:16:38 +00001562 const MCExpr *OpExpr = lowerConstant(Op, AP);
Chris Lattner52492ac2010-01-23 06:17:14 +00001563
1564 // We can emit the pointer value into this slot if the slot is an
1565 // integer slot equal to the size of the pointer.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001566 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
Chris Lattner52492ac2010-01-23 06:17:14 +00001567 return OpExpr;
1568
1569 // Otherwise the pointer is smaller than the resultant integer, mask off
1570 // the high bits so we are sure to get a proper truncation if the input is
1571 // a constant expr.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001572 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
Chris Lattner52492ac2010-01-23 06:17:14 +00001573 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1574 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1575 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001576
Dan Gohman5938a3e2010-02-09 00:02:37 +00001577 // The MC library also has a right-shift operator, but it isn't consistently
1578 // signed or unsigned between different targets.
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001579 case Instruction::Add:
1580 case Instruction::Sub:
Dan Gohman5938a3e2010-02-09 00:02:37 +00001581 case Instruction::Mul:
1582 case Instruction::SDiv:
1583 case Instruction::SRem:
1584 case Instruction::Shl:
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001585 case Instruction::And:
1586 case Instruction::Or:
Chris Lattner52492ac2010-01-23 06:17:14 +00001587 case Instruction::Xor: {
Chad Rosierc53ade22012-09-07 18:16:38 +00001588 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1589 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001590 switch (CE->getOpcode()) {
Chris Lattner52492ac2010-01-23 06:17:14 +00001591 default: llvm_unreachable("Unknown binary operator constant cast expr");
1592 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1593 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
Dan Gohman5938a3e2010-02-09 00:02:37 +00001594 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1595 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1596 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1597 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
Chris Lattner52492ac2010-01-23 06:17:14 +00001598 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1599 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1600 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
Chris Lattnerfe0e7ed2010-01-13 04:29:19 +00001601 }
Chris Lattner52492ac2010-01-23 06:17:14 +00001602 }
Chris Lattnera80ba712004-08-16 23:15:22 +00001603 }
1604}
Chris Lattner1b7e2352004-08-17 06:36:49 +00001605
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001606static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
Chris Lattner44e05082010-04-20 06:20:21 +00001607
David Greened92e2e42011-08-31 17:30:56 +00001608/// isRepeatedByteSequence - Determine whether the given value is
1609/// composed of a repeated sequence of identical bytes and return the
1610/// byte value. If it is not a repeated sequence, return -1.
Chris Lattner9e631da2012-01-24 09:31:43 +00001611static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1612 StringRef Data = V->getRawDataValues();
1613 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1614 char C = Data[0];
1615 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1616 if (Data[i] != C) return -1;
Chandler Carruthbeb05952012-01-30 23:47:44 +00001617 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
Chris Lattner9e631da2012-01-24 09:31:43 +00001618}
1619
1620
1621/// isRepeatedByteSequence - Determine whether the given value is
1622/// composed of a repeated sequence of identical bytes and return the
1623/// byte value. If it is not a repeated sequence, return -1.
David Greened92e2e42011-08-31 17:30:56 +00001624static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1625
1626 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1627 if (CI->getBitWidth() > 64) return -1;
1628
Micah Villmow3574eca2012-10-08 16:38:25 +00001629 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
David Greened92e2e42011-08-31 17:30:56 +00001630 uint64_t Value = CI->getZExtValue();
1631
1632 // Make sure the constant is at least 8 bits long and has a power
1633 // of 2 bit width. This guarantees the constant bit width is
1634 // always a multiple of 8 bits, avoiding issues with padding out
1635 // to Size and other such corner cases.
1636 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1637
1638 uint8_t Byte = static_cast<uint8_t>(Value);
1639
1640 for (unsigned i = 1; i < Size; ++i) {
1641 Value >>= 8;
1642 if (static_cast<uint8_t>(Value) != Byte) return -1;
1643 }
1644 return Byte;
1645 }
1646 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1647 // Make sure all array elements are sequences of the same repeated
1648 // byte.
Chris Lattner9e631da2012-01-24 09:31:43 +00001649 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
David Greened92e2e42011-08-31 17:30:56 +00001650 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1651 if (Byte == -1) return -1;
1652
1653 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1654 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1655 if (ThisByte == -1) return -1;
1656 if (Byte != ThisByte) return -1;
1657 }
1658 return Byte;
1659 }
Eric Christopherdcc675a2012-11-20 20:34:44 +00001660
Chris Lattner9e631da2012-01-24 09:31:43 +00001661 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1662 return isRepeatedByteSequence(CDS);
David Greened92e2e42011-08-31 17:30:56 +00001663
1664 return -1;
1665}
1666
Chad Rosierc53ade22012-09-07 18:16:38 +00001667static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001668 AsmPrinter &AP){
Eric Christopherdcc675a2012-11-20 20:34:44 +00001669
Chris Lattner9e631da2012-01-24 09:31:43 +00001670 // See if we can aggregate this into a .fill, if so, emit it as such.
1671 int Value = isRepeatedByteSequence(CDS, AP.TM);
1672 if (Value != -1) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001673 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
Chris Lattnerc63352f2012-01-31 03:39:24 +00001674 // Don't emit a 1-byte object as a .fill.
1675 if (Bytes > 1)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001676 return AP.OutStreamer.EmitFill(Bytes, Value);
Chris Lattner9e631da2012-01-24 09:31:43 +00001677 }
Eric Christopherdcc675a2012-11-20 20:34:44 +00001678
Chris Lattner9e631da2012-01-24 09:31:43 +00001679 // If this can be emitted with .ascii/.asciz, emit it as such.
1680 if (CDS->isString())
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001681 return AP.OutStreamer.EmitBytes(CDS->getAsString());
Chris Lattner9e631da2012-01-24 09:31:43 +00001682
1683 // Otherwise, emit the values in successive locations.
1684 unsigned ElementByteSize = CDS->getElementByteSize();
1685 if (isa<IntegerType>(CDS->getElementType())) {
Chris Lattner0f193b82012-01-25 01:27:20 +00001686 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerb66fb5a2012-01-30 05:55:11 +00001687 if (AP.isVerbose())
1688 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1689 CDS->getElementAsInteger(i));
Chris Lattner9e631da2012-01-24 09:31:43 +00001690 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001691 ElementByteSize);
Chris Lattner9e631da2012-01-24 09:31:43 +00001692 }
Chris Lattner6e64c382012-01-30 05:49:43 +00001693 } else if (ElementByteSize == 4) {
1694 // FP Constants are printed as integer constants to avoid losing
1695 // precision.
1696 assert(CDS->getElementType()->isFloatTy());
Chris Lattner0f193b82012-01-25 01:27:20 +00001697 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner9e631da2012-01-24 09:31:43 +00001698 union {
1699 float F;
1700 uint32_t I;
1701 };
Eric Christopherdcc675a2012-11-20 20:34:44 +00001702
Chris Lattner9e631da2012-01-24 09:31:43 +00001703 F = CDS->getElementAsFloat(i);
1704 if (AP.isVerbose())
1705 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001706 AP.OutStreamer.EmitIntValue(I, 4);
Chris Lattner9e631da2012-01-24 09:31:43 +00001707 }
Chris Lattner6e64c382012-01-30 05:49:43 +00001708 } else {
1709 assert(CDS->getElementType()->isDoubleTy());
1710 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1711 union {
1712 double F;
1713 uint64_t I;
1714 };
Eric Christopherdcc675a2012-11-20 20:34:44 +00001715
Chris Lattner6e64c382012-01-30 05:49:43 +00001716 F = CDS->getElementAsDouble(i);
1717 if (AP.isVerbose())
1718 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001719 AP.OutStreamer.EmitIntValue(I, 8);
Chris Lattner6e64c382012-01-30 05:49:43 +00001720 }
Chris Lattner9e631da2012-01-24 09:31:43 +00001721 }
1722
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001723 const DataLayout &DL = *AP.TM.getDataLayout();
1724 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1725 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
Chris Lattner6e64c382012-01-30 05:49:43 +00001726 CDS->getNumElements();
1727 if (unsigned Padding = Size - EmittedSize)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001728 AP.OutStreamer.EmitZeros(Padding);
Chris Lattner6e64c382012-01-30 05:49:43 +00001729
Chris Lattner9e631da2012-01-24 09:31:43 +00001730}
1731
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001732static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
Chris Lattner18c7f802012-02-05 02:29:43 +00001733 // See if we can aggregate some values. Make sure it can be
1734 // represented as a series of bytes of the constant value.
1735 int Value = isRepeatedByteSequence(CA, AP.TM);
David Greened92e2e42011-08-31 17:30:56 +00001736
Chris Lattner18c7f802012-02-05 02:29:43 +00001737 if (Value != -1) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001738 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001739 AP.OutStreamer.EmitFill(Bytes, Value);
Dan Gohman00d448a2008-12-22 21:14:27 +00001740 }
Chris Lattner18c7f802012-02-05 02:29:43 +00001741 else {
1742 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001743 emitGlobalConstantImpl(CA->getOperand(i), AP);
Chris Lattner18c7f802012-02-05 02:29:43 +00001744 }
Dan Gohman00d448a2008-12-22 21:14:27 +00001745}
1746
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001747static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
Chris Lattnerbcb83e52010-01-20 07:41:15 +00001748 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001749 emitGlobalConstantImpl(CV->getOperand(i), AP);
Nick Lewycky5b7ac142011-06-22 18:55:03 +00001750
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001751 const DataLayout &DL = *AP.TM.getDataLayout();
1752 unsigned Size = DL.getTypeAllocSize(CV->getType());
1753 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
Nick Lewycky5b7ac142011-06-22 18:55:03 +00001754 CV->getType()->getNumElements();
1755 if (unsigned Padding = Size - EmittedSize)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001756 AP.OutStreamer.EmitZeros(Padding);
Dan Gohman00d448a2008-12-22 21:14:27 +00001757}
1758
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001759static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
Dan Gohman00d448a2008-12-22 21:14:27 +00001760 // Print the fields in successive locations. Pad to align if needed!
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001761 const DataLayout *DL = AP.TM.getDataLayout();
1762 unsigned Size = DL->getTypeAllocSize(CS->getType());
1763 const StructLayout *Layout = DL->getStructLayout(CS->getType());
Chris Lattner91093ec2010-01-19 19:10:44 +00001764 uint64_t SizeSoFar = 0;
1765 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattnerbcb83e52010-01-20 07:41:15 +00001766 const Constant *Field = CS->getOperand(i);
Dan Gohman00d448a2008-12-22 21:14:27 +00001767
1768 // Check if padding is needed and insert one or more 0s.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001769 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
Chris Lattner2dd245c2010-01-20 07:11:32 +00001770 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1771 - Layout->getElementOffset(i)) - FieldSize;
1772 SizeSoFar += FieldSize + PadSize;
Dan Gohman00d448a2008-12-22 21:14:27 +00001773
1774 // Now print the actual field value.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001775 emitGlobalConstantImpl(Field, AP);
Dan Gohman00d448a2008-12-22 21:14:27 +00001776
1777 // Insert padding - this may include padding to increase the size of the
1778 // current field up to the ABI size (if the struct is not packed) as well
1779 // as padding to ensure that the next field starts at the right offset.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001780 AP.OutStreamer.EmitZeros(PadSize);
Dan Gohman00d448a2008-12-22 21:14:27 +00001781 }
Chris Lattner2dd245c2010-01-20 07:11:32 +00001782 assert(SizeSoFar == Layout->getSizeInBytes() &&
Dan Gohman00d448a2008-12-22 21:14:27 +00001783 "Layout of constant struct may be incorrect!");
1784}
1785
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001786static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
Chris Lattner09ce6742010-01-19 22:16:33 +00001787 APInt API = CFP->getValueAPF().bitcastToAPInt();
Tim Northover5f2801b2013-01-11 10:36:13 +00001788
1789 // First print a comment with what we think the original floating-point value
1790 // should have been.
1791 if (AP.isVerbose()) {
1792 SmallString<8> StrVal;
1793 CFP->getValueAPF().toString(StrVal);
1794
1795 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1796 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
Chris Lattner09ce6742010-01-19 22:16:33 +00001797 }
Tim Northover5f2801b2013-01-11 10:36:13 +00001798
1799 // Now iterate through the APInt chunks, emitting them in endian-correct
1800 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1801 // floats).
1802 unsigned NumBytes = API.getBitWidth() / 8;
1803 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1804 const uint64_t *p = API.getRawData();
1805
1806 // PPC's long double has odd notions of endianness compared to how LLVM
1807 // handles it: p[0] goes first for *big* endian on PPC.
1808 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1809 int Chunk = API.getNumWords() - 1;
1810
1811 if (TrailingBytes)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001812 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
Tim Northover5f2801b2013-01-11 10:36:13 +00001813
1814 for (; Chunk >= 0; --Chunk)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001815 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
Tim Northover5f2801b2013-01-11 10:36:13 +00001816 } else {
1817 unsigned Chunk;
1818 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001819 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
Tim Northover5f2801b2013-01-11 10:36:13 +00001820
1821 if (TrailingBytes)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001822 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
Tim Northover5f2801b2013-01-11 10:36:13 +00001823 }
1824
1825 // Emit the tail padding for the long double.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001826 const DataLayout &DL = *AP.TM.getDataLayout();
1827 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1828 DL.getTypeStoreSize(CFP->getType()));
Dan Gohman00d448a2008-12-22 21:14:27 +00001829}
1830
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001831static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001832 const DataLayout *DL = AP.TM.getDataLayout();
Dan Gohman00d448a2008-12-22 21:14:27 +00001833 unsigned BitWidth = CI->getBitWidth();
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001834
1835 // Copy the value as we may massage the layout for constants whose bit width
1836 // is not a multiple of 64-bits.
1837 APInt Realigned(CI->getValue());
1838 uint64_t ExtraBits = 0;
1839 unsigned ExtraBitsSize = BitWidth & 63;
1840
1841 if (ExtraBitsSize) {
1842 // The bit width of the data is not a multiple of 64-bits.
1843 // The extra bits are expected to be at the end of the chunk of the memory.
1844 // Little endian:
1845 // * Nothing to be done, just record the extra bits to emit.
1846 // Big endian:
1847 // * Record the extra bits to emit.
1848 // * Realign the raw data to emit the chunks of 64-bits.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001849 if (DL->isBigEndian()) {
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001850 // Basically the structure of the raw data is a chunk of 64-bits cells:
1851 // 0 1 BitWidth / 64
1852 // [chunk1][chunk2] ... [chunkN].
1853 // The most significant chunk is chunkN and it should be emitted first.
1854 // However, due to the alignment issue chunkN contains useless bits.
1855 // Realign the chunks so that they contain only useless information:
1856 // ExtraBits 0 1 (BitWidth / 64) - 1
1857 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1858 ExtraBits = Realigned.getRawData()[0] &
1859 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1860 Realigned = Realigned.lshr(ExtraBitsSize);
1861 } else
1862 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1863 }
Dan Gohman00d448a2008-12-22 21:14:27 +00001864
1865 // We don't expect assemblers to support integer data directives
1866 // for more than 64 bits, so we emit the data in at most 64-bit
1867 // quantities at a time.
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001868 const uint64_t *RawData = Realigned.getRawData();
Dan Gohman00d448a2008-12-22 21:14:27 +00001869 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001870 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001871 AP.OutStreamer.EmitIntValue(Val, 8);
Dan Gohman00d448a2008-12-22 21:14:27 +00001872 }
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001873
1874 if (ExtraBitsSize) {
1875 // Emit the extra bits after the 64-bits chunks.
1876
1877 // Emit a directive that fills the expected size.
1878 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1879 Size -= (BitWidth / 64) * 8;
1880 assert(Size && Size * 8 >= ExtraBitsSize &&
1881 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1882 == ExtraBits && "Directive too small for extra bits.");
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001883 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
Quentin Colombetfcca6c62013-06-07 18:36:03 +00001884 }
Dan Gohman00d448a2008-12-22 21:14:27 +00001885}
1886
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001887static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001888 const DataLayout *DL = AP.TM.getDataLayout();
1889 uint64_t Size = DL->getTypeAllocSize(CV->getType());
Bill Wendling21e42d02012-03-20 08:56:43 +00001890 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001891 return AP.OutStreamer.EmitZeros(Size);
Chris Lattner2dd245c2010-01-20 07:11:32 +00001892
1893 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Chris Lattner2dd245c2010-01-20 07:11:32 +00001894 switch (Size) {
1895 case 1:
1896 case 2:
1897 case 4:
1898 case 8:
Chris Lattner44e05082010-04-20 06:20:21 +00001899 if (AP.isVerbose())
Benjamin Kramer41a96492011-11-05 08:57:40 +00001900 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1901 CI->getZExtValue());
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001902 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
Chris Lattner2dd245c2010-01-20 07:11:32 +00001903 return;
1904 default:
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001905 emitGlobalConstantLargeInt(CI, AP);
Chris Lattner2dd245c2010-01-20 07:11:32 +00001906 return;
1907 }
1908 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001909
Chris Lattner91093ec2010-01-19 19:10:44 +00001910 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001911 return emitGlobalConstantFP(CFP, AP);
Chris Lattner1b7e2352004-08-17 06:36:49 +00001912
Chris Lattnerb0bedd62010-01-20 17:57:50 +00001913 if (isa<ConstantPointerNull>(CV)) {
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001914 AP.OutStreamer.EmitIntValue(0, Size);
Chris Lattnerb0bedd62010-01-20 17:57:50 +00001915 return;
1916 }
Jim Grosbach83d80832011-03-29 23:20:22 +00001917
Chris Lattner9e631da2012-01-24 09:31:43 +00001918 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001919 return emitGlobalConstantDataSequential(CDS, AP);
Eric Christopherdcc675a2012-11-20 20:34:44 +00001920
Chris Lattner9e631da2012-01-24 09:31:43 +00001921 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001922 return emitGlobalConstantArray(CVA, AP);
Jim Grosbach83d80832011-03-29 23:20:22 +00001923
Chris Lattner9e631da2012-01-24 09:31:43 +00001924 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001925 return emitGlobalConstantStruct(CVS, AP);
Chris Lattner9e631da2012-01-24 09:31:43 +00001926
Bill Wendling21e42d02012-03-20 08:56:43 +00001927 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1928 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1929 // vectors).
Chris Lattner9e631da2012-01-24 09:31:43 +00001930 if (CE->getOpcode() == Instruction::BitCast)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001931 return emitGlobalConstantImpl(CE->getOperand(0), AP);
Bill Wendling21e42d02012-03-20 08:56:43 +00001932
1933 if (Size > 8) {
1934 // If the constant expression's size is greater than 64-bits, then we have
1935 // to emit the value in chunks. Try to constant fold the value and emit it
1936 // that way.
Matt Arsenaultcee51c42013-10-03 19:50:01 +00001937 Constant *New = ConstantFoldConstantExpression(CE, DL);
Bill Wendling21e42d02012-03-20 08:56:43 +00001938 if (New && New != CE)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001939 return emitGlobalConstantImpl(New, AP);
Bill Wendling21e42d02012-03-20 08:56:43 +00001940 }
1941 }
Eric Christopherdcc675a2012-11-20 20:34:44 +00001942
Chris Lattner9e631da2012-01-24 09:31:43 +00001943 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001944 return emitGlobalConstantVector(V, AP);
Eric Christopherdcc675a2012-11-20 20:34:44 +00001945
Chris Lattner52492ac2010-01-23 06:17:14 +00001946 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1947 // thread the streamer with EmitValue.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001948 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
Chris Lattner44e05082010-04-20 06:20:21 +00001949}
1950
1951/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001952void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001953 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
Chris Lattner44e05082010-04-20 06:20:21 +00001954 if (Size)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001955 emitGlobalConstantImpl(CV, *this);
Chris Lattner44e05082010-04-20 06:20:21 +00001956 else if (MAI->hasSubsectionsViaSymbols()) {
1957 // If the global has zero size, emit a single byte so that two labels don't
1958 // look like they are at the same location.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00001959 OutStreamer.EmitIntValue(0, 1);
Chris Lattner44e05082010-04-20 06:20:21 +00001960 }
Chris Lattner1b7e2352004-08-17 06:36:49 +00001961}
Chris Lattner0264d1a2006-01-27 02:10:10 +00001962
Chris Lattnerfad86b02008-08-17 07:19:36 +00001963void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
Evan Chengd6594ae2006-09-12 21:00:35 +00001964 // Target doesn't support this yet!
Torok Edwinc23197a2009-07-14 16:55:14 +00001965 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
Evan Chengd6594ae2006-09-12 21:00:35 +00001966}
1967
Chris Lattnerdfa107e2010-04-04 18:16:38 +00001968void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1969 if (Offset > 0)
1970 OS << '+' << Offset;
1971 else if (Offset < 0)
1972 OS << Offset;
1973}
1974
Chris Lattnerc0215722010-04-04 19:25:43 +00001975//===----------------------------------------------------------------------===//
1976// Symbol Lowering Routines.
1977//===----------------------------------------------------------------------===//
1978
1979/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1980/// temporary label with the specified stem and unique ID.
1981MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
Chris Lattneraf8df262010-04-04 19:28:59 +00001982 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
Chris Lattnerc0215722010-04-04 19:25:43 +00001983 Name + Twine(ID));
1984}
1985
1986/// GetTempSymbol - Return an assembler temporary label with the specified
1987/// stem.
1988MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1989 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1990 Name);
1991}
1992
Chris Lattner66099132006-02-01 22:41:11 +00001993
Chris Lattner95175542010-02-08 23:10:08 +00001994MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
Chris Lattner3b9d6212010-03-14 17:53:23 +00001995 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
Dan Gohman8c2b5252009-10-30 01:27:03 +00001996}
1997
Chris Lattner3b9d6212010-03-14 17:53:23 +00001998MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1999 return MMI->getAddrLabelSymbol(BB);
Dan Gohman8c2b5252009-10-30 01:27:03 +00002000}
2001
Chris Lattner39248682010-01-23 05:19:23 +00002002/// GetCPISymbol - Return the symbol for the specified constant pool entry.
2003MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
Chris Lattner9b97a732010-03-30 18:10:53 +00002004 return OutContext.GetOrCreateSymbol
Chris Lattner98cdab52010-03-10 02:25:11 +00002005 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2006 + "_" + Twine(CPID));
Chris Lattner39248682010-01-23 05:19:23 +00002007}
2008
2009/// GetJTISymbol - Return the symbol for the specified jump table entry.
Bill Wendling07d31772010-06-29 22:34:52 +00002010MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2011 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
Chris Lattner7cb384d2009-09-12 23:02:08 +00002012}
2013
Chris Lattner798d1252010-01-25 21:17:10 +00002014/// GetJTSetSymbol - Return the symbol for the specified jump table .set
2015/// FIXME: privatize to AsmPrinter.
2016MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
Chris Lattner9b97a732010-03-30 18:10:53 +00002017 return OutContext.GetOrCreateSymbol
Chris Lattner98cdab52010-03-10 02:25:11 +00002018 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2019 Twine(UID) + "_set_" + Twine(MBBID));
Chris Lattner798d1252010-01-25 21:17:10 +00002020}
2021
Chris Lattner7a2ba942010-01-16 18:37:32 +00002022/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
Chris Lattnerd588b972010-01-15 23:25:11 +00002023/// global value name as its base, with the specified suffix, and where the
Chris Lattner7a2ba942010-01-16 18:37:32 +00002024/// symbol is forced to have private linkage if ForcePrivate is true.
2025MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
2026 StringRef Suffix,
2027 bool ForcePrivate) const {
Chris Lattnerd588b972010-01-15 23:25:11 +00002028 SmallString<60> NameStr;
Chris Lattner7a2ba942010-01-16 18:37:32 +00002029 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
Chris Lattnerd588b972010-01-15 23:25:11 +00002030 NameStr.append(Suffix.begin(), Suffix.end());
Chris Lattner9b97a732010-03-30 18:10:53 +00002031 return OutContext.GetOrCreateSymbol(NameStr.str());
Chris Lattnerd588b972010-01-15 23:25:11 +00002032}
2033
Chris Lattner6b04ede2010-01-15 23:18:17 +00002034/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2035/// ExternalSymbol.
2036MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2037 SmallString<60> NameStr;
2038 Mang->getNameWithPrefix(NameStr, Sym);
2039 return OutContext.GetOrCreateSymbol(NameStr.str());
Jim Grosbach83d80832011-03-29 23:20:22 +00002040}
Chris Lattner6b04ede2010-01-15 23:18:17 +00002041
Chris Lattner7cb384d2009-09-12 23:02:08 +00002042
Chris Lattner523a5082010-01-22 21:50:41 +00002043
2044/// PrintParentLoopComment - Print comments about parent loops of this one.
2045static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2046 unsigned FunctionNumber) {
2047 if (Loop == 0) return;
2048 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2049 OS.indent(Loop->getLoopDepth()*2)
2050 << "Parent Loop BB" << FunctionNumber << "_"
2051 << Loop->getHeader()->getNumber()
2052 << " Depth=" << Loop->getLoopDepth() << '\n';
2053}
2054
2055
2056/// PrintChildLoopComment - Print comments about child loops within
2057/// the loop for this basic block, with nesting.
2058static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2059 unsigned FunctionNumber) {
2060 // Add child loop information
2061 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2062 OS.indent((*CL)->getLoopDepth()*2)
2063 << "Child Loop BB" << FunctionNumber << "_"
2064 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2065 << '\n';
2066 PrintChildLoopComment(OS, *CL, FunctionNumber);
2067 }
2068}
2069
Chad Rosierc53ade22012-09-07 18:16:38 +00002070/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2071static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
Chris Lattnerdfa107e2010-04-04 18:16:38 +00002072 const MachineLoopInfo *LI,
2073 const AsmPrinter &AP) {
Chris Lattner523a5082010-01-22 21:50:41 +00002074 // Add loop depth information
2075 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2076 if (Loop == 0) return;
Jim Grosbach83d80832011-03-29 23:20:22 +00002077
Chris Lattner523a5082010-01-22 21:50:41 +00002078 MachineBasicBlock *Header = Loop->getHeader();
2079 assert(Header && "No header for loop");
Jim Grosbach83d80832011-03-29 23:20:22 +00002080
Chris Lattner523a5082010-01-22 21:50:41 +00002081 // If this block is not a loop header, just print out what is the loop header
2082 // and return.
2083 if (Header != &MBB) {
2084 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2085 Twine(AP.getFunctionNumber())+"_" +
2086 Twine(Loop->getHeader()->getNumber())+
2087 " Depth="+Twine(Loop->getLoopDepth()));
2088 return;
2089 }
Jim Grosbach83d80832011-03-29 23:20:22 +00002090
Chris Lattner523a5082010-01-22 21:50:41 +00002091 // Otherwise, it is a loop header. Print out information about child and
2092 // parent loops.
2093 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
Jim Grosbach83d80832011-03-29 23:20:22 +00002094
2095 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2096
Chris Lattner523a5082010-01-22 21:50:41 +00002097 OS << "=>";
2098 OS.indent(Loop->getLoopDepth()*2-2);
Jim Grosbach83d80832011-03-29 23:20:22 +00002099
Chris Lattner523a5082010-01-22 21:50:41 +00002100 OS << "This ";
2101 if (Loop->empty())
2102 OS << "Inner ";
2103 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
Jim Grosbach83d80832011-03-29 23:20:22 +00002104
Chris Lattner523a5082010-01-22 21:50:41 +00002105 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2106}
2107
2108
Chris Lattner70a54c02009-09-13 18:25:37 +00002109/// EmitBasicBlockStart - This method prints the label for the specified
2110/// MachineBasicBlock, an alignment (if present) and a comment describing
2111/// it if appropriate.
Chris Lattner662316c2009-09-14 03:15:54 +00002112void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
Dan Gohmanb1cac332009-10-30 01:34:35 +00002113 // Emit an alignment directive for this block, if needed.
Chris Lattner70a54c02009-09-13 18:25:37 +00002114 if (unsigned Align = MBB->getAlignment())
Jakob Stoklund Olesen8c741b82011-12-06 01:26:19 +00002115 EmitAlignment(Align);
Evan Chengfb8075d2008-02-28 00:43:03 +00002116
Chris Lattner999aee22010-03-16 00:29:39 +00002117 // If the block has its address taken, emit any labels that were used to
2118 // reference the block. It is possible that there is more than one label
2119 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2120 // the references were generated.
Dan Gohman8c2b5252009-10-30 01:27:03 +00002121 if (MBB->hasAddressTaken()) {
Chris Lattner213168b2010-01-20 07:24:05 +00002122 const BasicBlock *BB = MBB->getBasicBlock();
Chris Lattner3f53c832010-04-04 18:52:31 +00002123 if (isVerbose())
Chris Lattner999aee22010-03-16 00:29:39 +00002124 OutStreamer.AddComment("Block address taken");
Jim Grosbach83d80832011-03-29 23:20:22 +00002125
Chris Lattner999aee22010-03-16 00:29:39 +00002126 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2127
2128 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2129 OutStreamer.EmitLabel(Syms[i]);
Dan Gohman8c2b5252009-10-30 01:27:03 +00002130 }
2131
Jakob Stoklund Olesenc511c282012-03-06 22:27:13 +00002132 // Print some verbose block comments.
2133 if (isVerbose()) {
2134 if (const BasicBlock *BB = MBB->getBasicBlock())
2135 if (BB->hasName())
2136 OutStreamer.AddComment("%" + BB->getName());
Chad Rosierc53ade22012-09-07 18:16:38 +00002137 emitBasicBlockLoopComments(*MBB, LI, *this);
Jakob Stoklund Olesenc511c282012-03-06 22:27:13 +00002138 }
2139
Dan Gohmanb1cac332009-10-30 01:34:35 +00002140 // Print the main label for the block.
Chris Lattner0a3f3992010-02-17 18:52:56 +00002141 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
Chris Lattner3f53c832010-04-04 18:52:31 +00002142 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
Chris Lattner58bc4dd2010-04-03 22:12:35 +00002143 // NOTE: Want this comment at start of line, don't emit with AddComment.
2144 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2145 Twine(MBB->getNumber()) + ":");
Chris Lattner0fd90fd2010-01-22 19:52:01 +00002146 }
Dan Gohmane3cc3f32009-10-06 17:38:38 +00002147 } else {
Chris Lattner1b2eb0e2010-03-13 21:04:28 +00002148 OutStreamer.EmitLabel(MBB->getSymbol());
Dan Gohmane3cc3f32009-10-06 17:38:38 +00002149 }
Nate Begeman37efe672006-04-22 18:53:45 +00002150}
Nate Begeman52a51e382006-08-12 21:29:52 +00002151
Stuart Hastings5129bde2011-02-23 02:27:05 +00002152void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2153 bool IsDefinition) const {
Chris Lattner152a29b2010-01-23 06:53:23 +00002154 MCSymbolAttr Attr = MCSA_Invalid;
Jim Grosbach83d80832011-03-29 23:20:22 +00002155
Chris Lattner152a29b2010-01-23 06:53:23 +00002156 switch (Visibility) {
2157 default: break;
2158 case GlobalValue::HiddenVisibility:
Stuart Hastings5129bde2011-02-23 02:27:05 +00002159 if (IsDefinition)
2160 Attr = MAI->getHiddenVisibilityAttr();
2161 else
2162 Attr = MAI->getHiddenDeclarationVisibilityAttr();
Chris Lattner152a29b2010-01-23 06:53:23 +00002163 break;
2164 case GlobalValue::ProtectedVisibility:
2165 Attr = MAI->getProtectedVisibilityAttr();
2166 break;
Chris Lattner53d4d782010-01-15 23:38:51 +00002167 }
Chris Lattner152a29b2010-01-23 06:53:23 +00002168
2169 if (Attr != MCSA_Invalid)
2170 OutStreamer.EmitSymbolAttribute(Sym, Attr);
Chris Lattner53d4d782010-01-15 23:38:51 +00002171}
2172
Chris Lattner0a3f3992010-02-17 18:52:56 +00002173/// isBlockOnlyReachableByFallthough - Return true if the basic block has
2174/// exactly one predecessor and the control transfer mechanism between
2175/// the predecessor and this block is a fall-through.
Chris Lattnere00b59f2010-04-04 17:57:56 +00002176bool AsmPrinter::
2177isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
Chris Lattner0a3f3992010-02-17 18:52:56 +00002178 // If this is a landing pad, it isn't a fall through. If it has no preds,
2179 // then nothing falls through to it.
2180 if (MBB->isLandingPad() || MBB->pred_empty())
2181 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002182
Chris Lattner0a3f3992010-02-17 18:52:56 +00002183 // If there isn't exactly one predecessor, it can't be a fall through.
2184 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2185 ++PI2;
2186 if (PI2 != MBB->pred_end())
2187 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002188
Chris Lattner0a3f3992010-02-17 18:52:56 +00002189 // The predecessor has to be immediately before this block.
Eli Friedman0fc30152011-06-14 19:30:33 +00002190 MachineBasicBlock *Pred = *PI;
Jim Grosbach83d80832011-03-29 23:20:22 +00002191
Chris Lattner0a3f3992010-02-17 18:52:56 +00002192 if (!Pred->isLayoutSuccessor(MBB))
2193 return false;
Jim Grosbach83d80832011-03-29 23:20:22 +00002194
Chris Lattner0a3f3992010-02-17 18:52:56 +00002195 // If the block is completely empty, then it definitely does fall through.
2196 if (Pred->empty())
2197 return true;
Jim Grosbach83d80832011-03-29 23:20:22 +00002198
Eli Friedman0fc30152011-06-14 19:30:33 +00002199 // Check the terminators in the previous blocks
2200 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2201 IE = Pred->end(); II != IE; ++II) {
2202 MachineInstr &MI = *II;
2203
2204 // If it is not a simple branch, we are in a table somewhere.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00002205 if (!MI.isBranch() || MI.isIndirectBranch())
Eli Friedman0fc30152011-06-14 19:30:33 +00002206 return false;
2207
2208 // If we are the operands of one of the branches, this is not
2209 // a fall through.
2210 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2211 OE = MI.operands_end(); OI != OE; ++OI) {
2212 const MachineOperand& OP = *OI;
Rafael Espindolaaeb6da42011-06-15 21:00:28 +00002213 if (OP.isJTI())
2214 return false;
Eli Friedman0fc30152011-06-14 19:30:33 +00002215 if (OP.isMBB() && OP.getMBB() == MBB)
2216 return false;
2217 }
2218 }
2219
2220 return true;
Chris Lattner0a3f3992010-02-17 18:52:56 +00002221}
2222
2223
2224
Gordon Henriksen5eca0752008-08-17 18:44:35 +00002225GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2226 if (!S->usesMetadata())
Gordon Henriksenc317a602008-08-17 12:08:44 +00002227 return 0;
Chris Lattnere00b59f2010-04-04 17:57:56 +00002228
2229 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2230 gcp_map_type::iterator GCPI = GCMap.find(S);
2231 if (GCPI != GCMap.end())
Gordon Henriksenc317a602008-08-17 12:08:44 +00002232 return GCPI->second;
Jim Grosbach83d80832011-03-29 23:20:22 +00002233
Gordon Henriksen5eca0752008-08-17 18:44:35 +00002234 const char *Name = S->getName().c_str();
Jim Grosbach83d80832011-03-29 23:20:22 +00002235
Gordon Henriksenc317a602008-08-17 12:08:44 +00002236 for (GCMetadataPrinterRegistry::iterator
2237 I = GCMetadataPrinterRegistry::begin(),
2238 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2239 if (strcmp(Name, I->getName()) == 0) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00002240 GCMetadataPrinter *GMP = I->instantiate();
2241 GMP->S = S;
Chris Lattnere00b59f2010-04-04 17:57:56 +00002242 GCMap.insert(std::make_pair(S, GMP));
Gordon Henriksen5eca0752008-08-17 18:44:35 +00002243 return GMP;
Gordon Henriksenc317a602008-08-17 12:08:44 +00002244 }
Jim Grosbach83d80832011-03-29 23:20:22 +00002245
Chris Lattner75361b62010-04-07 22:58:41 +00002246 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
Gordon Henriksenc317a602008-08-17 12:08:44 +00002247}