Home | History | Annotate | Download | only in Target
      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/IR/Constants.h"
     17 #include "llvm/IR/DataLayout.h"
     18 #include "llvm/IR/DerivedTypes.h"
     19 #include "llvm/IR/Function.h"
     20 #include "llvm/IR/GlobalVariable.h"
     21 #include "llvm/IR/Mangler.h"
     22 #include "llvm/MC/MCAsmInfo.h"
     23 #include "llvm/MC/MCContext.h"
     24 #include "llvm/MC/MCExpr.h"
     25 #include "llvm/MC/MCStreamer.h"
     26 #include "llvm/MC/MCSymbol.h"
     27 #include "llvm/Support/Dwarf.h"
     28 #include "llvm/Support/ErrorHandling.h"
     29 #include "llvm/Support/raw_ostream.h"
     30 #include "llvm/Target/TargetLowering.h"
     31 #include "llvm/Target/TargetMachine.h"
     32 #include "llvm/Target/TargetOptions.h"
     33 #include "llvm/Target/TargetSubtargetInfo.h"
     34 using namespace llvm;
     35 
     36 //===----------------------------------------------------------------------===//
     37 //                              Generic Code
     38 //===----------------------------------------------------------------------===//
     39 
     40 /// Initialize - this method must be called before any actual lowering is
     41 /// done.  This specifies the current context for codegen, and gives the
     42 /// lowering implementations a chance to set up their default sections.
     43 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
     44                                           const TargetMachine &TM) {
     45   Ctx = &ctx;
     46   InitMCObjectFileInfo(TM.getTargetTriple(), TM.getRelocationModel(),
     47                        TM.getCodeModel(), *Ctx);
     48 }
     49 
     50 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
     51 }
     52 
     53 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
     54   const Constant *C = GV->getInitializer();
     55 
     56   // Must have zero initializer.
     57   if (!C->isNullValue())
     58     return false;
     59 
     60   // Leave constant zeros in readonly constant sections, so they can be shared.
     61   if (GV->isConstant())
     62     return false;
     63 
     64   // If the global has an explicit section specified, don't put it in BSS.
     65   if (GV->hasSection())
     66     return false;
     67 
     68   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
     69   if (NoZerosInBSS)
     70     return false;
     71 
     72   // Otherwise, put it in BSS!
     73   return true;
     74 }
     75 
     76 /// IsNullTerminatedString - Return true if the specified constant (which is
     77 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
     78 /// nul value and contains no other nuls in it.  Note that this is more general
     79 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
     80 static bool IsNullTerminatedString(const Constant *C) {
     81   // First check: is we have constant array terminated with zero
     82   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
     83     unsigned NumElts = CDS->getNumElements();
     84     assert(NumElts != 0 && "Can't have an empty CDS");
     85 
     86     if (CDS->getElementAsInteger(NumElts-1) != 0)
     87       return false; // Not null terminated.
     88 
     89     // Verify that the null doesn't occur anywhere else in the string.
     90     for (unsigned i = 0; i != NumElts-1; ++i)
     91       if (CDS->getElementAsInteger(i) == 0)
     92         return false;
     93     return true;
     94   }
     95 
     96   // Another possibility: [1 x i8] zeroinitializer
     97   if (isa<ConstantAggregateZero>(C))
     98     return cast<ArrayType>(C->getType())->getNumElements() == 1;
     99 
    100   return false;
    101 }
    102 
    103 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
    104     const GlobalValue *GV, StringRef Suffix, Mangler &Mang,
    105     const TargetMachine &TM) const {
    106   assert(!Suffix.empty());
    107 
    108   SmallString<60> NameStr;
    109   NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
    110   TM.getNameWithPrefix(NameStr, GV, Mang);
    111   NameStr.append(Suffix.begin(), Suffix.end());
    112   return Ctx->getOrCreateSymbol(NameStr);
    113 }
    114 
    115 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
    116     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
    117     MachineModuleInfo *MMI) const {
    118   return TM.getSymbol(GV, Mang);
    119 }
    120 
    121 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
    122                                                     const DataLayout &,
    123                                                     const MCSymbol *Sym) const {
    124 }
    125 
    126 
    127 /// getKindForGlobal - This is a top-level target-independent classifier for
    128 /// a global variable.  Given an global variable and information from TM, it
    129 /// classifies the global in a variety of ways that make various target
    130 /// implementations simpler.  The target implementation is free to ignore this
    131 /// extra info of course.
    132 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
    133                                                        const TargetMachine &TM){
    134   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
    135          "Can only be used for global definitions");
    136 
    137   Reloc::Model ReloModel = TM.getRelocationModel();
    138 
    139   // Early exit - functions should be always in text sections.
    140   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
    141   if (!GVar)
    142     return SectionKind::getText();
    143 
    144   // Handle thread-local data first.
    145   if (GVar->isThreadLocal()) {
    146     if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
    147       return SectionKind::getThreadBSS();
    148     return SectionKind::getThreadData();
    149   }
    150 
    151   // Variables with common linkage always get classified as common.
    152   if (GVar->hasCommonLinkage())
    153     return SectionKind::getCommon();
    154 
    155   // Variable can be easily put to BSS section.
    156   if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
    157     if (GVar->hasLocalLinkage())
    158       return SectionKind::getBSSLocal();
    159     else if (GVar->hasExternalLinkage())
    160       return SectionKind::getBSSExtern();
    161     return SectionKind::getBSS();
    162   }
    163 
    164   const Constant *C = GVar->getInitializer();
    165 
    166   // If the global is marked constant, we can put it into a mergable section,
    167   // a mergable string section, or general .data if it contains relocations.
    168   if (GVar->isConstant()) {
    169     // If the initializer for the global contains something that requires a
    170     // relocation, then we may have to drop this into a writable data section
    171     // even though it is marked const.
    172     if (!C->needsRelocation()) {
    173       // If the global is required to have a unique address, it can't be put
    174       // into a mergable section: just drop it into the general read-only
    175       // section instead.
    176       if (!GVar->hasUnnamedAddr())
    177         return SectionKind::getReadOnly();
    178 
    179       // If initializer is a null-terminated string, put it in a "cstring"
    180       // section of the right width.
    181       if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
    182         if (IntegerType *ITy =
    183               dyn_cast<IntegerType>(ATy->getElementType())) {
    184           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
    185                ITy->getBitWidth() == 32) &&
    186               IsNullTerminatedString(C)) {
    187             if (ITy->getBitWidth() == 8)
    188               return SectionKind::getMergeable1ByteCString();
    189             if (ITy->getBitWidth() == 16)
    190               return SectionKind::getMergeable2ByteCString();
    191 
    192             assert(ITy->getBitWidth() == 32 && "Unknown width");
    193             return SectionKind::getMergeable4ByteCString();
    194           }
    195         }
    196       }
    197 
    198       // Otherwise, just drop it into a mergable constant section.  If we have
    199       // a section for this size, use it, otherwise use the arbitrary sized
    200       // mergable section.
    201       switch (GV->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
    202       case 4:  return SectionKind::getMergeableConst4();
    203       case 8:  return SectionKind::getMergeableConst8();
    204       case 16: return SectionKind::getMergeableConst16();
    205       default:
    206         return SectionKind::getReadOnly();
    207       }
    208 
    209     } else {
    210       // In static relocation model, the linker will resolve all addresses, so
    211       // the relocation entries will actually be constants by the time the app
    212       // starts up.  However, we can't put this into a mergable section, because
    213       // the linker doesn't take relocations into consideration when it tries to
    214       // merge entries in the section.
    215       if (ReloModel == Reloc::Static)
    216         return SectionKind::getReadOnly();
    217 
    218       // Otherwise, the dynamic linker needs to fix it up, put it in the
    219       // writable data.rel section.
    220       return SectionKind::getReadOnlyWithRel();
    221     }
    222   }
    223 
    224   // Okay, this isn't a constant.  If the initializer for the global is going
    225   // to require a runtime relocation by the dynamic linker, put it into a more
    226   // specific section to improve startup time of the app.  This coalesces these
    227   // globals together onto fewer pages, improving the locality of the dynamic
    228   // linker.
    229   if (ReloModel == Reloc::Static)
    230     return SectionKind::getData();
    231 
    232   if (C->needsRelocation())
    233     return SectionKind::getData();
    234   return SectionKind::getData();
    235 }
    236 
    237 /// This method computes the appropriate section to emit the specified global
    238 /// variable or function definition.  This should not be passed external (or
    239 /// available externally) globals.
    240 MCSection *
    241 TargetLoweringObjectFile::SectionForGlobal(const GlobalValue *GV,
    242                                            SectionKind Kind, Mangler &Mang,
    243                                            const TargetMachine &TM) const {
    244   // Select section name.
    245   if (GV->hasSection())
    246     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
    247 
    248 
    249   // Use default section depending on the 'type' of global
    250   return SelectSectionForGlobal(GV, Kind, Mang, TM);
    251 }
    252 
    253 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
    254     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
    255   return getSectionForConstant(F.getParent()->getDataLayout(),
    256                                SectionKind::getReadOnly(), /*C=*/nullptr);
    257 }
    258 
    259 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
    260     bool UsesLabelDifference, const Function &F) const {
    261   // In PIC mode, we need to emit the jump table to the same section as the
    262   // function body itself, otherwise the label differences won't make sense.
    263   // FIXME: Need a better predicate for this: what about custom entries?
    264   if (UsesLabelDifference)
    265     return true;
    266 
    267   // We should also do if the section name is NULL or function is declared
    268   // in discardable section
    269   // FIXME: this isn't the right predicate, should be based on the MCSection
    270   // for the function.
    271   if (F.isWeakForLinker())
    272     return true;
    273 
    274   return false;
    275 }
    276 
    277 /// Given a mergable constant with the specified size and relocation
    278 /// information, return a section that it should be placed in.
    279 MCSection *TargetLoweringObjectFile::getSectionForConstant(
    280     const DataLayout &DL, SectionKind Kind, const Constant *C) const {
    281   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
    282     return ReadOnlySection;
    283 
    284   return DataSection;
    285 }
    286 
    287 /// getTTypeGlobalReference - Return an MCExpr to use for a
    288 /// reference to the specified global variable from exception
    289 /// handling information.
    290 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
    291     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
    292     const TargetMachine &TM, MachineModuleInfo *MMI,
    293     MCStreamer &Streamer) const {
    294   const MCSymbolRefExpr *Ref =
    295       MCSymbolRefExpr::create(TM.getSymbol(GV, Mang), getContext());
    296 
    297   return getTTypeReference(Ref, Encoding, Streamer);
    298 }
    299 
    300 const MCExpr *TargetLoweringObjectFile::
    301 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
    302                   MCStreamer &Streamer) const {
    303   switch (Encoding & 0x70) {
    304   default:
    305     report_fatal_error("We do not support this DWARF encoding yet!");
    306   case dwarf::DW_EH_PE_absptr:
    307     // Do nothing special
    308     return Sym;
    309   case dwarf::DW_EH_PE_pcrel: {
    310     // Emit a label to the streamer for the current position.  This gives us
    311     // .-foo addressing.
    312     MCSymbol *PCSym = getContext().createTempSymbol();
    313     Streamer.EmitLabel(PCSym);
    314     const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
    315     return MCBinaryExpr::createSub(Sym, PC, getContext());
    316   }
    317   }
    318 }
    319 
    320 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
    321   // FIXME: It's not clear what, if any, default this should have - perhaps a
    322   // null return could mean 'no location' & we should just do that here.
    323   return MCSymbolRefExpr::create(Sym, *Ctx);
    324 }
    325 
    326 void TargetLoweringObjectFile::getNameWithPrefix(
    327     SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
    328     const TargetMachine &TM) const {
    329   Mang.getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
    330 }
    331