TargetLoweringObjectFile.cpp revision 824583844a8f334dd261894a3fac7ad476531667
1//===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
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 classes used to handle lowerings specific to common
11// object file formats.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Target/TargetLoweringObjectFile.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/GlobalVariable.h"
19#include "llvm/MC/MCContext.h"
20#include "llvm/MC/MCSection.h"
21#include "llvm/Target/TargetMachine.h"
22#include "llvm/Target/TargetData.h"
23#include "llvm/Target/TargetOptions.h"
24#include "llvm/Support/Mangler.h"
25#include "llvm/ADT/StringExtras.h"
26using namespace llvm;
27
28//===----------------------------------------------------------------------===//
29//                              Generic Code
30//===----------------------------------------------------------------------===//
31
32TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
33  TextSection = 0;
34  DataSection = 0;
35  BSSSection = 0;
36  ReadOnlySection = 0;
37}
38
39TargetLoweringObjectFile::~TargetLoweringObjectFile() {
40}
41
42static bool isSuitableForBSS(const GlobalVariable *GV) {
43  Constant *C = GV->getInitializer();
44
45  // Must have zero initializer.
46  if (!C->isNullValue())
47    return false;
48
49  // Leave constant zeros in readonly constant sections, so they can be shared.
50  if (GV->isConstant())
51    return false;
52
53  // If the global has an explicit section specified, don't put it in BSS.
54  if (!GV->getSection().empty())
55    return false;
56
57  // If -nozero-initialized-in-bss is specified, don't ever use BSS.
58  if (NoZerosInBSS)
59    return false;
60
61  // Otherwise, put it in BSS!
62  return true;
63}
64
65static bool isConstantString(const Constant *C) {
66  // First check: is we have constant array of i8 terminated with zero
67  const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
68  // Check, if initializer is a null-terminated string
69  if (CVA && CVA->isCString())
70    return true;
71
72  // Another possibility: [1 x i8] zeroinitializer
73  if (isa<ConstantAggregateZero>(C))
74    if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))
75      return (Ty->getElementType() == Type::Int8Ty &&
76              Ty->getNumElements() == 1);
77
78  return false;
79}
80
81/// SectionKindForGlobal - This is a top-level target-independent classifier for
82/// a global variable.  Given an global variable and information from TM, it
83/// classifies the global in a variety of ways that make various target
84/// implementations simpler.  The target implementation is free to ignore this
85/// extra info of course.
86static SectionKind SectionKindForGlobal(const GlobalValue *GV,
87                                        const TargetMachine &TM) {
88  Reloc::Model ReloModel = TM.getRelocationModel();
89
90  // Early exit - functions should be always in text sections.
91  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
92  if (GVar == 0)
93    return SectionKind::get(SectionKind::Text);
94
95
96  // Handle thread-local data first.
97  if (GVar->isThreadLocal()) {
98    if (isSuitableForBSS(GVar))
99      return SectionKind::get(SectionKind::ThreadBSS);
100    return SectionKind::get(SectionKind::ThreadData);
101  }
102
103  // Variable can be easily put to BSS section.
104  if (isSuitableForBSS(GVar))
105    return SectionKind::get(SectionKind::BSS);
106
107  Constant *C = GVar->getInitializer();
108
109  // If the global is marked constant, we can put it into a mergable section,
110  // a mergable string section, or general .data if it contains relocations.
111  if (GVar->isConstant()) {
112    // If the initializer for the global contains something that requires a
113    // relocation, then we may have to drop this into a wriable data section
114    // even though it is marked const.
115    switch (C->getRelocationInfo()) {
116    default: llvm_unreachable("unknown relocation info kind");
117    case Constant::NoRelocation:
118      // If initializer is a null-terminated string, put it in a "cstring"
119      // section if the target has it.
120      if (isConstantString(C))
121        return SectionKind::get(SectionKind::MergeableCString);
122
123      // Otherwise, just drop it into a mergable constant section.  If we have
124      // a section for this size, use it, otherwise use the arbitrary sized
125      // mergable section.
126      switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
127      case 4:  return SectionKind::get(SectionKind::MergeableConst4);
128      case 8:  return SectionKind::get(SectionKind::MergeableConst8);
129      case 16: return SectionKind::get(SectionKind::MergeableConst16);
130      default: return SectionKind::get(SectionKind::MergeableConst);
131      }
132
133    case Constant::LocalRelocation:
134      // In static relocation model, the linker will resolve all addresses, so
135      // the relocation entries will actually be constants by the time the app
136      // starts up.  However, we can't put this into a mergable section, because
137      // the linker doesn't take relocations into consideration when it tries to
138      // merge entries in the section.
139      if (ReloModel == Reloc::Static)
140        return SectionKind::get(SectionKind::ReadOnly);
141
142      // Otherwise, the dynamic linker needs to fix it up, put it in the
143      // writable data.rel.local section.
144      return SectionKind::get(SectionKind::ReadOnlyWithRelLocal);
145
146    case Constant::GlobalRelocations:
147      // In static relocation model, the linker will resolve all addresses, so
148      // the relocation entries will actually be constants by the time the app
149      // starts up.  However, we can't put this into a mergable section, because
150      // the linker doesn't take relocations into consideration when it tries to
151      // merge entries in the section.
152      if (ReloModel == Reloc::Static)
153        return SectionKind::get(SectionKind::ReadOnly);
154
155      // Otherwise, the dynamic linker needs to fix it up, put it in the
156      // writable data.rel section.
157      return SectionKind::get(SectionKind::ReadOnlyWithRel);
158    }
159  }
160
161  // Okay, this isn't a constant.  If the initializer for the global is going
162  // to require a runtime relocation by the dynamic linker, put it into a more
163  // specific section to improve startup time of the app.  This coalesces these
164  // globals together onto fewer pages, improving the locality of the dynamic
165  // linker.
166  if (ReloModel == Reloc::Static)
167    return SectionKind::get(SectionKind::DataNoRel);
168
169  switch (C->getRelocationInfo()) {
170  default: llvm_unreachable("unknown relocation info kind");
171  case Constant::NoRelocation:
172    return SectionKind::get(SectionKind::DataNoRel);
173  case Constant::LocalRelocation:
174    return SectionKind::get(SectionKind::DataRelLocal);
175  case Constant::GlobalRelocations:
176    return SectionKind::get(SectionKind::DataRel);
177  }
178}
179
180/// SectionForGlobal - This method computes the appropriate section to emit
181/// the specified global variable or function definition.  This should not
182/// be passed external (or available externally) globals.
183const MCSection *TargetLoweringObjectFile::
184SectionForGlobal(const GlobalValue *GV, Mangler *Mang,
185                 const TargetMachine &TM) const {
186  assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
187         "Can only be used for global definitions");
188
189  SectionKind Kind = SectionKindForGlobal(GV, TM);
190
191  // Select section name.
192  if (GV->hasSection()) {
193    // If the target has special section hacks for specifically named globals,
194    // return them now.
195    if (const MCSection *TS = getSpecialCasedSectionGlobals(GV, Mang, Kind))
196      return TS;
197
198    // If the target has magic semantics for certain section names, make sure to
199    // pick up the flags.  This allows the user to write things with attribute
200    // section and still get the appropriate section flags printed.
201    Kind = getKindForNamedSection(GV->getSection().c_str(), Kind);
202
203    return getOrCreateSection(GV->getSection().c_str(), false, Kind);
204  }
205
206
207  // Use default section depending on the 'type' of global
208  return SelectSectionForGlobal(GV, Kind, Mang, TM);
209}
210
211// Lame default implementation. Calculate the section name for global.
212const MCSection *
213TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
214                                                 SectionKind Kind,
215                                                 Mangler *Mang,
216                                                 const TargetMachine &TM) const{
217  assert(!Kind.isThreadLocal() && "Doesn't support TLS");
218
219  if (Kind.isText())
220    return getTextSection();
221
222  if (Kind.isBSS() && BSSSection != 0)
223    return BSSSection;
224
225  if (Kind.isReadOnly() && ReadOnlySection != 0)
226    return ReadOnlySection;
227
228  return getDataSection();
229}
230
231/// getSectionForMergableConstant - Given a mergable constant with the
232/// specified size and relocation information, return a section that it
233/// should be placed in.
234const MCSection *
235TargetLoweringObjectFile::
236getSectionForMergeableConstant(SectionKind Kind) const {
237  if (Kind.isReadOnly() && ReadOnlySection != 0)
238    return ReadOnlySection;
239
240  return DataSection;
241}
242
243
244const MCSection *TargetLoweringObjectFile::
245getOrCreateSection(const char *Name, bool isDirective, SectionKind Kind) const {
246  if (MCSection *S = Ctx->GetSection(Name))
247    return S;
248  return MCSection::Create(Name, isDirective, Kind, *Ctx);
249}
250
251
252
253//===----------------------------------------------------------------------===//
254//                                  ELF
255//===----------------------------------------------------------------------===//
256
257void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
258                                             const TargetMachine &TM) {
259  TargetLoweringObjectFile::Initialize(Ctx, TM);
260  if (!HasCrazyBSS)
261    BSSSection = getOrCreateSection("\t.bss", true,
262                                    SectionKind::get(SectionKind::BSS));
263  else
264    // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
265    // FIXME: Does .section .bss work everywhere??
266    // FIXME2: this should just be handle by the section printer.  We should get
267    // away from syntactic view of the sections and MCSection should just be a
268    // semantic view.
269    BSSSection = getOrCreateSection("\t.bss", false,
270                                    SectionKind::get(SectionKind::BSS));
271
272
273  TextSection = getOrCreateSection("\t.text", true,
274                                   SectionKind::get(SectionKind::Text));
275  DataSection = getOrCreateSection("\t.data", true,
276                                   SectionKind::get(SectionKind::DataRel));
277  ReadOnlySection =
278    getOrCreateSection("\t.rodata", false,
279                       SectionKind::get(SectionKind::ReadOnly));
280  TLSDataSection =
281    getOrCreateSection("\t.tdata", false,
282                       SectionKind::get(SectionKind::ThreadData));
283  CStringSection = getOrCreateSection("\t.rodata.str", true,
284                               SectionKind::get(SectionKind::MergeableCString));
285
286  TLSBSSSection = getOrCreateSection("\t.tbss", false,
287                                     SectionKind::get(SectionKind::ThreadBSS));
288
289  DataRelSection = getOrCreateSection("\t.data.rel", false,
290                                      SectionKind::get(SectionKind::DataRel));
291  DataRelLocalSection = getOrCreateSection("\t.data.rel.local", false,
292                                   SectionKind::get(SectionKind::DataRelLocal));
293  DataRelROSection = getOrCreateSection("\t.data.rel.ro", false,
294                                SectionKind::get(SectionKind::ReadOnlyWithRel));
295  DataRelROLocalSection =
296    getOrCreateSection("\t.data.rel.ro.local", false,
297                       SectionKind::get(SectionKind::ReadOnlyWithRelLocal));
298
299  MergeableConst4Section = getOrCreateSection(".rodata.cst4", false,
300                                SectionKind::get(SectionKind::MergeableConst4));
301  MergeableConst8Section = getOrCreateSection(".rodata.cst8", false,
302                                SectionKind::get(SectionKind::MergeableConst8));
303  MergeableConst16Section = getOrCreateSection(".rodata.cst16", false,
304                               SectionKind::get(SectionKind::MergeableConst16));
305}
306
307
308SectionKind TargetLoweringObjectFileELF::
309getKindForNamedSection(const char *Name, SectionKind K) const {
310  if (Name[0] != '.') return K;
311
312  // Some lame default implementation based on some magic section names.
313  if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
314      strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
315      strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
316      strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
317    return SectionKind::get(SectionKind::BSS);
318
319  if (strcmp(Name, ".tdata") == 0 ||
320      strncmp(Name, ".tdata.", 7) == 0 ||
321      strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
322      strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
323    return SectionKind::get(SectionKind::ThreadData);
324
325  if (strcmp(Name, ".tbss") == 0 ||
326      strncmp(Name, ".tbss.", 6) == 0 ||
327      strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
328      strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
329    return SectionKind::get(SectionKind::ThreadBSS);
330
331  return K;
332}
333
334void TargetLoweringObjectFileELF::
335getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
336  Str.push_back(',');
337  Str.push_back('"');
338
339  if (!Kind.isMetadata())
340    Str.push_back('a');
341  if (Kind.isText())
342    Str.push_back('x');
343  if (Kind.isWriteable())
344    Str.push_back('w');
345  if (Kind.isMergeableCString() ||
346      Kind.isMergeableConst4() ||
347      Kind.isMergeableConst8() ||
348      Kind.isMergeableConst16())
349    Str.push_back('M');
350  if (Kind.isMergeableCString())
351    Str.push_back('S');
352  if (Kind.isThreadLocal())
353    Str.push_back('T');
354
355  Str.push_back('"');
356  Str.push_back(',');
357
358  // If comment string is '@', e.g. as on ARM - use '%' instead
359  if (AtIsCommentChar)
360    Str.push_back('%');
361  else
362    Str.push_back('@');
363
364  const char *KindStr;
365  if (Kind.isBSS() || Kind.isThreadBSS())
366    KindStr = "nobits";
367  else
368    KindStr = "progbits";
369
370  Str.append(KindStr, KindStr+strlen(KindStr));
371
372  if (Kind.isMergeableCString()) {
373    // TODO: Eventually handle multiple byte character strings.  For now, all
374    // mergable C strings are single byte.
375    Str.push_back(',');
376    Str.push_back('1');
377  } else if (Kind.isMergeableConst4()) {
378    Str.push_back(',');
379    Str.push_back('4');
380  } else if (Kind.isMergeableConst8()) {
381    Str.push_back(',');
382    Str.push_back('8');
383  } else if (Kind.isMergeableConst16()) {
384    Str.push_back(',');
385    Str.push_back('1');
386    Str.push_back('6');
387  }
388}
389
390
391static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
392  if (Kind.isText())                 return ".gnu.linkonce.t.";
393  if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
394
395  if (Kind.isThreadData())           return ".gnu.linkonce.td.";
396  if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
397
398  if (Kind.isBSS())                  return ".gnu.linkonce.b.";
399  if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
400  if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
401  if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
402  if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
403
404  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
405  return ".gnu.linkonce.d.rel.ro.";
406}
407
408const MCSection *TargetLoweringObjectFileELF::
409SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
410                       Mangler *Mang, const TargetMachine &TM) const {
411
412  // If this global is linkonce/weak and the target handles this by emitting it
413  // into a 'uniqued' section name, create and return the section now.
414  if (GV->isWeakForLinker()) {
415    const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
416    std::string Name = Mang->makeNameProper(GV->getNameStr());
417    return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
418  }
419
420  if (Kind.isText()) return TextSection;
421
422  if (Kind.isMergeableCString()) {
423   assert(CStringSection && "Should have string section prefix");
424
425    // We also need alignment here.
426    // FIXME: this is getting the alignment of the character, not the
427    // alignment of the global!
428    unsigned Align =
429      TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
430
431    std::string Name = CStringSection->getName() + "1." + utostr(Align);
432    return getOrCreateSection(Name.c_str(), false,
433                              SectionKind::get(SectionKind::MergeableCString));
434  }
435
436  if (Kind.isMergeableConst()) {
437    if (Kind.isMergeableConst4())
438      return MergeableConst4Section;
439    if (Kind.isMergeableConst8())
440      return MergeableConst8Section;
441    if (Kind.isMergeableConst16())
442      return MergeableConst16Section;
443    return ReadOnlySection;  // .const
444  }
445
446  if (Kind.isReadOnly())             return ReadOnlySection;
447
448  if (Kind.isThreadData())           return TLSDataSection;
449  if (Kind.isThreadBSS())            return TLSBSSSection;
450
451  if (Kind.isBSS())                  return BSSSection;
452
453  if (Kind.isDataNoRel())            return DataSection;
454  if (Kind.isDataRelLocal())         return DataRelLocalSection;
455  if (Kind.isDataRel())              return DataRelSection;
456  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
457
458  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
459  return DataRelROSection;
460}
461
462/// getSectionForMergeableConstant - Given a mergeable constant with the
463/// specified size and relocation information, return a section that it
464/// should be placed in.
465const MCSection *TargetLoweringObjectFileELF::
466getSectionForMergeableConstant(SectionKind Kind) const {
467  if (Kind.isMergeableConst4())
468    return MergeableConst4Section;
469  if (Kind.isMergeableConst8())
470    return MergeableConst8Section;
471  if (Kind.isMergeableConst16())
472    return MergeableConst16Section;
473  if (Kind.isReadOnly())
474    return ReadOnlySection;
475
476  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
477  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
478  return DataRelROSection;
479}
480
481//===----------------------------------------------------------------------===//
482//                                 MachO
483//===----------------------------------------------------------------------===//
484
485void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
486                                               const TargetMachine &TM) {
487  TargetLoweringObjectFile::Initialize(Ctx, TM);
488  TextSection = getOrCreateSection("\t.text", true,
489                                   SectionKind::get(SectionKind::Text));
490  DataSection = getOrCreateSection("\t.data", true,
491                                   SectionKind::get(SectionKind::DataRel));
492
493  CStringSection = getOrCreateSection("\t.cstring", true,
494                               SectionKind::get(SectionKind::MergeableCString));
495  FourByteConstantSection = getOrCreateSection("\t.literal4\n", true,
496                                SectionKind::get(SectionKind::MergeableConst4));
497  EightByteConstantSection = getOrCreateSection("\t.literal8\n", true,
498                                SectionKind::get(SectionKind::MergeableConst8));
499
500  // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
501  // to using it in -static mode.
502  if (TM.getRelocationModel() != Reloc::Static &&
503      TM.getTargetData()->getPointerSize() == 32)
504    SixteenByteConstantSection =
505      getOrCreateSection("\t.literal16\n", true,
506                         SectionKind::get(SectionKind::MergeableConst16));
507  else
508    SixteenByteConstantSection = 0;
509
510  ReadOnlySection = getOrCreateSection("\t.const", true,
511                                       SectionKind::get(SectionKind::ReadOnly));
512
513  TextCoalSection =
514  getOrCreateSection("\t__TEXT,__textcoal_nt,coalesced,pure_instructions",
515                     false, SectionKind::get(SectionKind::Text));
516  ConstTextCoalSection = getOrCreateSection("\t__TEXT,__const_coal,coalesced",
517                                            false,
518                                           SectionKind::get(SectionKind::Text));
519  ConstDataCoalSection = getOrCreateSection("\t__DATA,__const_coal,coalesced",
520                                            false,
521                                          SectionKind::get(SectionKind::Text));
522  ConstDataSection = getOrCreateSection("\t.const_data", true,
523                                SectionKind::get(SectionKind::ReadOnlyWithRel));
524  DataCoalSection = getOrCreateSection("\t__DATA,__datacoal_nt,coalesced",
525                                       false,
526                                       SectionKind::get(SectionKind::DataRel));
527}
528
529const MCSection *TargetLoweringObjectFileMachO::
530SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
531                       Mangler *Mang, const TargetMachine &TM) const {
532  assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
533
534  if (Kind.isText())
535    return GV->isWeakForLinker() ? TextCoalSection : TextSection;
536
537  // If this is weak/linkonce, put this in a coalescable section, either in text
538  // or data depending on if it is writable.
539  if (GV->isWeakForLinker()) {
540    if (Kind.isReadOnly())
541      return ConstTextCoalSection;
542    return DataCoalSection;
543  }
544
545  // FIXME: Alignment check should be handled by section classifier.
546  if (Kind.isMergeableCString()) {
547    Constant *C = cast<GlobalVariable>(GV)->getInitializer();
548    const Type *Ty = cast<ArrayType>(C->getType())->getElementType();
549    const TargetData &TD = *TM.getTargetData();
550    unsigned Size = TD.getTypeAllocSize(Ty);
551    if (Size) {
552      unsigned Align = TD.getPreferredAlignment(cast<GlobalVariable>(GV));
553      if (Align <= 32)
554        return CStringSection;
555    }
556
557    return ReadOnlySection;
558  }
559
560  if (Kind.isMergeableConst()) {
561    if (Kind.isMergeableConst4())
562      return FourByteConstantSection;
563    if (Kind.isMergeableConst8())
564      return EightByteConstantSection;
565    if (Kind.isMergeableConst16() && SixteenByteConstantSection)
566      return SixteenByteConstantSection;
567    return ReadOnlySection;  // .const
568  }
569
570  // FIXME: ROData -> const in -static mode that is relocatable but they happen
571  // by the static linker.  Why not mergeable?
572  if (Kind.isReadOnly())
573    return ReadOnlySection;
574
575  // If this is marked const, put it into a const section.  But if the dynamic
576  // linker needs to write to it, put it in the data segment.
577  if (Kind.isReadOnlyWithRel())
578    return ConstDataSection;
579
580  // Otherwise, just drop the variable in the normal data section.
581  return DataSection;
582}
583
584const MCSection *
585TargetLoweringObjectFileMachO::
586getSectionForMergeableConstant(SectionKind Kind) const {
587  // If this constant requires a relocation, we have to put it in the data
588  // segment, not in the text segment.
589  if (Kind.isDataRel())
590    return ConstDataSection;
591
592  if (Kind.isMergeableConst4())
593    return FourByteConstantSection;
594  if (Kind.isMergeableConst8())
595    return EightByteConstantSection;
596  if (Kind.isMergeableConst16() && SixteenByteConstantSection)
597    return SixteenByteConstantSection;
598  return ReadOnlySection;  // .const
599}
600
601/// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
602/// not to emit the UsedDirective for some symbols in llvm.used.
603// FIXME: REMOVE this (rdar://7071300)
604bool TargetLoweringObjectFileMachO::
605shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
606  /// On Darwin, internally linked data beginning with "L" or "l" does not have
607  /// the directive emitted (this occurs in ObjC metadata).
608  if (!GV) return false;
609
610  // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
611  if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
612    // FIXME: ObjC metadata is currently emitted as internal symbols that have
613    // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
614    // this horrible hack can go away.
615    const std::string &Name = Mang->getMangledName(GV);
616    if (Name[0] == 'L' || Name[0] == 'l')
617      return false;
618  }
619
620  return true;
621}
622
623
624//===----------------------------------------------------------------------===//
625//                                  COFF
626//===----------------------------------------------------------------------===//
627
628void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
629                                              const TargetMachine &TM) {
630  TargetLoweringObjectFile::Initialize(Ctx, TM);
631  TextSection = getOrCreateSection("\t.text", true,
632                                   SectionKind::get(SectionKind::Text));
633  DataSection = getOrCreateSection("\t.data", true,
634                                   SectionKind::get(SectionKind::DataRel));
635}
636
637void TargetLoweringObjectFileCOFF::
638getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
639  // FIXME: Inefficient.
640  std::string Res = ",\"";
641  if (Kind.isText())
642    Res += 'x';
643  if (Kind.isWriteable())
644    Res += 'w';
645  Res += "\"";
646
647  Str.append(Res.begin(), Res.end());
648}
649
650static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
651  if (Kind.isText())
652    return ".text$linkonce";
653  if (Kind.isWriteable())
654    return ".data$linkonce";
655  return ".rdata$linkonce";
656}
657
658
659const MCSection *TargetLoweringObjectFileCOFF::
660SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
661                       Mangler *Mang, const TargetMachine &TM) const {
662  assert(!Kind.isThreadLocal() && "Doesn't support TLS");
663
664  // If this global is linkonce/weak and the target handles this by emitting it
665  // into a 'uniqued' section name, create and return the section now.
666  if (GV->isWeakForLinker()) {
667    const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
668    std::string Name = Mang->makeNameProper(GV->getNameStr());
669    return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
670  }
671
672  if (Kind.isText())
673    return getTextSection();
674
675  return getDataSection();
676}
677
678