Deleted Added
full compact
AsmPrinter.cpp (261991) AsmPrinter.cpp (262613)
1//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "asm-printer"
15#include "llvm/CodeGen/AsmPrinter.h"
16#include "DwarfDebug.h"
17#include "DwarfException.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/ConstantFolding.h"
21#include "llvm/Assembly/Writer.h"
22#include "llvm/CodeGen/GCMetadataPrinter.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
1//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AsmPrinter class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "asm-printer"
15#include "llvm/CodeGen/AsmPrinter.h"
16#include "DwarfDebug.h"
17#include "DwarfException.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/ConstantFolding.h"
21#include "llvm/Assembly/Writer.h"
22#include "llvm/CodeGen/GCMetadataPrinter.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineInstrBundle.h"
26#include "llvm/CodeGen/MachineJumpTableInfo.h"
27#include "llvm/CodeGen/MachineLoopInfo.h"
28#include "llvm/CodeGen/MachineModuleInfo.h"
29#include "llvm/DebugInfo.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Operator.h"
33#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
35#include "llvm/MC/MCExpr.h"
36#include "llvm/MC/MCInst.h"
37#include "llvm/MC/MCSection.h"
38#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/Format.h"
42#include "llvm/Support/MathExtras.h"
43#include "llvm/Support/Timer.h"
44#include "llvm/Target/Mangler.h"
45#include "llvm/Target/TargetFrameLowering.h"
46#include "llvm/Target/TargetInstrInfo.h"
47#include "llvm/Target/TargetLowering.h"
48#include "llvm/Target/TargetLoweringObjectFile.h"
49#include "llvm/Target/TargetOptions.h"
50#include "llvm/Target/TargetRegisterInfo.h"
51#include "llvm/Transforms/Utils/GlobalStatus.h"
52using namespace llvm;
53
54static const char *const DWARFGroupName = "DWARF Emission";
55static const char *const DbgTimerName = "DWARF Debug Writer";
56static const char *const EHTimerName = "DWARF Exception Writer";
57
58STATISTIC(EmittedInsts, "Number of machine instrs printed");
59
60char AsmPrinter::ID = 0;
61
62typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
63static gcp_map_type &getGCMap(void *&P) {
64 if (P == 0)
65 P = new gcp_map_type();
66 return *(gcp_map_type*)P;
67}
68
69
70/// getGVAlignmentLog2 - Return the alignment to use for the specified global
71/// value in log2 form. This rounds up to the preferred alignment if possible
72/// and legal.
73static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
74 unsigned InBits = 0) {
75 unsigned NumBits = 0;
76 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
77 NumBits = TD.getPreferredAlignmentLog(GVar);
78
79 // If InBits is specified, round it to it.
80 if (InBits > NumBits)
81 NumBits = InBits;
82
83 // If the GV has a specified alignment, take it into account.
84 if (GV->getAlignment() == 0)
85 return NumBits;
86
87 unsigned GVAlign = Log2_32(GV->getAlignment());
88
89 // If the GVAlign is larger than NumBits, or if we are required to obey
90 // NumBits because the GV has an assigned section, obey it.
91 if (GVAlign > NumBits || GV->hasSection())
92 NumBits = GVAlign;
93 return NumBits;
94}
95
96AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
97 : MachineFunctionPass(ID),
98 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
99 OutContext(Streamer.getContext()),
100 OutStreamer(Streamer),
101 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
102 DD = 0; DE = 0; MMI = 0; LI = 0; MF = 0;
103 CurrentFnSym = CurrentFnSymForSize = 0;
104 GCMetadataPrinters = 0;
105 VerboseAsm = Streamer.isVerboseAsm();
106}
107
108AsmPrinter::~AsmPrinter() {
109 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
110
111 if (GCMetadataPrinters != 0) {
112 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
113
114 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
115 delete I->second;
116 delete &GCMap;
117 GCMetadataPrinters = 0;
118 }
119
120 delete &OutStreamer;
121}
122
123/// getFunctionNumber - Return a unique ID for the current function.
124///
125unsigned AsmPrinter::getFunctionNumber() const {
126 return MF->getFunctionNumber();
127}
128
129const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
130 return TM.getTargetLowering()->getObjFileLowering();
131}
132
133/// getDataLayout - Return information about data layout.
134const DataLayout &AsmPrinter::getDataLayout() const {
135 return *TM.getDataLayout();
136}
137
138StringRef AsmPrinter::getTargetTriple() const {
139 return TM.getTargetTriple();
140}
141
142/// getCurrentSection() - Return the current section we are emitting to.
143const MCSection *AsmPrinter::getCurrentSection() const {
144 return OutStreamer.getCurrentSection().first;
145}
146
147
148
149void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
150 AU.setPreservesAll();
151 MachineFunctionPass::getAnalysisUsage(AU);
152 AU.addRequired<MachineModuleInfo>();
153 AU.addRequired<GCModuleInfo>();
154 if (isVerbose())
155 AU.addRequired<MachineLoopInfo>();
156}
157
158bool AsmPrinter::doInitialization(Module &M) {
159 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
160 MMI->AnalyzeModule(M);
161
162 // Initialize TargetLoweringObjectFile.
163 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
164 .Initialize(OutContext, TM);
165
166 OutStreamer.InitStreamer();
167
168 Mang = new Mangler(&TM);
169
170 // Allow the target to emit any magic that it wants at the start of the file.
171 EmitStartOfAsmFile(M);
172
173 // Very minimal debug info. It is ignored if we emit actual debug info. If we
174 // don't, this at least helps the user find where a global came from.
175 if (MAI->hasSingleParameterDotFile()) {
176 // .file "foo.c"
177 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
178 }
179
180 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
181 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
182 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
183 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
184 MP->beginAssembly(*this);
185
186 // Emit module-level inline asm if it exists.
187 if (!M.getModuleInlineAsm().empty()) {
188 OutStreamer.AddComment("Start of file scope inline assembly");
189 OutStreamer.AddBlankLine();
190 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
191 OutStreamer.AddComment("End of file scope inline assembly");
192 OutStreamer.AddBlankLine();
193 }
194
195 if (MAI->doesSupportDebugInformation())
196 DD = new DwarfDebug(this, &M);
197
198 switch (MAI->getExceptionHandlingType()) {
199 case ExceptionHandling::None:
200 return false;
201 case ExceptionHandling::SjLj:
202 case ExceptionHandling::DwarfCFI:
203 DE = new DwarfCFIException(this);
204 return false;
205 case ExceptionHandling::ARM:
206 DE = new ARMException(this);
207 return false;
208 case ExceptionHandling::Win64:
209 DE = new Win64Exception(this);
210 return false;
211 }
212
213 llvm_unreachable("Unknown exception type.");
214}
215
216void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
217 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
218 switch (Linkage) {
219 case GlobalValue::CommonLinkage:
220 case GlobalValue::LinkOnceAnyLinkage:
221 case GlobalValue::LinkOnceODRLinkage:
222 case GlobalValue::WeakAnyLinkage:
223 case GlobalValue::WeakODRLinkage:
224 case GlobalValue::LinkerPrivateWeakLinkage:
225 if (MAI->getWeakDefDirective() != 0) {
226 // .globl _foo
227 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
228
229 bool CanBeHidden = false;
230
231 if (Linkage == GlobalValue::LinkOnceODRLinkage) {
232 if (GV->hasUnnamedAddr()) {
233 CanBeHidden = true;
234 } else {
235 GlobalStatus GS;
236 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
237 CanBeHidden = true;
238 }
239 }
240
241 if (!CanBeHidden)
242 // .weak_definition _foo
243 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
244 else
245 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
246 } else if (MAI->getLinkOnceDirective() != 0) {
247 // .globl _foo
248 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
249 //NOTE: linkonce is handled by the section the symbol was assigned to.
250 } else {
251 // .weak _foo
252 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
253 }
254 return;
255 case GlobalValue::DLLExportLinkage:
256 case GlobalValue::AppendingLinkage:
257 // FIXME: appending linkage variables should go into a section of
258 // their name or something. For now, just emit them as external.
259 case GlobalValue::ExternalLinkage:
260 // If external or appending, declare as a global symbol.
261 // .globl _foo
262 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
263 return;
264 case GlobalValue::PrivateLinkage:
265 case GlobalValue::InternalLinkage:
266 case GlobalValue::LinkerPrivateLinkage:
267 return;
268 case GlobalValue::AvailableExternallyLinkage:
269 llvm_unreachable("Should never emit this");
270 case GlobalValue::DLLImportLinkage:
271 case GlobalValue::ExternalWeakLinkage:
272 llvm_unreachable("Don't know how to emit these");
273 }
274 llvm_unreachable("Unknown linkage type!");
275}
276
277MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
278 return getObjFileLowering().getSymbol(*Mang, GV);
279}
280
281/// EmitGlobalVariable - Emit the specified global variable to the .s file.
282void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
283 if (GV->hasInitializer()) {
284 // Check to see if this is a special global used by LLVM, if so, emit it.
285 if (EmitSpecialLLVMGlobal(GV))
286 return;
287
288 if (isVerbose()) {
289 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
290 /*PrintType=*/false, GV->getParent());
291 OutStreamer.GetCommentOS() << '\n';
292 }
293 }
294
295 MCSymbol *GVSym = getSymbol(GV);
296 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
297
298 if (!GV->hasInitializer()) // External globals require no extra code.
299 return;
300
301 if (MAI->hasDotTypeDotSizeDirective())
302 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
303
304 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
305
306 const DataLayout *DL = TM.getDataLayout();
307 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
308
309 // If the alignment is specified, we *must* obey it. Overaligning a global
310 // with a specified alignment is a prompt way to break globals emitted to
311 // sections and expected to be contiguous (e.g. ObjC metadata).
312 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
313
314 if (DD)
315 DD->setSymbolSize(GVSym, Size);
316
317 // Handle common and BSS local symbols (.lcomm).
318 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
319 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
320 unsigned Align = 1 << AlignLog;
321
322 // Handle common symbols.
323 if (GVKind.isCommon()) {
324 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
325 Align = 0;
326
327 // .comm _foo, 42, 4
328 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
329 return;
330 }
331
332 // Handle local BSS symbols.
333 if (MAI->hasMachoZeroFillDirective()) {
334 const MCSection *TheSection =
335 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
336 // .zerofill __DATA, __bss, _foo, 400, 5
337 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
338 return;
339 }
340
341 // Use .lcomm only if it supports user-specified alignment.
342 // Otherwise, while it would still be correct to use .lcomm in some
343 // cases (e.g. when Align == 1), the external assembler might enfore
344 // some -unknown- default alignment behavior, which could cause
345 // spurious differences between external and integrated assembler.
346 // Prefer to simply fall back to .local / .comm in this case.
347 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
348 // .lcomm _foo, 42
349 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
350 return;
351 }
352
353 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
354 Align = 0;
355
356 // .local _foo
357 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
358 // .comm _foo, 42, 4
359 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
360 return;
361 }
362
363 const MCSection *TheSection =
364 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
365
366 // Handle the zerofill directive on darwin, which is a special form of BSS
367 // emission.
368 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
369 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
370
371 // .globl _foo
372 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
373 // .zerofill __DATA, __common, _foo, 400, 5
374 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
375 return;
376 }
377
378 // Handle thread local data for mach-o which requires us to output an
379 // additional structure of data and mangle the original symbol so that we
380 // can reference it later.
381 //
382 // TODO: This should become an "emit thread local global" method on TLOF.
383 // All of this macho specific stuff should be sunk down into TLOFMachO and
384 // stuff like "TLSExtraDataSection" should no longer be part of the parent
385 // TLOF class. This will also make it more obvious that stuff like
386 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
387 // specific code.
388 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
389 // Emit the .tbss symbol
390 MCSymbol *MangSym =
391 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
392
393 if (GVKind.isThreadBSS()) {
394 TheSection = getObjFileLowering().getTLSBSSSection();
395 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
396 } else if (GVKind.isThreadData()) {
397 OutStreamer.SwitchSection(TheSection);
398
399 EmitAlignment(AlignLog, GV);
400 OutStreamer.EmitLabel(MangSym);
401
402 EmitGlobalConstant(GV->getInitializer());
403 }
404
405 OutStreamer.AddBlankLine();
406
407 // Emit the variable struct for the runtime.
408 const MCSection *TLVSect
409 = getObjFileLowering().getTLSExtraDataSection();
410
411 OutStreamer.SwitchSection(TLVSect);
412 // Emit the linkage here.
413 EmitLinkage(GV, GVSym);
414 OutStreamer.EmitLabel(GVSym);
415
416 // Three pointers in size:
417 // - __tlv_bootstrap - used to make sure support exists
418 // - spare pointer, used when mapped by the runtime
419 // - pointer to mangled symbol above with initializer
420 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
421 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
422 PtrSize);
423 OutStreamer.EmitIntValue(0, PtrSize);
424 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
425
426 OutStreamer.AddBlankLine();
427 return;
428 }
429
430 OutStreamer.SwitchSection(TheSection);
431
432 EmitLinkage(GV, GVSym);
433 EmitAlignment(AlignLog, GV);
434
435 OutStreamer.EmitLabel(GVSym);
436
437 EmitGlobalConstant(GV->getInitializer());
438
439 if (MAI->hasDotTypeDotSizeDirective())
440 // .size foo, 42
441 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
442
443 OutStreamer.AddBlankLine();
444}
445
446/// EmitFunctionHeader - This method emits the header for the current
447/// function.
448void AsmPrinter::EmitFunctionHeader() {
449 // Print out constants referenced by the function
450 EmitConstantPool();
451
452 // Print the 'header' of function.
453 const Function *F = MF->getFunction();
454
455 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
456 EmitVisibility(CurrentFnSym, F->getVisibility());
457
458 EmitLinkage(F, CurrentFnSym);
459 EmitAlignment(MF->getAlignment(), F);
460
461 if (MAI->hasDotTypeDotSizeDirective())
462 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
463
464 if (isVerbose()) {
465 WriteAsOperand(OutStreamer.GetCommentOS(), F,
466 /*PrintType=*/false, F->getParent());
467 OutStreamer.GetCommentOS() << '\n';
468 }
469
470 // Emit the CurrentFnSym. This is a virtual function to allow targets to
471 // do their wild and crazy things as required.
472 EmitFunctionEntryLabel();
473
474 // If the function had address-taken blocks that got deleted, then we have
475 // references to the dangling symbols. Emit them at the start of the function
476 // so that we don't get references to undefined symbols.
477 std::vector<MCSymbol*> DeadBlockSyms;
478 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
479 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
480 OutStreamer.AddComment("Address taken block that was later removed");
481 OutStreamer.EmitLabel(DeadBlockSyms[i]);
482 }
483
484 // Emit pre-function debug and/or EH information.
485 if (DE) {
486 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
487 DE->BeginFunction(MF);
488 }
489 if (DD) {
490 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
491 DD->beginFunction(MF);
492 }
493
494 // Emit the prefix data.
495 if (F->hasPrefixData())
496 EmitGlobalConstant(F->getPrefixData());
497}
498
499/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
500/// function. This can be overridden by targets as required to do custom stuff.
501void AsmPrinter::EmitFunctionEntryLabel() {
502 // The function label could have already been emitted if two symbols end up
503 // conflicting due to asm renaming. Detect this and emit an error.
504 if (CurrentFnSym->isUndefined())
505 return OutStreamer.EmitLabel(CurrentFnSym);
506
507 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
508 "' label emitted multiple times to assembly file");
509}
510
511/// emitComments - Pretty-print comments for instructions.
512static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
513 const MachineFunction *MF = MI.getParent()->getParent();
514 const TargetMachine &TM = MF->getTarget();
515
516 // Check for spills and reloads
517 int FI;
518
519 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
520
521 // We assume a single instruction only has a spill or reload, not
522 // both.
523 const MachineMemOperand *MMO;
524 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
525 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
526 MMO = *MI.memoperands_begin();
527 CommentOS << MMO->getSize() << "-byte Reload\n";
528 }
529 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
530 if (FrameInfo->isSpillSlotObjectIndex(FI))
531 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
532 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
533 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
534 MMO = *MI.memoperands_begin();
535 CommentOS << MMO->getSize() << "-byte Spill\n";
536 }
537 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
538 if (FrameInfo->isSpillSlotObjectIndex(FI))
539 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
540 }
541
542 // Check for spill-induced copies
543 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
544 CommentOS << " Reload Reuse\n";
545}
546
547/// emitImplicitDef - This method emits the specified machine instruction
548/// that is an implicit def.
549void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
550 unsigned RegNo = MI->getOperand(0).getReg();
551 OutStreamer.AddComment(Twine("implicit-def: ") +
552 TM.getRegisterInfo()->getName(RegNo));
553 OutStreamer.AddBlankLine();
554}
555
556static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
557 std::string Str = "kill:";
558 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
559 const MachineOperand &Op = MI->getOperand(i);
560 assert(Op.isReg() && "KILL instruction must have only register operands");
561 Str += ' ';
562 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
563 Str += (Op.isDef() ? "<def>" : "<kill>");
564 }
565 AP.OutStreamer.AddComment(Str);
566 AP.OutStreamer.AddBlankLine();
567}
568
569/// emitDebugValueComment - This method handles the target-independent form
570/// of DBG_VALUE, returning true if it was able to do so. A false return
571/// means the target will need to handle MI in EmitInstruction.
572static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
573 // This code handles only the 3-operand target-independent form.
574 if (MI->getNumOperands() != 3)
575 return false;
576
577 SmallString<128> Str;
578 raw_svector_ostream OS(Str);
579 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
580
581 // cast away const; DIetc do not take const operands for some reason.
582 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
583 if (V.getContext().isSubprogram()) {
584 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
585 if (!Name.empty())
586 OS << Name << ":";
587 }
588 OS << V.getName() << " <- ";
589
590 // The second operand is only an offset if it's an immediate.
591 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
592 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
593
594 // Register or immediate value. Register 0 means undef.
595 if (MI->getOperand(0).isFPImm()) {
596 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
597 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
598 OS << (double)APF.convertToFloat();
599 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
600 OS << APF.convertToDouble();
601 } else {
602 // There is no good way to print long double. Convert a copy to
603 // double. Ah well, it's only a comment.
604 bool ignored;
605 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
606 &ignored);
607 OS << "(long double) " << APF.convertToDouble();
608 }
609 } else if (MI->getOperand(0).isImm()) {
610 OS << MI->getOperand(0).getImm();
611 } else if (MI->getOperand(0).isCImm()) {
612 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
613 } else {
614 unsigned Reg;
615 if (MI->getOperand(0).isReg()) {
616 Reg = MI->getOperand(0).getReg();
617 } else {
618 assert(MI->getOperand(0).isFI() && "Unknown operand type");
619 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
620 Offset += TFI->getFrameIndexReference(*AP.MF,
621 MI->getOperand(0).getIndex(), Reg);
622 Deref = true;
623 }
624 if (Reg == 0) {
625 // Suppress offset, it is not meaningful here.
626 OS << "undef";
627 // NOTE: Want this comment at start of line, don't emit with AddComment.
628 AP.OutStreamer.EmitRawText(OS.str());
629 return true;
630 }
631 if (Deref)
632 OS << '[';
633 OS << AP.TM.getRegisterInfo()->getName(Reg);
634 }
635
636 if (Deref)
637 OS << '+' << Offset << ']';
638
639 // NOTE: Want this comment at start of line, don't emit with AddComment.
640 AP.OutStreamer.EmitRawText(OS.str());
641 return true;
642}
643
644AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
645 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
646 MF->getFunction()->needsUnwindTableEntry())
647 return CFI_M_EH;
648
649 if (MMI->hasDebugInfo())
650 return CFI_M_Debug;
651
652 return CFI_M_None;
653}
654
655bool AsmPrinter::needsSEHMoves() {
656 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
657 MF->getFunction()->needsUnwindTableEntry();
658}
659
660bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
661 return MAI->doesDwarfUseRelocationsAcrossSections();
662}
663
664void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
665 const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
666
667 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
668 return;
669
670 if (needsCFIMoves() == CFI_M_None)
671 return;
672
673 if (MMI->getCompactUnwindEncoding() != 0)
674 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
675
676 const MachineModuleInfo &MMI = MF->getMMI();
677 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
678 bool FoundOne = false;
679 (void)FoundOne;
680 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
681 E = Instrs.end(); I != E; ++I) {
682 if (I->getLabel() == Label) {
683 emitCFIInstruction(*I);
684 FoundOne = true;
685 }
686 }
687 assert(FoundOne);
688}
689
690/// EmitFunctionBody - This method emits the body and trailer for a
691/// function.
692void AsmPrinter::EmitFunctionBody() {
693 // Emit target-specific gunk before the function body.
694 EmitFunctionBodyStart();
695
696 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
697
698 // Print out code for the function.
699 bool HasAnyRealCode = false;
700 const MachineInstr *LastMI = 0;
701 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
702 I != E; ++I) {
703 // Print a label for the basic block.
704 EmitBasicBlockStart(I);
705 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
706 II != IE; ++II) {
707 LastMI = II;
708
709 // Print the assembly for the instruction.
710 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
711 !II->isDebugValue()) {
712 HasAnyRealCode = true;
713 ++EmittedInsts;
714 }
715
716 if (ShouldPrintDebugScopes) {
717 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
718 DD->beginInstruction(II);
719 }
720
721 if (isVerbose())
722 emitComments(*II, OutStreamer.GetCommentOS());
723
724 switch (II->getOpcode()) {
725 case TargetOpcode::PROLOG_LABEL:
726 emitPrologLabel(*II);
727 break;
728
729 case TargetOpcode::EH_LABEL:
730 case TargetOpcode::GC_LABEL:
731 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
732 break;
733 case TargetOpcode::INLINEASM:
734 EmitInlineAsm(II);
735 break;
736 case TargetOpcode::DBG_VALUE:
737 if (isVerbose()) {
738 if (!emitDebugValueComment(II, *this))
739 EmitInstruction(II);
740 }
741 break;
742 case TargetOpcode::IMPLICIT_DEF:
743 if (isVerbose()) emitImplicitDef(II);
744 break;
745 case TargetOpcode::KILL:
746 if (isVerbose()) emitKill(II, *this);
747 break;
748 default:
749 if (!TM.hasMCUseLoc())
750 MCLineEntry::Make(&OutStreamer, getCurrentSection());
751
752 EmitInstruction(II);
753 break;
754 }
755
756 if (ShouldPrintDebugScopes) {
757 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
758 DD->endInstruction(II);
759 }
760 }
761 }
762
763 // If the last instruction was a prolog label, then we have a situation where
764 // we emitted a prolog but no function body. This results in the ending prolog
765 // label equaling the end of function label and an invalid "row" in the
766 // FDE. We need to emit a noop in this situation so that the FDE's rows are
767 // valid.
768 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
769
770 // If the function is empty and the object file uses .subsections_via_symbols,
771 // then we need to emit *something* to the function body to prevent the
772 // labels from collapsing together. Just emit a noop.
773 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
774 MCInst Noop;
775 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
776 if (Noop.getOpcode()) {
777 OutStreamer.AddComment("avoids zero-length function");
778 OutStreamer.EmitInstruction(Noop);
779 } else // Target not mc-ized yet.
780 OutStreamer.EmitRawText(StringRef("\tnop\n"));
781 }
782
783 const Function *F = MF->getFunction();
784 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
785 const BasicBlock *BB = i;
786 if (!BB->hasAddressTaken())
787 continue;
788 MCSymbol *Sym = GetBlockAddressSymbol(BB);
789 if (Sym->isDefined())
790 continue;
791 OutStreamer.AddComment("Address of block that was removed by CodeGen");
792 OutStreamer.EmitLabel(Sym);
793 }
794
795 // Emit target-specific gunk after the function body.
796 EmitFunctionBodyEnd();
797
798 // If the target wants a .size directive for the size of the function, emit
799 // it.
800 if (MAI->hasDotTypeDotSizeDirective()) {
801 // Create a symbol for the end of function, so we can get the size as
802 // difference between the function label and the temp label.
803 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
804 OutStreamer.EmitLabel(FnEndLabel);
805
806 const MCExpr *SizeExp =
807 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
808 MCSymbolRefExpr::Create(CurrentFnSymForSize,
809 OutContext),
810 OutContext);
811 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
812 }
813
814 // Emit post-function debug information.
815 if (DD) {
816 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
817 DD->endFunction(MF);
818 }
819 if (DE) {
820 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
821 DE->EndFunction();
822 }
823 MMI->EndFunction();
824
825 // Print out jump tables referenced by the function.
826 EmitJumpTableInfo();
827
828 OutStreamer.AddBlankLine();
829}
830
831/// EmitDwarfRegOp - Emit dwarf register operation.
832void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
833 bool Indirect) const {
834 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
835 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
836
837 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
838 ++SR) {
839 Reg = TRI->getDwarfRegNum(*SR, false);
840 // FIXME: Get the bit range this register uses of the superregister
841 // so that we can produce a DW_OP_bit_piece
842 }
843
844 // FIXME: Handle cases like a super register being encoded as
845 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
846
847 // FIXME: We have no reasonable way of handling errors in here. The
848 // caller might be in the middle of an dwarf expression. We should
849 // probably assert that Reg >= 0 once debug info generation is more mature.
850
851 if (MLoc.isIndirect() || Indirect) {
852 if (Reg < 32) {
853 OutStreamer.AddComment(
854 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
855 EmitInt8(dwarf::DW_OP_breg0 + Reg);
856 } else {
857 OutStreamer.AddComment("DW_OP_bregx");
858 EmitInt8(dwarf::DW_OP_bregx);
859 OutStreamer.AddComment(Twine(Reg));
860 EmitULEB128(Reg);
861 }
862 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
863 if (MLoc.isIndirect() && Indirect)
864 EmitInt8(dwarf::DW_OP_deref);
865 } else {
866 if (Reg < 32) {
867 OutStreamer.AddComment(
868 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
869 EmitInt8(dwarf::DW_OP_reg0 + Reg);
870 } else {
871 OutStreamer.AddComment("DW_OP_regx");
872 EmitInt8(dwarf::DW_OP_regx);
873 OutStreamer.AddComment(Twine(Reg));
874 EmitULEB128(Reg);
875 }
876 }
877
878 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
879}
880
881bool AsmPrinter::doFinalization(Module &M) {
882 // Emit global variables.
883 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
884 I != E; ++I)
885 EmitGlobalVariable(I);
886
887 // Emit visibility info for declarations
888 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
889 const Function &F = *I;
890 if (!F.isDeclaration())
891 continue;
892 GlobalValue::VisibilityTypes V = F.getVisibility();
893 if (V == GlobalValue::DefaultVisibility)
894 continue;
895
896 MCSymbol *Name = getSymbol(&F);
897 EmitVisibility(Name, V, false);
898 }
899
900 // Emit module flags.
901 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
902 M.getModuleFlagsMetadata(ModuleFlags);
903 if (!ModuleFlags.empty())
904 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
905
906 // Make sure we wrote out everything we need.
907 OutStreamer.Flush();
908
909 // Finalize debug and EH information.
910 if (DE) {
911 {
912 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
913 DE->EndModule();
914 }
915 delete DE; DE = 0;
916 }
917 if (DD) {
918 {
919 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
920 DD->endModule();
921 }
922 delete DD; DD = 0;
923 }
924
925 // If the target wants to know about weak references, print them all.
926 if (MAI->getWeakRefDirective()) {
927 // FIXME: This is not lazy, it would be nice to only print weak references
928 // to stuff that is actually used. Note that doing so would require targets
929 // to notice uses in operands (due to constant exprs etc). This should
930 // happen with the MC stuff eventually.
931
932 // Print out module-level global variables here.
933 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
934 I != E; ++I) {
935 if (!I->hasExternalWeakLinkage()) continue;
936 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
937 }
938
939 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
940 if (!I->hasExternalWeakLinkage()) continue;
941 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
942 }
943 }
944
945 if (MAI->hasSetDirective()) {
946 OutStreamer.AddBlankLine();
947 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
948 I != E; ++I) {
949 MCSymbol *Name = getSymbol(I);
950
951 const GlobalValue *GV = I->getAliasedGlobal();
952 if (GV->isDeclaration()) {
953 report_fatal_error(Name->getName() +
954 ": Target doesn't support aliases to declarations");
955 }
956
957 MCSymbol *Target = getSymbol(GV);
958
959 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
960 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
961 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
962 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
963 else
964 assert(I->hasLocalLinkage() && "Invalid alias linkage");
965
966 EmitVisibility(Name, I->getVisibility());
967
968 // Emit the directives as assignments aka .set:
969 OutStreamer.EmitAssignment(Name,
970 MCSymbolRefExpr::Create(Target, OutContext));
971 }
972 }
973
974 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
975 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
976 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
977 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
978 MP->finishAssembly(*this);
979
980 // Emit llvm.ident metadata in an '.ident' directive.
981 EmitModuleIdents(M);
982
983 // If we don't have any trampolines, then we don't require stack memory
984 // to be executable. Some targets have a directive to declare this.
985 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
986 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
987 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
988 OutStreamer.SwitchSection(S);
989
990 // Allow the target to emit any magic that it wants at the end of the file,
991 // after everything else has gone out.
992 EmitEndOfAsmFile(M);
993
994 delete Mang; Mang = 0;
995 MMI = 0;
996
997 OutStreamer.Finish();
998 OutStreamer.reset();
999
1000 return false;
1001}
1002
1003void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1004 this->MF = &MF;
1005 // Get the function symbol.
1006 CurrentFnSym = getSymbol(MF.getFunction());
1007 CurrentFnSymForSize = CurrentFnSym;
1008
1009 if (isVerbose())
1010 LI = &getAnalysis<MachineLoopInfo>();
1011}
1012
1013namespace {
1014 // SectionCPs - Keep track the alignment, constpool entries per Section.
1015 struct SectionCPs {
1016 const MCSection *S;
1017 unsigned Alignment;
1018 SmallVector<unsigned, 4> CPEs;
1019 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1020 };
1021}
1022
1023/// EmitConstantPool - Print to the current output stream assembly
1024/// representations of the constants in the constant pool MCP. This is
1025/// used to print out constants which have been "spilled to memory" by
1026/// the code generator.
1027///
1028void AsmPrinter::EmitConstantPool() {
1029 const MachineConstantPool *MCP = MF->getConstantPool();
1030 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1031 if (CP.empty()) return;
1032
1033 // Calculate sections for constant pool entries. We collect entries to go into
1034 // the same section together to reduce amount of section switch statements.
1035 SmallVector<SectionCPs, 4> CPSections;
1036 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1037 const MachineConstantPoolEntry &CPE = CP[i];
1038 unsigned Align = CPE.getAlignment();
1039
1040 SectionKind Kind;
1041 switch (CPE.getRelocationInfo()) {
1042 default: llvm_unreachable("Unknown section kind");
1043 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1044 case 1:
1045 Kind = SectionKind::getReadOnlyWithRelLocal();
1046 break;
1047 case 0:
1048 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1049 case 4: Kind = SectionKind::getMergeableConst4(); break;
1050 case 8: Kind = SectionKind::getMergeableConst8(); break;
1051 case 16: Kind = SectionKind::getMergeableConst16();break;
1052 default: Kind = SectionKind::getMergeableConst(); break;
1053 }
1054 }
1055
1056 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1057
1058 // The number of sections are small, just do a linear search from the
1059 // last section to the first.
1060 bool Found = false;
1061 unsigned SecIdx = CPSections.size();
1062 while (SecIdx != 0) {
1063 if (CPSections[--SecIdx].S == S) {
1064 Found = true;
1065 break;
1066 }
1067 }
1068 if (!Found) {
1069 SecIdx = CPSections.size();
1070 CPSections.push_back(SectionCPs(S, Align));
1071 }
1072
1073 if (Align > CPSections[SecIdx].Alignment)
1074 CPSections[SecIdx].Alignment = Align;
1075 CPSections[SecIdx].CPEs.push_back(i);
1076 }
1077
1078 // Now print stuff into the calculated sections.
1079 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1080 OutStreamer.SwitchSection(CPSections[i].S);
1081 EmitAlignment(Log2_32(CPSections[i].Alignment));
1082
1083 unsigned Offset = 0;
1084 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1085 unsigned CPI = CPSections[i].CPEs[j];
1086 MachineConstantPoolEntry CPE = CP[CPI];
1087
1088 // Emit inter-object padding for alignment.
1089 unsigned AlignMask = CPE.getAlignment() - 1;
1090 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1091 OutStreamer.EmitZeros(NewOffset - Offset);
1092
1093 Type *Ty = CPE.getType();
1094 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1095 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1096
1097 if (CPE.isMachineConstantPoolEntry())
1098 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1099 else
1100 EmitGlobalConstant(CPE.Val.ConstVal);
1101 }
1102 }
1103}
1104
1105/// EmitJumpTableInfo - Print assembly representations of the jump tables used
1106/// by the current function to the current output stream.
1107///
1108void AsmPrinter::EmitJumpTableInfo() {
1109 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1110 if (MJTI == 0) return;
1111 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1112 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1113 if (JT.empty()) return;
1114
1115 // Pick the directive to use to print the jump table entries, and switch to
1116 // the appropriate section.
1117 const Function *F = MF->getFunction();
1118 bool JTInDiffSection = false;
1119 if (// In PIC mode, we need to emit the jump table to the same section as the
1120 // function body itself, otherwise the label differences won't make sense.
1121 // FIXME: Need a better predicate for this: what about custom entries?
1122 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1123 // We should also do if the section name is NULL or function is declared
1124 // in discardable section
1125 // FIXME: this isn't the right predicate, should be based on the MCSection
1126 // for the function.
1127 F->isWeakForLinker()) {
1128 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1129 } else {
1130 // Otherwise, drop it in the readonly section.
1131 const MCSection *ReadOnlySection =
1132 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1133 OutStreamer.SwitchSection(ReadOnlySection);
1134 JTInDiffSection = true;
1135 }
1136
1137 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1138
1139 // Jump tables in code sections are marked with a data_region directive
1140 // where that's supported.
1141 if (!JTInDiffSection)
1142 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1143
1144 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1145 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1146
1147 // If this jump table was deleted, ignore it.
1148 if (JTBBs.empty()) continue;
1149
1150 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1151 // .set directive for each unique entry. This reduces the number of
1152 // relocations the assembler will generate for the jump table.
1153 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1154 MAI->hasSetDirective()) {
1155 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1156 const TargetLowering *TLI = TM.getTargetLowering();
1157 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1158 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1159 const MachineBasicBlock *MBB = JTBBs[ii];
1160 if (!EmittedSets.insert(MBB)) continue;
1161
1162 // .set LJTSet, LBB32-base
1163 const MCExpr *LHS =
1164 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1165 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1166 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1167 }
1168 }
1169
1170 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1171 // before each jump table. The first label is never referenced, but tells
1172 // the assembler and linker the extents of the jump table object. The
1173 // second label is actually referenced by the code.
1174 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1175 // FIXME: This doesn't have to have any specific name, just any randomly
1176 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1177 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1178
1179 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1180
1181 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1182 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1183 }
1184 if (!JTInDiffSection)
1185 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1186}
1187
1188/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1189/// current stream.
1190void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1191 const MachineBasicBlock *MBB,
1192 unsigned UID) const {
1193 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1194 const MCExpr *Value = 0;
1195 switch (MJTI->getEntryKind()) {
1196 case MachineJumpTableInfo::EK_Inline:
1197 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1198 case MachineJumpTableInfo::EK_Custom32:
1199 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1200 OutContext);
1201 break;
1202 case MachineJumpTableInfo::EK_BlockAddress:
1203 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1204 // .word LBB123
1205 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1206 break;
1207 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1208 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1209 // with a relocation as gp-relative, e.g.:
1210 // .gprel32 LBB123
1211 MCSymbol *MBBSym = MBB->getSymbol();
1212 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1213 return;
1214 }
1215
1216 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1217 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1218 // with a relocation as gp-relative, e.g.:
1219 // .gpdword LBB123
1220 MCSymbol *MBBSym = MBB->getSymbol();
1221 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1222 return;
1223 }
1224
1225 case MachineJumpTableInfo::EK_LabelDifference32: {
1226 // EK_LabelDifference32 - Each entry is the address of the block minus
1227 // the address of the jump table. This is used for PIC jump tables where
1228 // gprel32 is not supported. e.g.:
1229 // .word LBB123 - LJTI1_2
1230 // If the .set directive is supported, this is emitted as:
1231 // .set L4_5_set_123, LBB123 - LJTI1_2
1232 // .word L4_5_set_123
1233
1234 // If we have emitted set directives for the jump table entries, print
1235 // them rather than the entries themselves. If we're emitting PIC, then
1236 // emit the table entries as differences between two text section labels.
1237 if (MAI->hasSetDirective()) {
1238 // If we used .set, reference the .set's symbol.
1239 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1240 OutContext);
1241 break;
1242 }
1243 // Otherwise, use the difference as the jump table entry.
1244 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1245 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1246 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1247 break;
1248 }
1249 }
1250
1251 assert(Value && "Unknown entry kind!");
1252
1253 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1254 OutStreamer.EmitValue(Value, EntrySize);
1255}
1256
1257
1258/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1259/// special global used by LLVM. If so, emit it and return true, otherwise
1260/// do nothing and return false.
1261bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1262 if (GV->getName() == "llvm.used") {
1263 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1264 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1265 return true;
1266 }
1267
1268 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1269 if (GV->getSection() == "llvm.metadata" ||
1270 GV->hasAvailableExternallyLinkage())
1271 return true;
1272
1273 if (!GV->hasAppendingLinkage()) return false;
1274
1275 assert(GV->hasInitializer() && "Not a special LLVM global!");
1276
1277 if (GV->getName() == "llvm.global_ctors") {
1278 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1279
1280 if (TM.getRelocationModel() == Reloc::Static &&
1281 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1282 StringRef Sym(".constructors_used");
1283 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1284 MCSA_Reference);
1285 }
1286 return true;
1287 }
1288
1289 if (GV->getName() == "llvm.global_dtors") {
1290 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1291
1292 if (TM.getRelocationModel() == Reloc::Static &&
1293 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1294 StringRef Sym(".destructors_used");
1295 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1296 MCSA_Reference);
1297 }
1298 return true;
1299 }
1300
1301 return false;
1302}
1303
1304/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1305/// global in the specified llvm.used list for which emitUsedDirectiveFor
1306/// is true, as being used with this directive.
1307void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1308 // Should be an array of 'i8*'.
1309 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1310 const GlobalValue *GV =
1311 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1312 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1313 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1314 }
1315}
1316
1317/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1318/// priority.
1319void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1320 // Should be an array of '{ int, void ()* }' structs. The first value is the
1321 // init priority.
1322 if (!isa<ConstantArray>(List)) return;
1323
1324 // Sanity check the structors list.
1325 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1326 if (!InitList) return; // Not an array!
1327 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1328 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1329 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1330 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1331
1332 // Gather the structors in a form that's convenient for sorting by priority.
1333 typedef std::pair<unsigned, Constant *> Structor;
1334 SmallVector<Structor, 8> Structors;
1335 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1336 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1337 if (!CS) continue; // Malformed.
1338 if (CS->getOperand(1)->isNullValue())
1339 break; // Found a null terminator, skip the rest.
1340 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1341 if (!Priority) continue; // Malformed.
1342 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1343 CS->getOperand(1)));
1344 }
1345
1346 // Emit the function pointers in the target-specific order
1347 const DataLayout *DL = TM.getDataLayout();
1348 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1349 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1350 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1351 const MCSection *OutputSection =
1352 (isCtor ?
1353 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1354 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1355 OutStreamer.SwitchSection(OutputSection);
1356 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1357 EmitAlignment(Align);
1358 EmitXXStructor(Structors[i].second);
1359 }
1360}
1361
1362void AsmPrinter::EmitModuleIdents(Module &M) {
1363 if (!MAI->hasIdentDirective())
1364 return;
1365
1366 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1367 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1368 const MDNode *N = NMD->getOperand(i);
1369 assert(N->getNumOperands() == 1 &&
1370 "llvm.ident metadata entry can have only one operand");
1371 const MDString *S = cast<MDString>(N->getOperand(0));
1372 OutStreamer.EmitIdent(S->getString());
1373 }
1374 }
1375}
1376
1377//===--------------------------------------------------------------------===//
1378// Emission and print routines
1379//
1380
1381/// EmitInt8 - Emit a byte directive and value.
1382///
1383void AsmPrinter::EmitInt8(int Value) const {
1384 OutStreamer.EmitIntValue(Value, 1);
1385}
1386
1387/// EmitInt16 - Emit a short directive and value.
1388///
1389void AsmPrinter::EmitInt16(int Value) const {
1390 OutStreamer.EmitIntValue(Value, 2);
1391}
1392
1393/// EmitInt32 - Emit a long directive and value.
1394///
1395void AsmPrinter::EmitInt32(int Value) const {
1396 OutStreamer.EmitIntValue(Value, 4);
1397}
1398
1399/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1400/// in bytes of the directive is specified by Size and Hi/Lo specify the
1401/// labels. This implicitly uses .set if it is available.
1402void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1403 unsigned Size) const {
1404 // Get the Hi-Lo expression.
1405 const MCExpr *Diff =
1406 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1407 MCSymbolRefExpr::Create(Lo, OutContext),
1408 OutContext);
1409
1410 if (!MAI->hasSetDirective()) {
1411 OutStreamer.EmitValue(Diff, Size);
1412 return;
1413 }
1414
1415 // Otherwise, emit with .set (aka assignment).
1416 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1417 OutStreamer.EmitAssignment(SetLabel, Diff);
1418 OutStreamer.EmitSymbolValue(SetLabel, Size);
1419}
1420
1421/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1422/// where the size in bytes of the directive is specified by Size and Hi/Lo
1423/// specify the labels. This implicitly uses .set if it is available.
1424void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1425 const MCSymbol *Lo, unsigned Size)
1426 const {
1427
1428 // Emit Hi+Offset - Lo
1429 // Get the Hi+Offset expression.
1430 const MCExpr *Plus =
1431 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1432 MCConstantExpr::Create(Offset, OutContext),
1433 OutContext);
1434
1435 // Get the Hi+Offset-Lo expression.
1436 const MCExpr *Diff =
1437 MCBinaryExpr::CreateSub(Plus,
1438 MCSymbolRefExpr::Create(Lo, OutContext),
1439 OutContext);
1440
1441 if (!MAI->hasSetDirective())
1442 OutStreamer.EmitValue(Diff, Size);
1443 else {
1444 // Otherwise, emit with .set (aka assignment).
1445 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1446 OutStreamer.EmitAssignment(SetLabel, Diff);
1447 OutStreamer.EmitSymbolValue(SetLabel, Size);
1448 }
1449}
1450
1451/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1452/// where the size in bytes of the directive is specified by Size and Label
1453/// specifies the label. This implicitly uses .set if it is available.
1454void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1455 unsigned Size, bool IsSectionRelative)
1456 const {
1457 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1458 OutStreamer.EmitCOFFSecRel32(Label);
1459 return;
1460 }
1461
1462 // Emit Label+Offset (or just Label if Offset is zero)
1463 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1464 if (Offset)
1465 Expr = MCBinaryExpr::CreateAdd(Expr,
1466 MCConstantExpr::Create(Offset, OutContext),
1467 OutContext);
1468
1469 OutStreamer.EmitValue(Expr, Size);
1470}
1471
1472
1473//===----------------------------------------------------------------------===//
1474
1475// EmitAlignment - Emit an alignment directive to the specified power of
1476// two boundary. For example, if you pass in 3 here, you will get an 8
1477// byte alignment. If a global value is specified, and if that global has
1478// an explicit alignment requested, it will override the alignment request
1479// if required for correctness.
1480//
1481void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1482 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1483
1484 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1485
1486 if (getCurrentSection()->getKind().isText())
1487 OutStreamer.EmitCodeAlignment(1 << NumBits);
1488 else
1489 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1490}
1491
1492//===----------------------------------------------------------------------===//
1493// Constant emission.
1494//===----------------------------------------------------------------------===//
1495
1496/// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1497///
1498static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1499 MCContext &Ctx = AP.OutContext;
1500
1501 if (CV->isNullValue() || isa<UndefValue>(CV))
1502 return MCConstantExpr::Create(0, Ctx);
1503
1504 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1505 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1506
1507 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1508 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1509
1510 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1511 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1512
1513 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1514 if (CE == 0) {
1515 llvm_unreachable("Unknown constant value to lower!");
1516 }
1517
1518 switch (CE->getOpcode()) {
1519 default:
1520 // If the code isn't optimized, there may be outstanding folding
1521 // opportunities. Attempt to fold the expression using DataLayout as a
1522 // last resort before giving up.
1523 if (Constant *C =
1524 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1525 if (C != CE)
1526 return lowerConstant(C, AP);
1527
1528 // Otherwise report the problem to the user.
1529 {
1530 std::string S;
1531 raw_string_ostream OS(S);
1532 OS << "Unsupported expression in static initializer: ";
1533 WriteAsOperand(OS, CE, /*PrintType=*/false,
1534 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1535 report_fatal_error(OS.str());
1536 }
1537 case Instruction::GetElementPtr: {
1538 const DataLayout &DL = *AP.TM.getDataLayout();
1539 // Generate a symbolic expression for the byte address
1540 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1541 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1542
1543 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1544 if (!OffsetAI)
1545 return Base;
1546
1547 int64_t Offset = OffsetAI.getSExtValue();
1548 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1549 Ctx);
1550 }
1551
1552 case Instruction::Trunc:
1553 // We emit the value and depend on the assembler to truncate the generated
1554 // expression properly. This is important for differences between
1555 // blockaddress labels. Since the two labels are in the same function, it
1556 // is reasonable to treat their delta as a 32-bit value.
1557 // FALL THROUGH.
1558 case Instruction::BitCast:
1559 return lowerConstant(CE->getOperand(0), AP);
1560
1561 case Instruction::IntToPtr: {
1562 const DataLayout &DL = *AP.TM.getDataLayout();
1563 // Handle casts to pointers by changing them into casts to the appropriate
1564 // integer type. This promotes constant folding and simplifies this code.
1565 Constant *Op = CE->getOperand(0);
1566 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1567 false/*ZExt*/);
1568 return lowerConstant(Op, AP);
1569 }
1570
1571 case Instruction::PtrToInt: {
1572 const DataLayout &DL = *AP.TM.getDataLayout();
1573 // Support only foldable casts to/from pointers that can be eliminated by
1574 // changing the pointer to the appropriately sized integer type.
1575 Constant *Op = CE->getOperand(0);
1576 Type *Ty = CE->getType();
1577
1578 const MCExpr *OpExpr = lowerConstant(Op, AP);
1579
1580 // We can emit the pointer value into this slot if the slot is an
1581 // integer slot equal to the size of the pointer.
1582 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1583 return OpExpr;
1584
1585 // Otherwise the pointer is smaller than the resultant integer, mask off
1586 // the high bits so we are sure to get a proper truncation if the input is
1587 // a constant expr.
1588 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1589 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1590 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1591 }
1592
1593 // The MC library also has a right-shift operator, but it isn't consistently
1594 // signed or unsigned between different targets.
1595 case Instruction::Add:
1596 case Instruction::Sub:
1597 case Instruction::Mul:
1598 case Instruction::SDiv:
1599 case Instruction::SRem:
1600 case Instruction::Shl:
1601 case Instruction::And:
1602 case Instruction::Or:
1603 case Instruction::Xor: {
1604 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1605 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1606 switch (CE->getOpcode()) {
1607 default: llvm_unreachable("Unknown binary operator constant cast expr");
1608 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1609 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1610 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1611 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1612 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1613 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1614 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1615 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1616 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1617 }
1618 }
1619 }
1620}
1621
1622static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1623
1624/// isRepeatedByteSequence - Determine whether the given value is
1625/// composed of a repeated sequence of identical bytes and return the
1626/// byte value. If it is not a repeated sequence, return -1.
1627static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1628 StringRef Data = V->getRawDataValues();
1629 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1630 char C = Data[0];
1631 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1632 if (Data[i] != C) return -1;
1633 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1634}
1635
1636
1637/// isRepeatedByteSequence - Determine whether the given value is
1638/// composed of a repeated sequence of identical bytes and return the
1639/// byte value. If it is not a repeated sequence, return -1.
1640static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1641
1642 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1643 if (CI->getBitWidth() > 64) return -1;
1644
1645 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1646 uint64_t Value = CI->getZExtValue();
1647
1648 // Make sure the constant is at least 8 bits long and has a power
1649 // of 2 bit width. This guarantees the constant bit width is
1650 // always a multiple of 8 bits, avoiding issues with padding out
1651 // to Size and other such corner cases.
1652 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1653
1654 uint8_t Byte = static_cast<uint8_t>(Value);
1655
1656 for (unsigned i = 1; i < Size; ++i) {
1657 Value >>= 8;
1658 if (static_cast<uint8_t>(Value) != Byte) return -1;
1659 }
1660 return Byte;
1661 }
1662 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1663 // Make sure all array elements are sequences of the same repeated
1664 // byte.
1665 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1666 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1667 if (Byte == -1) return -1;
1668
1669 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1670 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1671 if (ThisByte == -1) return -1;
1672 if (Byte != ThisByte) return -1;
1673 }
1674 return Byte;
1675 }
1676
1677 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1678 return isRepeatedByteSequence(CDS);
1679
1680 return -1;
1681}
1682
1683static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1684 AsmPrinter &AP){
1685
1686 // See if we can aggregate this into a .fill, if so, emit it as such.
1687 int Value = isRepeatedByteSequence(CDS, AP.TM);
1688 if (Value != -1) {
1689 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1690 // Don't emit a 1-byte object as a .fill.
1691 if (Bytes > 1)
1692 return AP.OutStreamer.EmitFill(Bytes, Value);
1693 }
1694
1695 // If this can be emitted with .ascii/.asciz, emit it as such.
1696 if (CDS->isString())
1697 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1698
1699 // Otherwise, emit the values in successive locations.
1700 unsigned ElementByteSize = CDS->getElementByteSize();
1701 if (isa<IntegerType>(CDS->getElementType())) {
1702 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1703 if (AP.isVerbose())
1704 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1705 CDS->getElementAsInteger(i));
1706 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1707 ElementByteSize);
1708 }
1709 } else if (ElementByteSize == 4) {
1710 // FP Constants are printed as integer constants to avoid losing
1711 // precision.
1712 assert(CDS->getElementType()->isFloatTy());
1713 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1714 union {
1715 float F;
1716 uint32_t I;
1717 };
1718
1719 F = CDS->getElementAsFloat(i);
1720 if (AP.isVerbose())
1721 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1722 AP.OutStreamer.EmitIntValue(I, 4);
1723 }
1724 } else {
1725 assert(CDS->getElementType()->isDoubleTy());
1726 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1727 union {
1728 double F;
1729 uint64_t I;
1730 };
1731
1732 F = CDS->getElementAsDouble(i);
1733 if (AP.isVerbose())
1734 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1735 AP.OutStreamer.EmitIntValue(I, 8);
1736 }
1737 }
1738
1739 const DataLayout &DL = *AP.TM.getDataLayout();
1740 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1741 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1742 CDS->getNumElements();
1743 if (unsigned Padding = Size - EmittedSize)
1744 AP.OutStreamer.EmitZeros(Padding);
1745
1746}
1747
1748static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1749 // See if we can aggregate some values. Make sure it can be
1750 // represented as a series of bytes of the constant value.
1751 int Value = isRepeatedByteSequence(CA, AP.TM);
1752
1753 if (Value != -1) {
1754 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1755 AP.OutStreamer.EmitFill(Bytes, Value);
1756 }
1757 else {
1758 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1759 emitGlobalConstantImpl(CA->getOperand(i), AP);
1760 }
1761}
1762
1763static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1764 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1765 emitGlobalConstantImpl(CV->getOperand(i), AP);
1766
1767 const DataLayout &DL = *AP.TM.getDataLayout();
1768 unsigned Size = DL.getTypeAllocSize(CV->getType());
1769 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1770 CV->getType()->getNumElements();
1771 if (unsigned Padding = Size - EmittedSize)
1772 AP.OutStreamer.EmitZeros(Padding);
1773}
1774
1775static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1776 // Print the fields in successive locations. Pad to align if needed!
1777 const DataLayout *DL = AP.TM.getDataLayout();
1778 unsigned Size = DL->getTypeAllocSize(CS->getType());
1779 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1780 uint64_t SizeSoFar = 0;
1781 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1782 const Constant *Field = CS->getOperand(i);
1783
1784 // Check if padding is needed and insert one or more 0s.
1785 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1786 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1787 - Layout->getElementOffset(i)) - FieldSize;
1788 SizeSoFar += FieldSize + PadSize;
1789
1790 // Now print the actual field value.
1791 emitGlobalConstantImpl(Field, AP);
1792
1793 // Insert padding - this may include padding to increase the size of the
1794 // current field up to the ABI size (if the struct is not packed) as well
1795 // as padding to ensure that the next field starts at the right offset.
1796 AP.OutStreamer.EmitZeros(PadSize);
1797 }
1798 assert(SizeSoFar == Layout->getSizeInBytes() &&
1799 "Layout of constant struct may be incorrect!");
1800}
1801
1802static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1803 APInt API = CFP->getValueAPF().bitcastToAPInt();
1804
1805 // First print a comment with what we think the original floating-point value
1806 // should have been.
1807 if (AP.isVerbose()) {
1808 SmallString<8> StrVal;
1809 CFP->getValueAPF().toString(StrVal);
1810
1811 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1812 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1813 }
1814
1815 // Now iterate through the APInt chunks, emitting them in endian-correct
1816 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1817 // floats).
1818 unsigned NumBytes = API.getBitWidth() / 8;
1819 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1820 const uint64_t *p = API.getRawData();
1821
1822 // PPC's long double has odd notions of endianness compared to how LLVM
1823 // handles it: p[0] goes first for *big* endian on PPC.
1824 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1825 int Chunk = API.getNumWords() - 1;
1826
1827 if (TrailingBytes)
1828 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1829
1830 for (; Chunk >= 0; --Chunk)
1831 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1832 } else {
1833 unsigned Chunk;
1834 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1835 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1836
1837 if (TrailingBytes)
1838 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1839 }
1840
1841 // Emit the tail padding for the long double.
1842 const DataLayout &DL = *AP.TM.getDataLayout();
1843 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1844 DL.getTypeStoreSize(CFP->getType()));
1845}
1846
1847static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1848 const DataLayout *DL = AP.TM.getDataLayout();
1849 unsigned BitWidth = CI->getBitWidth();
1850
1851 // Copy the value as we may massage the layout for constants whose bit width
1852 // is not a multiple of 64-bits.
1853 APInt Realigned(CI->getValue());
1854 uint64_t ExtraBits = 0;
1855 unsigned ExtraBitsSize = BitWidth & 63;
1856
1857 if (ExtraBitsSize) {
1858 // The bit width of the data is not a multiple of 64-bits.
1859 // The extra bits are expected to be at the end of the chunk of the memory.
1860 // Little endian:
1861 // * Nothing to be done, just record the extra bits to emit.
1862 // Big endian:
1863 // * Record the extra bits to emit.
1864 // * Realign the raw data to emit the chunks of 64-bits.
1865 if (DL->isBigEndian()) {
1866 // Basically the structure of the raw data is a chunk of 64-bits cells:
1867 // 0 1 BitWidth / 64
1868 // [chunk1][chunk2] ... [chunkN].
1869 // The most significant chunk is chunkN and it should be emitted first.
1870 // However, due to the alignment issue chunkN contains useless bits.
1871 // Realign the chunks so that they contain only useless information:
1872 // ExtraBits 0 1 (BitWidth / 64) - 1
1873 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1874 ExtraBits = Realigned.getRawData()[0] &
1875 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1876 Realigned = Realigned.lshr(ExtraBitsSize);
1877 } else
1878 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1879 }
1880
1881 // We don't expect assemblers to support integer data directives
1882 // for more than 64 bits, so we emit the data in at most 64-bit
1883 // quantities at a time.
1884 const uint64_t *RawData = Realigned.getRawData();
1885 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1886 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1887 AP.OutStreamer.EmitIntValue(Val, 8);
1888 }
1889
1890 if (ExtraBitsSize) {
1891 // Emit the extra bits after the 64-bits chunks.
1892
1893 // Emit a directive that fills the expected size.
1894 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1895 Size -= (BitWidth / 64) * 8;
1896 assert(Size && Size * 8 >= ExtraBitsSize &&
1897 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1898 == ExtraBits && "Directive too small for extra bits.");
1899 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1900 }
1901}
1902
1903static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1904 const DataLayout *DL = AP.TM.getDataLayout();
1905 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1906 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1907 return AP.OutStreamer.EmitZeros(Size);
1908
1909 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1910 switch (Size) {
1911 case 1:
1912 case 2:
1913 case 4:
1914 case 8:
1915 if (AP.isVerbose())
1916 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1917 CI->getZExtValue());
1918 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1919 return;
1920 default:
1921 emitGlobalConstantLargeInt(CI, AP);
1922 return;
1923 }
1924 }
1925
1926 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1927 return emitGlobalConstantFP(CFP, AP);
1928
1929 if (isa<ConstantPointerNull>(CV)) {
1930 AP.OutStreamer.EmitIntValue(0, Size);
1931 return;
1932 }
1933
1934 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1935 return emitGlobalConstantDataSequential(CDS, AP);
1936
1937 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1938 return emitGlobalConstantArray(CVA, AP);
1939
1940 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1941 return emitGlobalConstantStruct(CVS, AP);
1942
1943 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1944 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1945 // vectors).
1946 if (CE->getOpcode() == Instruction::BitCast)
1947 return emitGlobalConstantImpl(CE->getOperand(0), AP);
1948
1949 if (Size > 8) {
1950 // If the constant expression's size is greater than 64-bits, then we have
1951 // to emit the value in chunks. Try to constant fold the value and emit it
1952 // that way.
1953 Constant *New = ConstantFoldConstantExpression(CE, DL);
1954 if (New && New != CE)
1955 return emitGlobalConstantImpl(New, AP);
1956 }
1957 }
1958
1959 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1960 return emitGlobalConstantVector(V, AP);
1961
1962 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1963 // thread the streamer with EmitValue.
1964 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1965}
1966
1967/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1968void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1969 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1970 if (Size)
1971 emitGlobalConstantImpl(CV, *this);
1972 else if (MAI->hasSubsectionsViaSymbols()) {
1973 // If the global has zero size, emit a single byte so that two labels don't
1974 // look like they are at the same location.
1975 OutStreamer.EmitIntValue(0, 1);
1976 }
1977}
1978
1979void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1980 // Target doesn't support this yet!
1981 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1982}
1983
1984void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1985 if (Offset > 0)
1986 OS << '+' << Offset;
1987 else if (Offset < 0)
1988 OS << Offset;
1989}
1990
1991//===----------------------------------------------------------------------===//
1992// Symbol Lowering Routines.
1993//===----------------------------------------------------------------------===//
1994
1995/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1996/// temporary label with the specified stem and unique ID.
1997MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1998 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1999 Name + Twine(ID));
2000}
2001
2002/// GetTempSymbol - Return an assembler temporary label with the specified
2003/// stem.
2004MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2005 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
2006 Name);
2007}
2008
2009
2010MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2011 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2012}
2013
2014MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2015 return MMI->getAddrLabelSymbol(BB);
2016}
2017
2018/// GetCPISymbol - Return the symbol for the specified constant pool entry.
2019MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2020 return OutContext.GetOrCreateSymbol
2021 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2022 + "_" + Twine(CPID));
2023}
2024
2025/// GetJTISymbol - Return the symbol for the specified jump table entry.
2026MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2027 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2028}
2029
2030/// GetJTSetSymbol - Return the symbol for the specified jump table .set
2031/// FIXME: privatize to AsmPrinter.
2032MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2033 return OutContext.GetOrCreateSymbol
2034 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2035 Twine(UID) + "_set_" + Twine(MBBID));
2036}
2037
2038/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
2039/// global value name as its base, with the specified suffix, and where the
2040/// symbol is forced to have private linkage if ForcePrivate is true.
2041MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
2042 StringRef Suffix,
2043 bool ForcePrivate) const {
2044 SmallString<60> NameStr;
2045 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
2046 NameStr.append(Suffix.begin(), Suffix.end());
2047 return OutContext.GetOrCreateSymbol(NameStr.str());
2048}
2049
2050/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2051/// ExternalSymbol.
2052MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2053 SmallString<60> NameStr;
2054 Mang->getNameWithPrefix(NameStr, Sym);
2055 return OutContext.GetOrCreateSymbol(NameStr.str());
2056}
2057
2058
2059
2060/// PrintParentLoopComment - Print comments about parent loops of this one.
2061static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2062 unsigned FunctionNumber) {
2063 if (Loop == 0) return;
2064 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2065 OS.indent(Loop->getLoopDepth()*2)
2066 << "Parent Loop BB" << FunctionNumber << "_"
2067 << Loop->getHeader()->getNumber()
2068 << " Depth=" << Loop->getLoopDepth() << '\n';
2069}
2070
2071
2072/// PrintChildLoopComment - Print comments about child loops within
2073/// the loop for this basic block, with nesting.
2074static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2075 unsigned FunctionNumber) {
2076 // Add child loop information
2077 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2078 OS.indent((*CL)->getLoopDepth()*2)
2079 << "Child Loop BB" << FunctionNumber << "_"
2080 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2081 << '\n';
2082 PrintChildLoopComment(OS, *CL, FunctionNumber);
2083 }
2084}
2085
2086/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2087static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2088 const MachineLoopInfo *LI,
2089 const AsmPrinter &AP) {
2090 // Add loop depth information
2091 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2092 if (Loop == 0) return;
2093
2094 MachineBasicBlock *Header = Loop->getHeader();
2095 assert(Header && "No header for loop");
2096
2097 // If this block is not a loop header, just print out what is the loop header
2098 // and return.
2099 if (Header != &MBB) {
2100 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2101 Twine(AP.getFunctionNumber())+"_" +
2102 Twine(Loop->getHeader()->getNumber())+
2103 " Depth="+Twine(Loop->getLoopDepth()));
2104 return;
2105 }
2106
2107 // Otherwise, it is a loop header. Print out information about child and
2108 // parent loops.
2109 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2110
2111 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2112
2113 OS << "=>";
2114 OS.indent(Loop->getLoopDepth()*2-2);
2115
2116 OS << "This ";
2117 if (Loop->empty())
2118 OS << "Inner ";
2119 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2120
2121 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2122}
2123
2124
2125/// EmitBasicBlockStart - This method prints the label for the specified
2126/// MachineBasicBlock, an alignment (if present) and a comment describing
2127/// it if appropriate.
2128void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2129 // Emit an alignment directive for this block, if needed.
2130 if (unsigned Align = MBB->getAlignment())
2131 EmitAlignment(Align);
2132
2133 // If the block has its address taken, emit any labels that were used to
2134 // reference the block. It is possible that there is more than one label
2135 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2136 // the references were generated.
2137 if (MBB->hasAddressTaken()) {
2138 const BasicBlock *BB = MBB->getBasicBlock();
2139 if (isVerbose())
2140 OutStreamer.AddComment("Block address taken");
2141
2142 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2143
2144 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2145 OutStreamer.EmitLabel(Syms[i]);
2146 }
2147
2148 // Print some verbose block comments.
2149 if (isVerbose()) {
2150 if (const BasicBlock *BB = MBB->getBasicBlock())
2151 if (BB->hasName())
2152 OutStreamer.AddComment("%" + BB->getName());
2153 emitBasicBlockLoopComments(*MBB, LI, *this);
2154 }
2155
2156 // Print the main label for the block.
2157 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2158 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2159 // NOTE: Want this comment at start of line, don't emit with AddComment.
2160 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2161 Twine(MBB->getNumber()) + ":");
2162 }
2163 } else {
2164 OutStreamer.EmitLabel(MBB->getSymbol());
2165 }
2166}
2167
2168void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2169 bool IsDefinition) const {
2170 MCSymbolAttr Attr = MCSA_Invalid;
2171
2172 switch (Visibility) {
2173 default: break;
2174 case GlobalValue::HiddenVisibility:
2175 if (IsDefinition)
2176 Attr = MAI->getHiddenVisibilityAttr();
2177 else
2178 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2179 break;
2180 case GlobalValue::ProtectedVisibility:
2181 Attr = MAI->getProtectedVisibilityAttr();
2182 break;
2183 }
2184
2185 if (Attr != MCSA_Invalid)
2186 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2187}
2188
2189/// isBlockOnlyReachableByFallthough - Return true if the basic block has
2190/// exactly one predecessor and the control transfer mechanism between
2191/// the predecessor and this block is a fall-through.
2192bool AsmPrinter::
2193isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2194 // If this is a landing pad, it isn't a fall through. If it has no preds,
2195 // then nothing falls through to it.
2196 if (MBB->isLandingPad() || MBB->pred_empty())
2197 return false;
2198
2199 // If there isn't exactly one predecessor, it can't be a fall through.
2200 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2201 ++PI2;
2202 if (PI2 != MBB->pred_end())
2203 return false;
2204
2205 // The predecessor has to be immediately before this block.
2206 MachineBasicBlock *Pred = *PI;
2207
2208 if (!Pred->isLayoutSuccessor(MBB))
2209 return false;
2210
2211 // If the block is completely empty, then it definitely does fall through.
2212 if (Pred->empty())
2213 return true;
2214
2215 // Check the terminators in the previous blocks
2216 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2217 IE = Pred->end(); II != IE; ++II) {
2218 MachineInstr &MI = *II;
2219
2220 // If it is not a simple branch, we are in a table somewhere.
2221 if (!MI.isBranch() || MI.isIndirectBranch())
2222 return false;
2223
27#include "llvm/CodeGen/MachineJumpTableInfo.h"
28#include "llvm/CodeGen/MachineLoopInfo.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/DebugInfo.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Operator.h"
34#include "llvm/MC/MCAsmInfo.h"
35#include "llvm/MC/MCContext.h"
36#include "llvm/MC/MCExpr.h"
37#include "llvm/MC/MCInst.h"
38#include "llvm/MC/MCSection.h"
39#include "llvm/MC/MCStreamer.h"
40#include "llvm/MC/MCSymbol.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/Format.h"
43#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Timer.h"
45#include "llvm/Target/Mangler.h"
46#include "llvm/Target/TargetFrameLowering.h"
47#include "llvm/Target/TargetInstrInfo.h"
48#include "llvm/Target/TargetLowering.h"
49#include "llvm/Target/TargetLoweringObjectFile.h"
50#include "llvm/Target/TargetOptions.h"
51#include "llvm/Target/TargetRegisterInfo.h"
52#include "llvm/Transforms/Utils/GlobalStatus.h"
53using namespace llvm;
54
55static const char *const DWARFGroupName = "DWARF Emission";
56static const char *const DbgTimerName = "DWARF Debug Writer";
57static const char *const EHTimerName = "DWARF Exception Writer";
58
59STATISTIC(EmittedInsts, "Number of machine instrs printed");
60
61char AsmPrinter::ID = 0;
62
63typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
64static gcp_map_type &getGCMap(void *&P) {
65 if (P == 0)
66 P = new gcp_map_type();
67 return *(gcp_map_type*)P;
68}
69
70
71/// getGVAlignmentLog2 - Return the alignment to use for the specified global
72/// value in log2 form. This rounds up to the preferred alignment if possible
73/// and legal.
74static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
75 unsigned InBits = 0) {
76 unsigned NumBits = 0;
77 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
78 NumBits = TD.getPreferredAlignmentLog(GVar);
79
80 // If InBits is specified, round it to it.
81 if (InBits > NumBits)
82 NumBits = InBits;
83
84 // If the GV has a specified alignment, take it into account.
85 if (GV->getAlignment() == 0)
86 return NumBits;
87
88 unsigned GVAlign = Log2_32(GV->getAlignment());
89
90 // If the GVAlign is larger than NumBits, or if we are required to obey
91 // NumBits because the GV has an assigned section, obey it.
92 if (GVAlign > NumBits || GV->hasSection())
93 NumBits = GVAlign;
94 return NumBits;
95}
96
97AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
98 : MachineFunctionPass(ID),
99 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
100 OutContext(Streamer.getContext()),
101 OutStreamer(Streamer),
102 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
103 DD = 0; DE = 0; MMI = 0; LI = 0; MF = 0;
104 CurrentFnSym = CurrentFnSymForSize = 0;
105 GCMetadataPrinters = 0;
106 VerboseAsm = Streamer.isVerboseAsm();
107}
108
109AsmPrinter::~AsmPrinter() {
110 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
111
112 if (GCMetadataPrinters != 0) {
113 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
114
115 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
116 delete I->second;
117 delete &GCMap;
118 GCMetadataPrinters = 0;
119 }
120
121 delete &OutStreamer;
122}
123
124/// getFunctionNumber - Return a unique ID for the current function.
125///
126unsigned AsmPrinter::getFunctionNumber() const {
127 return MF->getFunctionNumber();
128}
129
130const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
131 return TM.getTargetLowering()->getObjFileLowering();
132}
133
134/// getDataLayout - Return information about data layout.
135const DataLayout &AsmPrinter::getDataLayout() const {
136 return *TM.getDataLayout();
137}
138
139StringRef AsmPrinter::getTargetTriple() const {
140 return TM.getTargetTriple();
141}
142
143/// getCurrentSection() - Return the current section we are emitting to.
144const MCSection *AsmPrinter::getCurrentSection() const {
145 return OutStreamer.getCurrentSection().first;
146}
147
148
149
150void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
151 AU.setPreservesAll();
152 MachineFunctionPass::getAnalysisUsage(AU);
153 AU.addRequired<MachineModuleInfo>();
154 AU.addRequired<GCModuleInfo>();
155 if (isVerbose())
156 AU.addRequired<MachineLoopInfo>();
157}
158
159bool AsmPrinter::doInitialization(Module &M) {
160 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
161 MMI->AnalyzeModule(M);
162
163 // Initialize TargetLoweringObjectFile.
164 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
165 .Initialize(OutContext, TM);
166
167 OutStreamer.InitStreamer();
168
169 Mang = new Mangler(&TM);
170
171 // Allow the target to emit any magic that it wants at the start of the file.
172 EmitStartOfAsmFile(M);
173
174 // Very minimal debug info. It is ignored if we emit actual debug info. If we
175 // don't, this at least helps the user find where a global came from.
176 if (MAI->hasSingleParameterDotFile()) {
177 // .file "foo.c"
178 OutStreamer.EmitFileDirective(M.getModuleIdentifier());
179 }
180
181 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
182 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
183 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
184 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
185 MP->beginAssembly(*this);
186
187 // Emit module-level inline asm if it exists.
188 if (!M.getModuleInlineAsm().empty()) {
189 OutStreamer.AddComment("Start of file scope inline assembly");
190 OutStreamer.AddBlankLine();
191 EmitInlineAsm(M.getModuleInlineAsm()+"\n");
192 OutStreamer.AddComment("End of file scope inline assembly");
193 OutStreamer.AddBlankLine();
194 }
195
196 if (MAI->doesSupportDebugInformation())
197 DD = new DwarfDebug(this, &M);
198
199 switch (MAI->getExceptionHandlingType()) {
200 case ExceptionHandling::None:
201 return false;
202 case ExceptionHandling::SjLj:
203 case ExceptionHandling::DwarfCFI:
204 DE = new DwarfCFIException(this);
205 return false;
206 case ExceptionHandling::ARM:
207 DE = new ARMException(this);
208 return false;
209 case ExceptionHandling::Win64:
210 DE = new Win64Exception(this);
211 return false;
212 }
213
214 llvm_unreachable("Unknown exception type.");
215}
216
217void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
218 GlobalValue::LinkageTypes Linkage = GV->getLinkage();
219 switch (Linkage) {
220 case GlobalValue::CommonLinkage:
221 case GlobalValue::LinkOnceAnyLinkage:
222 case GlobalValue::LinkOnceODRLinkage:
223 case GlobalValue::WeakAnyLinkage:
224 case GlobalValue::WeakODRLinkage:
225 case GlobalValue::LinkerPrivateWeakLinkage:
226 if (MAI->getWeakDefDirective() != 0) {
227 // .globl _foo
228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
229
230 bool CanBeHidden = false;
231
232 if (Linkage == GlobalValue::LinkOnceODRLinkage) {
233 if (GV->hasUnnamedAddr()) {
234 CanBeHidden = true;
235 } else {
236 GlobalStatus GS;
237 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
238 CanBeHidden = true;
239 }
240 }
241
242 if (!CanBeHidden)
243 // .weak_definition _foo
244 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
245 else
246 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
247 } else if (MAI->getLinkOnceDirective() != 0) {
248 // .globl _foo
249 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
250 //NOTE: linkonce is handled by the section the symbol was assigned to.
251 } else {
252 // .weak _foo
253 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
254 }
255 return;
256 case GlobalValue::DLLExportLinkage:
257 case GlobalValue::AppendingLinkage:
258 // FIXME: appending linkage variables should go into a section of
259 // their name or something. For now, just emit them as external.
260 case GlobalValue::ExternalLinkage:
261 // If external or appending, declare as a global symbol.
262 // .globl _foo
263 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
264 return;
265 case GlobalValue::PrivateLinkage:
266 case GlobalValue::InternalLinkage:
267 case GlobalValue::LinkerPrivateLinkage:
268 return;
269 case GlobalValue::AvailableExternallyLinkage:
270 llvm_unreachable("Should never emit this");
271 case GlobalValue::DLLImportLinkage:
272 case GlobalValue::ExternalWeakLinkage:
273 llvm_unreachable("Don't know how to emit these");
274 }
275 llvm_unreachable("Unknown linkage type!");
276}
277
278MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
279 return getObjFileLowering().getSymbol(*Mang, GV);
280}
281
282/// EmitGlobalVariable - Emit the specified global variable to the .s file.
283void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
284 if (GV->hasInitializer()) {
285 // Check to see if this is a special global used by LLVM, if so, emit it.
286 if (EmitSpecialLLVMGlobal(GV))
287 return;
288
289 if (isVerbose()) {
290 WriteAsOperand(OutStreamer.GetCommentOS(), GV,
291 /*PrintType=*/false, GV->getParent());
292 OutStreamer.GetCommentOS() << '\n';
293 }
294 }
295
296 MCSymbol *GVSym = getSymbol(GV);
297 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
298
299 if (!GV->hasInitializer()) // External globals require no extra code.
300 return;
301
302 if (MAI->hasDotTypeDotSizeDirective())
303 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
304
305 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
306
307 const DataLayout *DL = TM.getDataLayout();
308 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
309
310 // If the alignment is specified, we *must* obey it. Overaligning a global
311 // with a specified alignment is a prompt way to break globals emitted to
312 // sections and expected to be contiguous (e.g. ObjC metadata).
313 unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
314
315 if (DD)
316 DD->setSymbolSize(GVSym, Size);
317
318 // Handle common and BSS local symbols (.lcomm).
319 if (GVKind.isCommon() || GVKind.isBSSLocal()) {
320 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
321 unsigned Align = 1 << AlignLog;
322
323 // Handle common symbols.
324 if (GVKind.isCommon()) {
325 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
326 Align = 0;
327
328 // .comm _foo, 42, 4
329 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
330 return;
331 }
332
333 // Handle local BSS symbols.
334 if (MAI->hasMachoZeroFillDirective()) {
335 const MCSection *TheSection =
336 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
337 // .zerofill __DATA, __bss, _foo, 400, 5
338 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
339 return;
340 }
341
342 // Use .lcomm only if it supports user-specified alignment.
343 // Otherwise, while it would still be correct to use .lcomm in some
344 // cases (e.g. when Align == 1), the external assembler might enfore
345 // some -unknown- default alignment behavior, which could cause
346 // spurious differences between external and integrated assembler.
347 // Prefer to simply fall back to .local / .comm in this case.
348 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
349 // .lcomm _foo, 42
350 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
351 return;
352 }
353
354 if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
355 Align = 0;
356
357 // .local _foo
358 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
359 // .comm _foo, 42, 4
360 OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
361 return;
362 }
363
364 const MCSection *TheSection =
365 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
366
367 // Handle the zerofill directive on darwin, which is a special form of BSS
368 // emission.
369 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
370 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined.
371
372 // .globl _foo
373 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
374 // .zerofill __DATA, __common, _foo, 400, 5
375 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
376 return;
377 }
378
379 // Handle thread local data for mach-o which requires us to output an
380 // additional structure of data and mangle the original symbol so that we
381 // can reference it later.
382 //
383 // TODO: This should become an "emit thread local global" method on TLOF.
384 // All of this macho specific stuff should be sunk down into TLOFMachO and
385 // stuff like "TLSExtraDataSection" should no longer be part of the parent
386 // TLOF class. This will also make it more obvious that stuff like
387 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
388 // specific code.
389 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
390 // Emit the .tbss symbol
391 MCSymbol *MangSym =
392 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
393
394 if (GVKind.isThreadBSS()) {
395 TheSection = getObjFileLowering().getTLSBSSSection();
396 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
397 } else if (GVKind.isThreadData()) {
398 OutStreamer.SwitchSection(TheSection);
399
400 EmitAlignment(AlignLog, GV);
401 OutStreamer.EmitLabel(MangSym);
402
403 EmitGlobalConstant(GV->getInitializer());
404 }
405
406 OutStreamer.AddBlankLine();
407
408 // Emit the variable struct for the runtime.
409 const MCSection *TLVSect
410 = getObjFileLowering().getTLSExtraDataSection();
411
412 OutStreamer.SwitchSection(TLVSect);
413 // Emit the linkage here.
414 EmitLinkage(GV, GVSym);
415 OutStreamer.EmitLabel(GVSym);
416
417 // Three pointers in size:
418 // - __tlv_bootstrap - used to make sure support exists
419 // - spare pointer, used when mapped by the runtime
420 // - pointer to mangled symbol above with initializer
421 unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
422 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
423 PtrSize);
424 OutStreamer.EmitIntValue(0, PtrSize);
425 OutStreamer.EmitSymbolValue(MangSym, PtrSize);
426
427 OutStreamer.AddBlankLine();
428 return;
429 }
430
431 OutStreamer.SwitchSection(TheSection);
432
433 EmitLinkage(GV, GVSym);
434 EmitAlignment(AlignLog, GV);
435
436 OutStreamer.EmitLabel(GVSym);
437
438 EmitGlobalConstant(GV->getInitializer());
439
440 if (MAI->hasDotTypeDotSizeDirective())
441 // .size foo, 42
442 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
443
444 OutStreamer.AddBlankLine();
445}
446
447/// EmitFunctionHeader - This method emits the header for the current
448/// function.
449void AsmPrinter::EmitFunctionHeader() {
450 // Print out constants referenced by the function
451 EmitConstantPool();
452
453 // Print the 'header' of function.
454 const Function *F = MF->getFunction();
455
456 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
457 EmitVisibility(CurrentFnSym, F->getVisibility());
458
459 EmitLinkage(F, CurrentFnSym);
460 EmitAlignment(MF->getAlignment(), F);
461
462 if (MAI->hasDotTypeDotSizeDirective())
463 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
464
465 if (isVerbose()) {
466 WriteAsOperand(OutStreamer.GetCommentOS(), F,
467 /*PrintType=*/false, F->getParent());
468 OutStreamer.GetCommentOS() << '\n';
469 }
470
471 // Emit the CurrentFnSym. This is a virtual function to allow targets to
472 // do their wild and crazy things as required.
473 EmitFunctionEntryLabel();
474
475 // If the function had address-taken blocks that got deleted, then we have
476 // references to the dangling symbols. Emit them at the start of the function
477 // so that we don't get references to undefined symbols.
478 std::vector<MCSymbol*> DeadBlockSyms;
479 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
480 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
481 OutStreamer.AddComment("Address taken block that was later removed");
482 OutStreamer.EmitLabel(DeadBlockSyms[i]);
483 }
484
485 // Emit pre-function debug and/or EH information.
486 if (DE) {
487 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
488 DE->BeginFunction(MF);
489 }
490 if (DD) {
491 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
492 DD->beginFunction(MF);
493 }
494
495 // Emit the prefix data.
496 if (F->hasPrefixData())
497 EmitGlobalConstant(F->getPrefixData());
498}
499
500/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
501/// function. This can be overridden by targets as required to do custom stuff.
502void AsmPrinter::EmitFunctionEntryLabel() {
503 // The function label could have already been emitted if two symbols end up
504 // conflicting due to asm renaming. Detect this and emit an error.
505 if (CurrentFnSym->isUndefined())
506 return OutStreamer.EmitLabel(CurrentFnSym);
507
508 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
509 "' label emitted multiple times to assembly file");
510}
511
512/// emitComments - Pretty-print comments for instructions.
513static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
514 const MachineFunction *MF = MI.getParent()->getParent();
515 const TargetMachine &TM = MF->getTarget();
516
517 // Check for spills and reloads
518 int FI;
519
520 const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
521
522 // We assume a single instruction only has a spill or reload, not
523 // both.
524 const MachineMemOperand *MMO;
525 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
526 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
527 MMO = *MI.memoperands_begin();
528 CommentOS << MMO->getSize() << "-byte Reload\n";
529 }
530 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
531 if (FrameInfo->isSpillSlotObjectIndex(FI))
532 CommentOS << MMO->getSize() << "-byte Folded Reload\n";
533 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
534 if (FrameInfo->isSpillSlotObjectIndex(FI)) {
535 MMO = *MI.memoperands_begin();
536 CommentOS << MMO->getSize() << "-byte Spill\n";
537 }
538 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
539 if (FrameInfo->isSpillSlotObjectIndex(FI))
540 CommentOS << MMO->getSize() << "-byte Folded Spill\n";
541 }
542
543 // Check for spill-induced copies
544 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
545 CommentOS << " Reload Reuse\n";
546}
547
548/// emitImplicitDef - This method emits the specified machine instruction
549/// that is an implicit def.
550void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
551 unsigned RegNo = MI->getOperand(0).getReg();
552 OutStreamer.AddComment(Twine("implicit-def: ") +
553 TM.getRegisterInfo()->getName(RegNo));
554 OutStreamer.AddBlankLine();
555}
556
557static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
558 std::string Str = "kill:";
559 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
560 const MachineOperand &Op = MI->getOperand(i);
561 assert(Op.isReg() && "KILL instruction must have only register operands");
562 Str += ' ';
563 Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
564 Str += (Op.isDef() ? "<def>" : "<kill>");
565 }
566 AP.OutStreamer.AddComment(Str);
567 AP.OutStreamer.AddBlankLine();
568}
569
570/// emitDebugValueComment - This method handles the target-independent form
571/// of DBG_VALUE, returning true if it was able to do so. A false return
572/// means the target will need to handle MI in EmitInstruction.
573static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
574 // This code handles only the 3-operand target-independent form.
575 if (MI->getNumOperands() != 3)
576 return false;
577
578 SmallString<128> Str;
579 raw_svector_ostream OS(Str);
580 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
581
582 // cast away const; DIetc do not take const operands for some reason.
583 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
584 if (V.getContext().isSubprogram()) {
585 StringRef Name = DISubprogram(V.getContext()).getDisplayName();
586 if (!Name.empty())
587 OS << Name << ":";
588 }
589 OS << V.getName() << " <- ";
590
591 // The second operand is only an offset if it's an immediate.
592 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
593 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
594
595 // Register or immediate value. Register 0 means undef.
596 if (MI->getOperand(0).isFPImm()) {
597 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
598 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
599 OS << (double)APF.convertToFloat();
600 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
601 OS << APF.convertToDouble();
602 } else {
603 // There is no good way to print long double. Convert a copy to
604 // double. Ah well, it's only a comment.
605 bool ignored;
606 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
607 &ignored);
608 OS << "(long double) " << APF.convertToDouble();
609 }
610 } else if (MI->getOperand(0).isImm()) {
611 OS << MI->getOperand(0).getImm();
612 } else if (MI->getOperand(0).isCImm()) {
613 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
614 } else {
615 unsigned Reg;
616 if (MI->getOperand(0).isReg()) {
617 Reg = MI->getOperand(0).getReg();
618 } else {
619 assert(MI->getOperand(0).isFI() && "Unknown operand type");
620 const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
621 Offset += TFI->getFrameIndexReference(*AP.MF,
622 MI->getOperand(0).getIndex(), Reg);
623 Deref = true;
624 }
625 if (Reg == 0) {
626 // Suppress offset, it is not meaningful here.
627 OS << "undef";
628 // NOTE: Want this comment at start of line, don't emit with AddComment.
629 AP.OutStreamer.EmitRawText(OS.str());
630 return true;
631 }
632 if (Deref)
633 OS << '[';
634 OS << AP.TM.getRegisterInfo()->getName(Reg);
635 }
636
637 if (Deref)
638 OS << '+' << Offset << ']';
639
640 // NOTE: Want this comment at start of line, don't emit with AddComment.
641 AP.OutStreamer.EmitRawText(OS.str());
642 return true;
643}
644
645AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
646 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
647 MF->getFunction()->needsUnwindTableEntry())
648 return CFI_M_EH;
649
650 if (MMI->hasDebugInfo())
651 return CFI_M_Debug;
652
653 return CFI_M_None;
654}
655
656bool AsmPrinter::needsSEHMoves() {
657 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
658 MF->getFunction()->needsUnwindTableEntry();
659}
660
661bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
662 return MAI->doesDwarfUseRelocationsAcrossSections();
663}
664
665void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
666 const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
667
668 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
669 return;
670
671 if (needsCFIMoves() == CFI_M_None)
672 return;
673
674 if (MMI->getCompactUnwindEncoding() != 0)
675 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
676
677 const MachineModuleInfo &MMI = MF->getMMI();
678 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
679 bool FoundOne = false;
680 (void)FoundOne;
681 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
682 E = Instrs.end(); I != E; ++I) {
683 if (I->getLabel() == Label) {
684 emitCFIInstruction(*I);
685 FoundOne = true;
686 }
687 }
688 assert(FoundOne);
689}
690
691/// EmitFunctionBody - This method emits the body and trailer for a
692/// function.
693void AsmPrinter::EmitFunctionBody() {
694 // Emit target-specific gunk before the function body.
695 EmitFunctionBodyStart();
696
697 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
698
699 // Print out code for the function.
700 bool HasAnyRealCode = false;
701 const MachineInstr *LastMI = 0;
702 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
703 I != E; ++I) {
704 // Print a label for the basic block.
705 EmitBasicBlockStart(I);
706 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
707 II != IE; ++II) {
708 LastMI = II;
709
710 // Print the assembly for the instruction.
711 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
712 !II->isDebugValue()) {
713 HasAnyRealCode = true;
714 ++EmittedInsts;
715 }
716
717 if (ShouldPrintDebugScopes) {
718 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
719 DD->beginInstruction(II);
720 }
721
722 if (isVerbose())
723 emitComments(*II, OutStreamer.GetCommentOS());
724
725 switch (II->getOpcode()) {
726 case TargetOpcode::PROLOG_LABEL:
727 emitPrologLabel(*II);
728 break;
729
730 case TargetOpcode::EH_LABEL:
731 case TargetOpcode::GC_LABEL:
732 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
733 break;
734 case TargetOpcode::INLINEASM:
735 EmitInlineAsm(II);
736 break;
737 case TargetOpcode::DBG_VALUE:
738 if (isVerbose()) {
739 if (!emitDebugValueComment(II, *this))
740 EmitInstruction(II);
741 }
742 break;
743 case TargetOpcode::IMPLICIT_DEF:
744 if (isVerbose()) emitImplicitDef(II);
745 break;
746 case TargetOpcode::KILL:
747 if (isVerbose()) emitKill(II, *this);
748 break;
749 default:
750 if (!TM.hasMCUseLoc())
751 MCLineEntry::Make(&OutStreamer, getCurrentSection());
752
753 EmitInstruction(II);
754 break;
755 }
756
757 if (ShouldPrintDebugScopes) {
758 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
759 DD->endInstruction(II);
760 }
761 }
762 }
763
764 // If the last instruction was a prolog label, then we have a situation where
765 // we emitted a prolog but no function body. This results in the ending prolog
766 // label equaling the end of function label and an invalid "row" in the
767 // FDE. We need to emit a noop in this situation so that the FDE's rows are
768 // valid.
769 bool RequiresNoop = LastMI && LastMI->isPrologLabel();
770
771 // If the function is empty and the object file uses .subsections_via_symbols,
772 // then we need to emit *something* to the function body to prevent the
773 // labels from collapsing together. Just emit a noop.
774 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
775 MCInst Noop;
776 TM.getInstrInfo()->getNoopForMachoTarget(Noop);
777 if (Noop.getOpcode()) {
778 OutStreamer.AddComment("avoids zero-length function");
779 OutStreamer.EmitInstruction(Noop);
780 } else // Target not mc-ized yet.
781 OutStreamer.EmitRawText(StringRef("\tnop\n"));
782 }
783
784 const Function *F = MF->getFunction();
785 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
786 const BasicBlock *BB = i;
787 if (!BB->hasAddressTaken())
788 continue;
789 MCSymbol *Sym = GetBlockAddressSymbol(BB);
790 if (Sym->isDefined())
791 continue;
792 OutStreamer.AddComment("Address of block that was removed by CodeGen");
793 OutStreamer.EmitLabel(Sym);
794 }
795
796 // Emit target-specific gunk after the function body.
797 EmitFunctionBodyEnd();
798
799 // If the target wants a .size directive for the size of the function, emit
800 // it.
801 if (MAI->hasDotTypeDotSizeDirective()) {
802 // Create a symbol for the end of function, so we can get the size as
803 // difference between the function label and the temp label.
804 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
805 OutStreamer.EmitLabel(FnEndLabel);
806
807 const MCExpr *SizeExp =
808 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
809 MCSymbolRefExpr::Create(CurrentFnSymForSize,
810 OutContext),
811 OutContext);
812 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
813 }
814
815 // Emit post-function debug information.
816 if (DD) {
817 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
818 DD->endFunction(MF);
819 }
820 if (DE) {
821 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
822 DE->EndFunction();
823 }
824 MMI->EndFunction();
825
826 // Print out jump tables referenced by the function.
827 EmitJumpTableInfo();
828
829 OutStreamer.AddBlankLine();
830}
831
832/// EmitDwarfRegOp - Emit dwarf register operation.
833void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
834 bool Indirect) const {
835 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
836 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
837
838 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0;
839 ++SR) {
840 Reg = TRI->getDwarfRegNum(*SR, false);
841 // FIXME: Get the bit range this register uses of the superregister
842 // so that we can produce a DW_OP_bit_piece
843 }
844
845 // FIXME: Handle cases like a super register being encoded as
846 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
847
848 // FIXME: We have no reasonable way of handling errors in here. The
849 // caller might be in the middle of an dwarf expression. We should
850 // probably assert that Reg >= 0 once debug info generation is more mature.
851
852 if (MLoc.isIndirect() || Indirect) {
853 if (Reg < 32) {
854 OutStreamer.AddComment(
855 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
856 EmitInt8(dwarf::DW_OP_breg0 + Reg);
857 } else {
858 OutStreamer.AddComment("DW_OP_bregx");
859 EmitInt8(dwarf::DW_OP_bregx);
860 OutStreamer.AddComment(Twine(Reg));
861 EmitULEB128(Reg);
862 }
863 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset());
864 if (MLoc.isIndirect() && Indirect)
865 EmitInt8(dwarf::DW_OP_deref);
866 } else {
867 if (Reg < 32) {
868 OutStreamer.AddComment(
869 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
870 EmitInt8(dwarf::DW_OP_reg0 + Reg);
871 } else {
872 OutStreamer.AddComment("DW_OP_regx");
873 EmitInt8(dwarf::DW_OP_regx);
874 OutStreamer.AddComment(Twine(Reg));
875 EmitULEB128(Reg);
876 }
877 }
878
879 // FIXME: Produce a DW_OP_bit_piece if we used a superregister
880}
881
882bool AsmPrinter::doFinalization(Module &M) {
883 // Emit global variables.
884 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
885 I != E; ++I)
886 EmitGlobalVariable(I);
887
888 // Emit visibility info for declarations
889 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
890 const Function &F = *I;
891 if (!F.isDeclaration())
892 continue;
893 GlobalValue::VisibilityTypes V = F.getVisibility();
894 if (V == GlobalValue::DefaultVisibility)
895 continue;
896
897 MCSymbol *Name = getSymbol(&F);
898 EmitVisibility(Name, V, false);
899 }
900
901 // Emit module flags.
902 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
903 M.getModuleFlagsMetadata(ModuleFlags);
904 if (!ModuleFlags.empty())
905 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM);
906
907 // Make sure we wrote out everything we need.
908 OutStreamer.Flush();
909
910 // Finalize debug and EH information.
911 if (DE) {
912 {
913 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
914 DE->EndModule();
915 }
916 delete DE; DE = 0;
917 }
918 if (DD) {
919 {
920 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
921 DD->endModule();
922 }
923 delete DD; DD = 0;
924 }
925
926 // If the target wants to know about weak references, print them all.
927 if (MAI->getWeakRefDirective()) {
928 // FIXME: This is not lazy, it would be nice to only print weak references
929 // to stuff that is actually used. Note that doing so would require targets
930 // to notice uses in operands (due to constant exprs etc). This should
931 // happen with the MC stuff eventually.
932
933 // Print out module-level global variables here.
934 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
935 I != E; ++I) {
936 if (!I->hasExternalWeakLinkage()) continue;
937 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
938 }
939
940 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
941 if (!I->hasExternalWeakLinkage()) continue;
942 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
943 }
944 }
945
946 if (MAI->hasSetDirective()) {
947 OutStreamer.AddBlankLine();
948 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
949 I != E; ++I) {
950 MCSymbol *Name = getSymbol(I);
951
952 const GlobalValue *GV = I->getAliasedGlobal();
953 if (GV->isDeclaration()) {
954 report_fatal_error(Name->getName() +
955 ": Target doesn't support aliases to declarations");
956 }
957
958 MCSymbol *Target = getSymbol(GV);
959
960 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
961 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
962 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
963 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
964 else
965 assert(I->hasLocalLinkage() && "Invalid alias linkage");
966
967 EmitVisibility(Name, I->getVisibility());
968
969 // Emit the directives as assignments aka .set:
970 OutStreamer.EmitAssignment(Name,
971 MCSymbolRefExpr::Create(Target, OutContext));
972 }
973 }
974
975 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
976 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
977 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
978 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
979 MP->finishAssembly(*this);
980
981 // Emit llvm.ident metadata in an '.ident' directive.
982 EmitModuleIdents(M);
983
984 // If we don't have any trampolines, then we don't require stack memory
985 // to be executable. Some targets have a directive to declare this.
986 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
987 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
988 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
989 OutStreamer.SwitchSection(S);
990
991 // Allow the target to emit any magic that it wants at the end of the file,
992 // after everything else has gone out.
993 EmitEndOfAsmFile(M);
994
995 delete Mang; Mang = 0;
996 MMI = 0;
997
998 OutStreamer.Finish();
999 OutStreamer.reset();
1000
1001 return false;
1002}
1003
1004void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1005 this->MF = &MF;
1006 // Get the function symbol.
1007 CurrentFnSym = getSymbol(MF.getFunction());
1008 CurrentFnSymForSize = CurrentFnSym;
1009
1010 if (isVerbose())
1011 LI = &getAnalysis<MachineLoopInfo>();
1012}
1013
1014namespace {
1015 // SectionCPs - Keep track the alignment, constpool entries per Section.
1016 struct SectionCPs {
1017 const MCSection *S;
1018 unsigned Alignment;
1019 SmallVector<unsigned, 4> CPEs;
1020 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1021 };
1022}
1023
1024/// EmitConstantPool - Print to the current output stream assembly
1025/// representations of the constants in the constant pool MCP. This is
1026/// used to print out constants which have been "spilled to memory" by
1027/// the code generator.
1028///
1029void AsmPrinter::EmitConstantPool() {
1030 const MachineConstantPool *MCP = MF->getConstantPool();
1031 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1032 if (CP.empty()) return;
1033
1034 // Calculate sections for constant pool entries. We collect entries to go into
1035 // the same section together to reduce amount of section switch statements.
1036 SmallVector<SectionCPs, 4> CPSections;
1037 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1038 const MachineConstantPoolEntry &CPE = CP[i];
1039 unsigned Align = CPE.getAlignment();
1040
1041 SectionKind Kind;
1042 switch (CPE.getRelocationInfo()) {
1043 default: llvm_unreachable("Unknown section kind");
1044 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1045 case 1:
1046 Kind = SectionKind::getReadOnlyWithRelLocal();
1047 break;
1048 case 0:
1049 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1050 case 4: Kind = SectionKind::getMergeableConst4(); break;
1051 case 8: Kind = SectionKind::getMergeableConst8(); break;
1052 case 16: Kind = SectionKind::getMergeableConst16();break;
1053 default: Kind = SectionKind::getMergeableConst(); break;
1054 }
1055 }
1056
1057 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1058
1059 // The number of sections are small, just do a linear search from the
1060 // last section to the first.
1061 bool Found = false;
1062 unsigned SecIdx = CPSections.size();
1063 while (SecIdx != 0) {
1064 if (CPSections[--SecIdx].S == S) {
1065 Found = true;
1066 break;
1067 }
1068 }
1069 if (!Found) {
1070 SecIdx = CPSections.size();
1071 CPSections.push_back(SectionCPs(S, Align));
1072 }
1073
1074 if (Align > CPSections[SecIdx].Alignment)
1075 CPSections[SecIdx].Alignment = Align;
1076 CPSections[SecIdx].CPEs.push_back(i);
1077 }
1078
1079 // Now print stuff into the calculated sections.
1080 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1081 OutStreamer.SwitchSection(CPSections[i].S);
1082 EmitAlignment(Log2_32(CPSections[i].Alignment));
1083
1084 unsigned Offset = 0;
1085 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1086 unsigned CPI = CPSections[i].CPEs[j];
1087 MachineConstantPoolEntry CPE = CP[CPI];
1088
1089 // Emit inter-object padding for alignment.
1090 unsigned AlignMask = CPE.getAlignment() - 1;
1091 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1092 OutStreamer.EmitZeros(NewOffset - Offset);
1093
1094 Type *Ty = CPE.getType();
1095 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1096 OutStreamer.EmitLabel(GetCPISymbol(CPI));
1097
1098 if (CPE.isMachineConstantPoolEntry())
1099 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1100 else
1101 EmitGlobalConstant(CPE.Val.ConstVal);
1102 }
1103 }
1104}
1105
1106/// EmitJumpTableInfo - Print assembly representations of the jump tables used
1107/// by the current function to the current output stream.
1108///
1109void AsmPrinter::EmitJumpTableInfo() {
1110 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1111 if (MJTI == 0) return;
1112 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1113 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1114 if (JT.empty()) return;
1115
1116 // Pick the directive to use to print the jump table entries, and switch to
1117 // the appropriate section.
1118 const Function *F = MF->getFunction();
1119 bool JTInDiffSection = false;
1120 if (// In PIC mode, we need to emit the jump table to the same section as the
1121 // function body itself, otherwise the label differences won't make sense.
1122 // FIXME: Need a better predicate for this: what about custom entries?
1123 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1124 // We should also do if the section name is NULL or function is declared
1125 // in discardable section
1126 // FIXME: this isn't the right predicate, should be based on the MCSection
1127 // for the function.
1128 F->isWeakForLinker()) {
1129 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1130 } else {
1131 // Otherwise, drop it in the readonly section.
1132 const MCSection *ReadOnlySection =
1133 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1134 OutStreamer.SwitchSection(ReadOnlySection);
1135 JTInDiffSection = true;
1136 }
1137
1138 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1139
1140 // Jump tables in code sections are marked with a data_region directive
1141 // where that's supported.
1142 if (!JTInDiffSection)
1143 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1144
1145 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1146 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1147
1148 // If this jump table was deleted, ignore it.
1149 if (JTBBs.empty()) continue;
1150
1151 // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1152 // .set directive for each unique entry. This reduces the number of
1153 // relocations the assembler will generate for the jump table.
1154 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1155 MAI->hasSetDirective()) {
1156 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1157 const TargetLowering *TLI = TM.getTargetLowering();
1158 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1159 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1160 const MachineBasicBlock *MBB = JTBBs[ii];
1161 if (!EmittedSets.insert(MBB)) continue;
1162
1163 // .set LJTSet, LBB32-base
1164 const MCExpr *LHS =
1165 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1166 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1167 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1168 }
1169 }
1170
1171 // On some targets (e.g. Darwin) we want to emit two consecutive labels
1172 // before each jump table. The first label is never referenced, but tells
1173 // the assembler and linker the extents of the jump table object. The
1174 // second label is actually referenced by the code.
1175 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1176 // FIXME: This doesn't have to have any specific name, just any randomly
1177 // named and numbered 'l' label would work. Simplify GetJTISymbol.
1178 OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1179
1180 OutStreamer.EmitLabel(GetJTISymbol(JTI));
1181
1182 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1183 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1184 }
1185 if (!JTInDiffSection)
1186 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1187}
1188
1189/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1190/// current stream.
1191void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1192 const MachineBasicBlock *MBB,
1193 unsigned UID) const {
1194 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1195 const MCExpr *Value = 0;
1196 switch (MJTI->getEntryKind()) {
1197 case MachineJumpTableInfo::EK_Inline:
1198 llvm_unreachable("Cannot emit EK_Inline jump table entry");
1199 case MachineJumpTableInfo::EK_Custom32:
1200 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1201 OutContext);
1202 break;
1203 case MachineJumpTableInfo::EK_BlockAddress:
1204 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1205 // .word LBB123
1206 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1207 break;
1208 case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1209 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1210 // with a relocation as gp-relative, e.g.:
1211 // .gprel32 LBB123
1212 MCSymbol *MBBSym = MBB->getSymbol();
1213 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1214 return;
1215 }
1216
1217 case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1218 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1219 // with a relocation as gp-relative, e.g.:
1220 // .gpdword LBB123
1221 MCSymbol *MBBSym = MBB->getSymbol();
1222 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1223 return;
1224 }
1225
1226 case MachineJumpTableInfo::EK_LabelDifference32: {
1227 // EK_LabelDifference32 - Each entry is the address of the block minus
1228 // the address of the jump table. This is used for PIC jump tables where
1229 // gprel32 is not supported. e.g.:
1230 // .word LBB123 - LJTI1_2
1231 // If the .set directive is supported, this is emitted as:
1232 // .set L4_5_set_123, LBB123 - LJTI1_2
1233 // .word L4_5_set_123
1234
1235 // If we have emitted set directives for the jump table entries, print
1236 // them rather than the entries themselves. If we're emitting PIC, then
1237 // emit the table entries as differences between two text section labels.
1238 if (MAI->hasSetDirective()) {
1239 // If we used .set, reference the .set's symbol.
1240 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1241 OutContext);
1242 break;
1243 }
1244 // Otherwise, use the difference as the jump table entry.
1245 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1246 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1247 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1248 break;
1249 }
1250 }
1251
1252 assert(Value && "Unknown entry kind!");
1253
1254 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1255 OutStreamer.EmitValue(Value, EntrySize);
1256}
1257
1258
1259/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1260/// special global used by LLVM. If so, emit it and return true, otherwise
1261/// do nothing and return false.
1262bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1263 if (GV->getName() == "llvm.used") {
1264 if (MAI->hasNoDeadStrip()) // No need to emit this at all.
1265 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1266 return true;
1267 }
1268
1269 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
1270 if (GV->getSection() == "llvm.metadata" ||
1271 GV->hasAvailableExternallyLinkage())
1272 return true;
1273
1274 if (!GV->hasAppendingLinkage()) return false;
1275
1276 assert(GV->hasInitializer() && "Not a special LLVM global!");
1277
1278 if (GV->getName() == "llvm.global_ctors") {
1279 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1280
1281 if (TM.getRelocationModel() == Reloc::Static &&
1282 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1283 StringRef Sym(".constructors_used");
1284 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1285 MCSA_Reference);
1286 }
1287 return true;
1288 }
1289
1290 if (GV->getName() == "llvm.global_dtors") {
1291 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1292
1293 if (TM.getRelocationModel() == Reloc::Static &&
1294 MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1295 StringRef Sym(".destructors_used");
1296 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1297 MCSA_Reference);
1298 }
1299 return true;
1300 }
1301
1302 return false;
1303}
1304
1305/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1306/// global in the specified llvm.used list for which emitUsedDirectiveFor
1307/// is true, as being used with this directive.
1308void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1309 // Should be an array of 'i8*'.
1310 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1311 const GlobalValue *GV =
1312 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1313 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1314 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1315 }
1316}
1317
1318/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1319/// priority.
1320void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1321 // Should be an array of '{ int, void ()* }' structs. The first value is the
1322 // init priority.
1323 if (!isa<ConstantArray>(List)) return;
1324
1325 // Sanity check the structors list.
1326 const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1327 if (!InitList) return; // Not an array!
1328 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1329 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1330 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1331 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1332
1333 // Gather the structors in a form that's convenient for sorting by priority.
1334 typedef std::pair<unsigned, Constant *> Structor;
1335 SmallVector<Structor, 8> Structors;
1336 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1337 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1338 if (!CS) continue; // Malformed.
1339 if (CS->getOperand(1)->isNullValue())
1340 break; // Found a null terminator, skip the rest.
1341 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1342 if (!Priority) continue; // Malformed.
1343 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1344 CS->getOperand(1)));
1345 }
1346
1347 // Emit the function pointers in the target-specific order
1348 const DataLayout *DL = TM.getDataLayout();
1349 unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1350 std::stable_sort(Structors.begin(), Structors.end(), less_first());
1351 for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1352 const MCSection *OutputSection =
1353 (isCtor ?
1354 getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1355 getObjFileLowering().getStaticDtorSection(Structors[i].first));
1356 OutStreamer.SwitchSection(OutputSection);
1357 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1358 EmitAlignment(Align);
1359 EmitXXStructor(Structors[i].second);
1360 }
1361}
1362
1363void AsmPrinter::EmitModuleIdents(Module &M) {
1364 if (!MAI->hasIdentDirective())
1365 return;
1366
1367 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1368 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1369 const MDNode *N = NMD->getOperand(i);
1370 assert(N->getNumOperands() == 1 &&
1371 "llvm.ident metadata entry can have only one operand");
1372 const MDString *S = cast<MDString>(N->getOperand(0));
1373 OutStreamer.EmitIdent(S->getString());
1374 }
1375 }
1376}
1377
1378//===--------------------------------------------------------------------===//
1379// Emission and print routines
1380//
1381
1382/// EmitInt8 - Emit a byte directive and value.
1383///
1384void AsmPrinter::EmitInt8(int Value) const {
1385 OutStreamer.EmitIntValue(Value, 1);
1386}
1387
1388/// EmitInt16 - Emit a short directive and value.
1389///
1390void AsmPrinter::EmitInt16(int Value) const {
1391 OutStreamer.EmitIntValue(Value, 2);
1392}
1393
1394/// EmitInt32 - Emit a long directive and value.
1395///
1396void AsmPrinter::EmitInt32(int Value) const {
1397 OutStreamer.EmitIntValue(Value, 4);
1398}
1399
1400/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1401/// in bytes of the directive is specified by Size and Hi/Lo specify the
1402/// labels. This implicitly uses .set if it is available.
1403void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1404 unsigned Size) const {
1405 // Get the Hi-Lo expression.
1406 const MCExpr *Diff =
1407 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1408 MCSymbolRefExpr::Create(Lo, OutContext),
1409 OutContext);
1410
1411 if (!MAI->hasSetDirective()) {
1412 OutStreamer.EmitValue(Diff, Size);
1413 return;
1414 }
1415
1416 // Otherwise, emit with .set (aka assignment).
1417 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1418 OutStreamer.EmitAssignment(SetLabel, Diff);
1419 OutStreamer.EmitSymbolValue(SetLabel, Size);
1420}
1421
1422/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1423/// where the size in bytes of the directive is specified by Size and Hi/Lo
1424/// specify the labels. This implicitly uses .set if it is available.
1425void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1426 const MCSymbol *Lo, unsigned Size)
1427 const {
1428
1429 // Emit Hi+Offset - Lo
1430 // Get the Hi+Offset expression.
1431 const MCExpr *Plus =
1432 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1433 MCConstantExpr::Create(Offset, OutContext),
1434 OutContext);
1435
1436 // Get the Hi+Offset-Lo expression.
1437 const MCExpr *Diff =
1438 MCBinaryExpr::CreateSub(Plus,
1439 MCSymbolRefExpr::Create(Lo, OutContext),
1440 OutContext);
1441
1442 if (!MAI->hasSetDirective())
1443 OutStreamer.EmitValue(Diff, Size);
1444 else {
1445 // Otherwise, emit with .set (aka assignment).
1446 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1447 OutStreamer.EmitAssignment(SetLabel, Diff);
1448 OutStreamer.EmitSymbolValue(SetLabel, Size);
1449 }
1450}
1451
1452/// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1453/// where the size in bytes of the directive is specified by Size and Label
1454/// specifies the label. This implicitly uses .set if it is available.
1455void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1456 unsigned Size, bool IsSectionRelative)
1457 const {
1458 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1459 OutStreamer.EmitCOFFSecRel32(Label);
1460 return;
1461 }
1462
1463 // Emit Label+Offset (or just Label if Offset is zero)
1464 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1465 if (Offset)
1466 Expr = MCBinaryExpr::CreateAdd(Expr,
1467 MCConstantExpr::Create(Offset, OutContext),
1468 OutContext);
1469
1470 OutStreamer.EmitValue(Expr, Size);
1471}
1472
1473
1474//===----------------------------------------------------------------------===//
1475
1476// EmitAlignment - Emit an alignment directive to the specified power of
1477// two boundary. For example, if you pass in 3 here, you will get an 8
1478// byte alignment. If a global value is specified, and if that global has
1479// an explicit alignment requested, it will override the alignment request
1480// if required for correctness.
1481//
1482void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1483 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1484
1485 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment.
1486
1487 if (getCurrentSection()->getKind().isText())
1488 OutStreamer.EmitCodeAlignment(1 << NumBits);
1489 else
1490 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1491}
1492
1493//===----------------------------------------------------------------------===//
1494// Constant emission.
1495//===----------------------------------------------------------------------===//
1496
1497/// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1498///
1499static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1500 MCContext &Ctx = AP.OutContext;
1501
1502 if (CV->isNullValue() || isa<UndefValue>(CV))
1503 return MCConstantExpr::Create(0, Ctx);
1504
1505 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1506 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1507
1508 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1509 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1510
1511 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1512 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1513
1514 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1515 if (CE == 0) {
1516 llvm_unreachable("Unknown constant value to lower!");
1517 }
1518
1519 switch (CE->getOpcode()) {
1520 default:
1521 // If the code isn't optimized, there may be outstanding folding
1522 // opportunities. Attempt to fold the expression using DataLayout as a
1523 // last resort before giving up.
1524 if (Constant *C =
1525 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1526 if (C != CE)
1527 return lowerConstant(C, AP);
1528
1529 // Otherwise report the problem to the user.
1530 {
1531 std::string S;
1532 raw_string_ostream OS(S);
1533 OS << "Unsupported expression in static initializer: ";
1534 WriteAsOperand(OS, CE, /*PrintType=*/false,
1535 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1536 report_fatal_error(OS.str());
1537 }
1538 case Instruction::GetElementPtr: {
1539 const DataLayout &DL = *AP.TM.getDataLayout();
1540 // Generate a symbolic expression for the byte address
1541 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1542 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1543
1544 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1545 if (!OffsetAI)
1546 return Base;
1547
1548 int64_t Offset = OffsetAI.getSExtValue();
1549 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1550 Ctx);
1551 }
1552
1553 case Instruction::Trunc:
1554 // We emit the value and depend on the assembler to truncate the generated
1555 // expression properly. This is important for differences between
1556 // blockaddress labels. Since the two labels are in the same function, it
1557 // is reasonable to treat their delta as a 32-bit value.
1558 // FALL THROUGH.
1559 case Instruction::BitCast:
1560 return lowerConstant(CE->getOperand(0), AP);
1561
1562 case Instruction::IntToPtr: {
1563 const DataLayout &DL = *AP.TM.getDataLayout();
1564 // Handle casts to pointers by changing them into casts to the appropriate
1565 // integer type. This promotes constant folding and simplifies this code.
1566 Constant *Op = CE->getOperand(0);
1567 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1568 false/*ZExt*/);
1569 return lowerConstant(Op, AP);
1570 }
1571
1572 case Instruction::PtrToInt: {
1573 const DataLayout &DL = *AP.TM.getDataLayout();
1574 // Support only foldable casts to/from pointers that can be eliminated by
1575 // changing the pointer to the appropriately sized integer type.
1576 Constant *Op = CE->getOperand(0);
1577 Type *Ty = CE->getType();
1578
1579 const MCExpr *OpExpr = lowerConstant(Op, AP);
1580
1581 // We can emit the pointer value into this slot if the slot is an
1582 // integer slot equal to the size of the pointer.
1583 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1584 return OpExpr;
1585
1586 // Otherwise the pointer is smaller than the resultant integer, mask off
1587 // the high bits so we are sure to get a proper truncation if the input is
1588 // a constant expr.
1589 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1590 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1591 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1592 }
1593
1594 // The MC library also has a right-shift operator, but it isn't consistently
1595 // signed or unsigned between different targets.
1596 case Instruction::Add:
1597 case Instruction::Sub:
1598 case Instruction::Mul:
1599 case Instruction::SDiv:
1600 case Instruction::SRem:
1601 case Instruction::Shl:
1602 case Instruction::And:
1603 case Instruction::Or:
1604 case Instruction::Xor: {
1605 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1606 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1607 switch (CE->getOpcode()) {
1608 default: llvm_unreachable("Unknown binary operator constant cast expr");
1609 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1610 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1611 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1612 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1613 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1614 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1615 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1616 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1617 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1618 }
1619 }
1620 }
1621}
1622
1623static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1624
1625/// isRepeatedByteSequence - Determine whether the given value is
1626/// composed of a repeated sequence of identical bytes and return the
1627/// byte value. If it is not a repeated sequence, return -1.
1628static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1629 StringRef Data = V->getRawDataValues();
1630 assert(!Data.empty() && "Empty aggregates should be CAZ node");
1631 char C = Data[0];
1632 for (unsigned i = 1, e = Data.size(); i != e; ++i)
1633 if (Data[i] != C) return -1;
1634 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1635}
1636
1637
1638/// isRepeatedByteSequence - Determine whether the given value is
1639/// composed of a repeated sequence of identical bytes and return the
1640/// byte value. If it is not a repeated sequence, return -1.
1641static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1642
1643 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1644 if (CI->getBitWidth() > 64) return -1;
1645
1646 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1647 uint64_t Value = CI->getZExtValue();
1648
1649 // Make sure the constant is at least 8 bits long and has a power
1650 // of 2 bit width. This guarantees the constant bit width is
1651 // always a multiple of 8 bits, avoiding issues with padding out
1652 // to Size and other such corner cases.
1653 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1654
1655 uint8_t Byte = static_cast<uint8_t>(Value);
1656
1657 for (unsigned i = 1; i < Size; ++i) {
1658 Value >>= 8;
1659 if (static_cast<uint8_t>(Value) != Byte) return -1;
1660 }
1661 return Byte;
1662 }
1663 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1664 // Make sure all array elements are sequences of the same repeated
1665 // byte.
1666 assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1667 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1668 if (Byte == -1) return -1;
1669
1670 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1671 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1672 if (ThisByte == -1) return -1;
1673 if (Byte != ThisByte) return -1;
1674 }
1675 return Byte;
1676 }
1677
1678 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1679 return isRepeatedByteSequence(CDS);
1680
1681 return -1;
1682}
1683
1684static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1685 AsmPrinter &AP){
1686
1687 // See if we can aggregate this into a .fill, if so, emit it as such.
1688 int Value = isRepeatedByteSequence(CDS, AP.TM);
1689 if (Value != -1) {
1690 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1691 // Don't emit a 1-byte object as a .fill.
1692 if (Bytes > 1)
1693 return AP.OutStreamer.EmitFill(Bytes, Value);
1694 }
1695
1696 // If this can be emitted with .ascii/.asciz, emit it as such.
1697 if (CDS->isString())
1698 return AP.OutStreamer.EmitBytes(CDS->getAsString());
1699
1700 // Otherwise, emit the values in successive locations.
1701 unsigned ElementByteSize = CDS->getElementByteSize();
1702 if (isa<IntegerType>(CDS->getElementType())) {
1703 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1704 if (AP.isVerbose())
1705 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1706 CDS->getElementAsInteger(i));
1707 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1708 ElementByteSize);
1709 }
1710 } else if (ElementByteSize == 4) {
1711 // FP Constants are printed as integer constants to avoid losing
1712 // precision.
1713 assert(CDS->getElementType()->isFloatTy());
1714 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1715 union {
1716 float F;
1717 uint32_t I;
1718 };
1719
1720 F = CDS->getElementAsFloat(i);
1721 if (AP.isVerbose())
1722 AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1723 AP.OutStreamer.EmitIntValue(I, 4);
1724 }
1725 } else {
1726 assert(CDS->getElementType()->isDoubleTy());
1727 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1728 union {
1729 double F;
1730 uint64_t I;
1731 };
1732
1733 F = CDS->getElementAsDouble(i);
1734 if (AP.isVerbose())
1735 AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1736 AP.OutStreamer.EmitIntValue(I, 8);
1737 }
1738 }
1739
1740 const DataLayout &DL = *AP.TM.getDataLayout();
1741 unsigned Size = DL.getTypeAllocSize(CDS->getType());
1742 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1743 CDS->getNumElements();
1744 if (unsigned Padding = Size - EmittedSize)
1745 AP.OutStreamer.EmitZeros(Padding);
1746
1747}
1748
1749static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1750 // See if we can aggregate some values. Make sure it can be
1751 // represented as a series of bytes of the constant value.
1752 int Value = isRepeatedByteSequence(CA, AP.TM);
1753
1754 if (Value != -1) {
1755 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1756 AP.OutStreamer.EmitFill(Bytes, Value);
1757 }
1758 else {
1759 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1760 emitGlobalConstantImpl(CA->getOperand(i), AP);
1761 }
1762}
1763
1764static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1765 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1766 emitGlobalConstantImpl(CV->getOperand(i), AP);
1767
1768 const DataLayout &DL = *AP.TM.getDataLayout();
1769 unsigned Size = DL.getTypeAllocSize(CV->getType());
1770 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1771 CV->getType()->getNumElements();
1772 if (unsigned Padding = Size - EmittedSize)
1773 AP.OutStreamer.EmitZeros(Padding);
1774}
1775
1776static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1777 // Print the fields in successive locations. Pad to align if needed!
1778 const DataLayout *DL = AP.TM.getDataLayout();
1779 unsigned Size = DL->getTypeAllocSize(CS->getType());
1780 const StructLayout *Layout = DL->getStructLayout(CS->getType());
1781 uint64_t SizeSoFar = 0;
1782 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1783 const Constant *Field = CS->getOperand(i);
1784
1785 // Check if padding is needed and insert one or more 0s.
1786 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1787 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1788 - Layout->getElementOffset(i)) - FieldSize;
1789 SizeSoFar += FieldSize + PadSize;
1790
1791 // Now print the actual field value.
1792 emitGlobalConstantImpl(Field, AP);
1793
1794 // Insert padding - this may include padding to increase the size of the
1795 // current field up to the ABI size (if the struct is not packed) as well
1796 // as padding to ensure that the next field starts at the right offset.
1797 AP.OutStreamer.EmitZeros(PadSize);
1798 }
1799 assert(SizeSoFar == Layout->getSizeInBytes() &&
1800 "Layout of constant struct may be incorrect!");
1801}
1802
1803static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1804 APInt API = CFP->getValueAPF().bitcastToAPInt();
1805
1806 // First print a comment with what we think the original floating-point value
1807 // should have been.
1808 if (AP.isVerbose()) {
1809 SmallString<8> StrVal;
1810 CFP->getValueAPF().toString(StrVal);
1811
1812 CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1813 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1814 }
1815
1816 // Now iterate through the APInt chunks, emitting them in endian-correct
1817 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1818 // floats).
1819 unsigned NumBytes = API.getBitWidth() / 8;
1820 unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1821 const uint64_t *p = API.getRawData();
1822
1823 // PPC's long double has odd notions of endianness compared to how LLVM
1824 // handles it: p[0] goes first for *big* endian on PPC.
1825 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1826 int Chunk = API.getNumWords() - 1;
1827
1828 if (TrailingBytes)
1829 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1830
1831 for (; Chunk >= 0; --Chunk)
1832 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1833 } else {
1834 unsigned Chunk;
1835 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1836 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1837
1838 if (TrailingBytes)
1839 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1840 }
1841
1842 // Emit the tail padding for the long double.
1843 const DataLayout &DL = *AP.TM.getDataLayout();
1844 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1845 DL.getTypeStoreSize(CFP->getType()));
1846}
1847
1848static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1849 const DataLayout *DL = AP.TM.getDataLayout();
1850 unsigned BitWidth = CI->getBitWidth();
1851
1852 // Copy the value as we may massage the layout for constants whose bit width
1853 // is not a multiple of 64-bits.
1854 APInt Realigned(CI->getValue());
1855 uint64_t ExtraBits = 0;
1856 unsigned ExtraBitsSize = BitWidth & 63;
1857
1858 if (ExtraBitsSize) {
1859 // The bit width of the data is not a multiple of 64-bits.
1860 // The extra bits are expected to be at the end of the chunk of the memory.
1861 // Little endian:
1862 // * Nothing to be done, just record the extra bits to emit.
1863 // Big endian:
1864 // * Record the extra bits to emit.
1865 // * Realign the raw data to emit the chunks of 64-bits.
1866 if (DL->isBigEndian()) {
1867 // Basically the structure of the raw data is a chunk of 64-bits cells:
1868 // 0 1 BitWidth / 64
1869 // [chunk1][chunk2] ... [chunkN].
1870 // The most significant chunk is chunkN and it should be emitted first.
1871 // However, due to the alignment issue chunkN contains useless bits.
1872 // Realign the chunks so that they contain only useless information:
1873 // ExtraBits 0 1 (BitWidth / 64) - 1
1874 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
1875 ExtraBits = Realigned.getRawData()[0] &
1876 (((uint64_t)-1) >> (64 - ExtraBitsSize));
1877 Realigned = Realigned.lshr(ExtraBitsSize);
1878 } else
1879 ExtraBits = Realigned.getRawData()[BitWidth / 64];
1880 }
1881
1882 // We don't expect assemblers to support integer data directives
1883 // for more than 64 bits, so we emit the data in at most 64-bit
1884 // quantities at a time.
1885 const uint64_t *RawData = Realigned.getRawData();
1886 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1887 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1888 AP.OutStreamer.EmitIntValue(Val, 8);
1889 }
1890
1891 if (ExtraBitsSize) {
1892 // Emit the extra bits after the 64-bits chunks.
1893
1894 // Emit a directive that fills the expected size.
1895 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
1896 Size -= (BitWidth / 64) * 8;
1897 assert(Size && Size * 8 >= ExtraBitsSize &&
1898 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
1899 == ExtraBits && "Directive too small for extra bits.");
1900 AP.OutStreamer.EmitIntValue(ExtraBits, Size);
1901 }
1902}
1903
1904static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
1905 const DataLayout *DL = AP.TM.getDataLayout();
1906 uint64_t Size = DL->getTypeAllocSize(CV->getType());
1907 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
1908 return AP.OutStreamer.EmitZeros(Size);
1909
1910 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1911 switch (Size) {
1912 case 1:
1913 case 2:
1914 case 4:
1915 case 8:
1916 if (AP.isVerbose())
1917 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1918 CI->getZExtValue());
1919 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
1920 return;
1921 default:
1922 emitGlobalConstantLargeInt(CI, AP);
1923 return;
1924 }
1925 }
1926
1927 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1928 return emitGlobalConstantFP(CFP, AP);
1929
1930 if (isa<ConstantPointerNull>(CV)) {
1931 AP.OutStreamer.EmitIntValue(0, Size);
1932 return;
1933 }
1934
1935 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
1936 return emitGlobalConstantDataSequential(CDS, AP);
1937
1938 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1939 return emitGlobalConstantArray(CVA, AP);
1940
1941 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1942 return emitGlobalConstantStruct(CVS, AP);
1943
1944 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1945 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
1946 // vectors).
1947 if (CE->getOpcode() == Instruction::BitCast)
1948 return emitGlobalConstantImpl(CE->getOperand(0), AP);
1949
1950 if (Size > 8) {
1951 // If the constant expression's size is greater than 64-bits, then we have
1952 // to emit the value in chunks. Try to constant fold the value and emit it
1953 // that way.
1954 Constant *New = ConstantFoldConstantExpression(CE, DL);
1955 if (New && New != CE)
1956 return emitGlobalConstantImpl(New, AP);
1957 }
1958 }
1959
1960 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1961 return emitGlobalConstantVector(V, AP);
1962
1963 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
1964 // thread the streamer with EmitValue.
1965 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
1966}
1967
1968/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1969void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
1970 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
1971 if (Size)
1972 emitGlobalConstantImpl(CV, *this);
1973 else if (MAI->hasSubsectionsViaSymbols()) {
1974 // If the global has zero size, emit a single byte so that two labels don't
1975 // look like they are at the same location.
1976 OutStreamer.EmitIntValue(0, 1);
1977 }
1978}
1979
1980void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1981 // Target doesn't support this yet!
1982 llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1983}
1984
1985void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1986 if (Offset > 0)
1987 OS << '+' << Offset;
1988 else if (Offset < 0)
1989 OS << Offset;
1990}
1991
1992//===----------------------------------------------------------------------===//
1993// Symbol Lowering Routines.
1994//===----------------------------------------------------------------------===//
1995
1996/// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1997/// temporary label with the specified stem and unique ID.
1998MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1999 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
2000 Name + Twine(ID));
2001}
2002
2003/// GetTempSymbol - Return an assembler temporary label with the specified
2004/// stem.
2005MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2006 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
2007 Name);
2008}
2009
2010
2011MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2012 return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2013}
2014
2015MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2016 return MMI->getAddrLabelSymbol(BB);
2017}
2018
2019/// GetCPISymbol - Return the symbol for the specified constant pool entry.
2020MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2021 return OutContext.GetOrCreateSymbol
2022 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2023 + "_" + Twine(CPID));
2024}
2025
2026/// GetJTISymbol - Return the symbol for the specified jump table entry.
2027MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2028 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2029}
2030
2031/// GetJTSetSymbol - Return the symbol for the specified jump table .set
2032/// FIXME: privatize to AsmPrinter.
2033MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2034 return OutContext.GetOrCreateSymbol
2035 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2036 Twine(UID) + "_set_" + Twine(MBBID));
2037}
2038
2039/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
2040/// global value name as its base, with the specified suffix, and where the
2041/// symbol is forced to have private linkage if ForcePrivate is true.
2042MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
2043 StringRef Suffix,
2044 bool ForcePrivate) const {
2045 SmallString<60> NameStr;
2046 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
2047 NameStr.append(Suffix.begin(), Suffix.end());
2048 return OutContext.GetOrCreateSymbol(NameStr.str());
2049}
2050
2051/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2052/// ExternalSymbol.
2053MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2054 SmallString<60> NameStr;
2055 Mang->getNameWithPrefix(NameStr, Sym);
2056 return OutContext.GetOrCreateSymbol(NameStr.str());
2057}
2058
2059
2060
2061/// PrintParentLoopComment - Print comments about parent loops of this one.
2062static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2063 unsigned FunctionNumber) {
2064 if (Loop == 0) return;
2065 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2066 OS.indent(Loop->getLoopDepth()*2)
2067 << "Parent Loop BB" << FunctionNumber << "_"
2068 << Loop->getHeader()->getNumber()
2069 << " Depth=" << Loop->getLoopDepth() << '\n';
2070}
2071
2072
2073/// PrintChildLoopComment - Print comments about child loops within
2074/// the loop for this basic block, with nesting.
2075static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2076 unsigned FunctionNumber) {
2077 // Add child loop information
2078 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2079 OS.indent((*CL)->getLoopDepth()*2)
2080 << "Child Loop BB" << FunctionNumber << "_"
2081 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2082 << '\n';
2083 PrintChildLoopComment(OS, *CL, FunctionNumber);
2084 }
2085}
2086
2087/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2088static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2089 const MachineLoopInfo *LI,
2090 const AsmPrinter &AP) {
2091 // Add loop depth information
2092 const MachineLoop *Loop = LI->getLoopFor(&MBB);
2093 if (Loop == 0) return;
2094
2095 MachineBasicBlock *Header = Loop->getHeader();
2096 assert(Header && "No header for loop");
2097
2098 // If this block is not a loop header, just print out what is the loop header
2099 // and return.
2100 if (Header != &MBB) {
2101 AP.OutStreamer.AddComment(" in Loop: Header=BB" +
2102 Twine(AP.getFunctionNumber())+"_" +
2103 Twine(Loop->getHeader()->getNumber())+
2104 " Depth="+Twine(Loop->getLoopDepth()));
2105 return;
2106 }
2107
2108 // Otherwise, it is a loop header. Print out information about child and
2109 // parent loops.
2110 raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2111
2112 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2113
2114 OS << "=>";
2115 OS.indent(Loop->getLoopDepth()*2-2);
2116
2117 OS << "This ";
2118 if (Loop->empty())
2119 OS << "Inner ";
2120 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2121
2122 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2123}
2124
2125
2126/// EmitBasicBlockStart - This method prints the label for the specified
2127/// MachineBasicBlock, an alignment (if present) and a comment describing
2128/// it if appropriate.
2129void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2130 // Emit an alignment directive for this block, if needed.
2131 if (unsigned Align = MBB->getAlignment())
2132 EmitAlignment(Align);
2133
2134 // If the block has its address taken, emit any labels that were used to
2135 // reference the block. It is possible that there is more than one label
2136 // here, because multiple LLVM BB's may have been RAUW'd to this block after
2137 // the references were generated.
2138 if (MBB->hasAddressTaken()) {
2139 const BasicBlock *BB = MBB->getBasicBlock();
2140 if (isVerbose())
2141 OutStreamer.AddComment("Block address taken");
2142
2143 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2144
2145 for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2146 OutStreamer.EmitLabel(Syms[i]);
2147 }
2148
2149 // Print some verbose block comments.
2150 if (isVerbose()) {
2151 if (const BasicBlock *BB = MBB->getBasicBlock())
2152 if (BB->hasName())
2153 OutStreamer.AddComment("%" + BB->getName());
2154 emitBasicBlockLoopComments(*MBB, LI, *this);
2155 }
2156
2157 // Print the main label for the block.
2158 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2159 if (isVerbose() && OutStreamer.hasRawTextSupport()) {
2160 // NOTE: Want this comment at start of line, don't emit with AddComment.
2161 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
2162 Twine(MBB->getNumber()) + ":");
2163 }
2164 } else {
2165 OutStreamer.EmitLabel(MBB->getSymbol());
2166 }
2167}
2168
2169void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2170 bool IsDefinition) const {
2171 MCSymbolAttr Attr = MCSA_Invalid;
2172
2173 switch (Visibility) {
2174 default: break;
2175 case GlobalValue::HiddenVisibility:
2176 if (IsDefinition)
2177 Attr = MAI->getHiddenVisibilityAttr();
2178 else
2179 Attr = MAI->getHiddenDeclarationVisibilityAttr();
2180 break;
2181 case GlobalValue::ProtectedVisibility:
2182 Attr = MAI->getProtectedVisibilityAttr();
2183 break;
2184 }
2185
2186 if (Attr != MCSA_Invalid)
2187 OutStreamer.EmitSymbolAttribute(Sym, Attr);
2188}
2189
2190/// isBlockOnlyReachableByFallthough - Return true if the basic block has
2191/// exactly one predecessor and the control transfer mechanism between
2192/// the predecessor and this block is a fall-through.
2193bool AsmPrinter::
2194isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2195 // If this is a landing pad, it isn't a fall through. If it has no preds,
2196 // then nothing falls through to it.
2197 if (MBB->isLandingPad() || MBB->pred_empty())
2198 return false;
2199
2200 // If there isn't exactly one predecessor, it can't be a fall through.
2201 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2202 ++PI2;
2203 if (PI2 != MBB->pred_end())
2204 return false;
2205
2206 // The predecessor has to be immediately before this block.
2207 MachineBasicBlock *Pred = *PI;
2208
2209 if (!Pred->isLayoutSuccessor(MBB))
2210 return false;
2211
2212 // If the block is completely empty, then it definitely does fall through.
2213 if (Pred->empty())
2214 return true;
2215
2216 // Check the terminators in the previous blocks
2217 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2218 IE = Pred->end(); II != IE; ++II) {
2219 MachineInstr &MI = *II;
2220
2221 // If it is not a simple branch, we are in a table somewhere.
2222 if (!MI.isBranch() || MI.isIndirectBranch())
2223 return false;
2224
2224 // If we are the operands of one of the branches, this is not
2225 // a fall through.
2226 for (MachineInstr::mop_iterator OI = MI.operands_begin(),
2227 OE = MI.operands_end(); OI != OE; ++OI) {
2228 const MachineOperand& OP = *OI;
2229 if (OP.isJTI())
2225 // If we are the operands of one of the branches, this is not a fall
2226 // through. Note that targets with delay slots will usually bundle
2227 // terminators with the delay slot instruction.
2228 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2229 if (OP->isJTI())
2230 return false;
2230 return false;
2231 if (OP.isMBB() && OP.getMBB() == MBB)
2231 if (OP->isMBB() && OP->getMBB() == MBB)
2232 return false;
2233 }
2234 }
2235
2236 return true;
2237}
2238
2239
2240
2241GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2242 if (!S->usesMetadata())
2243 return 0;
2244
2245 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2246 gcp_map_type::iterator GCPI = GCMap.find(S);
2247 if (GCPI != GCMap.end())
2248 return GCPI->second;
2249
2250 const char *Name = S->getName().c_str();
2251
2252 for (GCMetadataPrinterRegistry::iterator
2253 I = GCMetadataPrinterRegistry::begin(),
2254 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2255 if (strcmp(Name, I->getName()) == 0) {
2256 GCMetadataPrinter *GMP = I->instantiate();
2257 GMP->S = S;
2258 GCMap.insert(std::make_pair(S, GMP));
2259 return GMP;
2260 }
2261
2262 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2263}
2232 return false;
2233 }
2234 }
2235
2236 return true;
2237}
2238
2239
2240
2241GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2242 if (!S->usesMetadata())
2243 return 0;
2244
2245 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2246 gcp_map_type::iterator GCPI = GCMap.find(S);
2247 if (GCPI != GCMap.end())
2248 return GCPI->second;
2249
2250 const char *Name = S->getName().c_str();
2251
2252 for (GCMetadataPrinterRegistry::iterator
2253 I = GCMetadataPrinterRegistry::begin(),
2254 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2255 if (strcmp(Name, I->getName()) == 0) {
2256 GCMetadataPrinter *GMP = I->instantiate();
2257 GMP->S = S;
2258 GCMap.insert(std::make_pair(S, GMP));
2259 return GMP;
2260 }
2261
2262 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2263}