LLVM  mainline
TargetLoweringObjectFile.cpp
Go to the documentation of this file.
00001 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements classes used to handle lowerings specific to common
00011 // object file formats.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Target/TargetLoweringObjectFile.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/DataLayout.h"
00018 #include "llvm/IR/DerivedTypes.h"
00019 #include "llvm/IR/Function.h"
00020 #include "llvm/IR/GlobalVariable.h"
00021 #include "llvm/IR/Mangler.h"
00022 #include "llvm/MC/MCAsmInfo.h"
00023 #include "llvm/MC/MCContext.h"
00024 #include "llvm/MC/MCExpr.h"
00025 #include "llvm/MC/MCStreamer.h"
00026 #include "llvm/MC/MCSymbol.h"
00027 #include "llvm/Support/Dwarf.h"
00028 #include "llvm/Support/ErrorHandling.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/Target/TargetLowering.h"
00031 #include "llvm/Target/TargetMachine.h"
00032 #include "llvm/Target/TargetOptions.h"
00033 #include "llvm/Target/TargetSubtargetInfo.h"
00034 using namespace llvm;
00035 
00036 //===----------------------------------------------------------------------===//
00037 //                              Generic Code
00038 //===----------------------------------------------------------------------===//
00039 
00040 /// Initialize - this method must be called before any actual lowering is
00041 /// done.  This specifies the current context for codegen, and gives the
00042 /// lowering implementations a chance to set up their default sections.
00043 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
00044                                           const TargetMachine &TM) {
00045   Ctx = &ctx;
00046   InitMCObjectFileInfo(TM.getTargetTriple(), TM.getRelocationModel(),
00047                        TM.getCodeModel(), *Ctx);
00048 }
00049 
00050 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
00051 }
00052 
00053 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
00054   const Constant *C = GV->getInitializer();
00055 
00056   // Must have zero initializer.
00057   if (!C->isNullValue())
00058     return false;
00059 
00060   // Leave constant zeros in readonly constant sections, so they can be shared.
00061   if (GV->isConstant())
00062     return false;
00063 
00064   // If the global has an explicit section specified, don't put it in BSS.
00065   if (GV->hasSection())
00066     return false;
00067 
00068   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
00069   if (NoZerosInBSS)
00070     return false;
00071 
00072   // Otherwise, put it in BSS!
00073   return true;
00074 }
00075 
00076 /// IsNullTerminatedString - Return true if the specified constant (which is
00077 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
00078 /// nul value and contains no other nuls in it.  Note that this is more general
00079 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
00080 static bool IsNullTerminatedString(const Constant *C) {
00081   // First check: is we have constant array terminated with zero
00082   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
00083     unsigned NumElts = CDS->getNumElements();
00084     assert(NumElts != 0 && "Can't have an empty CDS");
00085     
00086     if (CDS->getElementAsInteger(NumElts-1) != 0)
00087       return false; // Not null terminated.
00088     
00089     // Verify that the null doesn't occur anywhere else in the string.
00090     for (unsigned i = 0; i != NumElts-1; ++i)
00091       if (CDS->getElementAsInteger(i) == 0)
00092         return false;
00093     return true;
00094   }
00095 
00096   // Another possibility: [1 x i8] zeroinitializer
00097   if (isa<ConstantAggregateZero>(C))
00098     return cast<ArrayType>(C->getType())->getNumElements() == 1;
00099 
00100   return false;
00101 }
00102 
00103 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
00104     const GlobalValue *GV, StringRef Suffix, Mangler &Mang,
00105     const TargetMachine &TM) const {
00106   assert(!Suffix.empty());
00107 
00108   SmallString<60> NameStr;
00109   NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
00110   TM.getNameWithPrefix(NameStr, GV, Mang);
00111   NameStr.append(Suffix.begin(), Suffix.end());
00112   return Ctx->getOrCreateSymbol(NameStr);
00113 }
00114 
00115 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
00116     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00117     MachineModuleInfo *MMI) const {
00118   return TM.getSymbol(GV, Mang);
00119 }
00120 
00121 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
00122                                                     const DataLayout &,
00123                                                     const MCSymbol *Sym) const {
00124 }
00125 
00126 
00127 /// getKindForGlobal - This is a top-level target-independent classifier for
00128 /// a global variable.  Given an global variable and information from TM, it
00129 /// classifies the global in a variety of ways that make various target
00130 /// implementations simpler.  The target implementation is free to ignore this
00131 /// extra info of course.
00132 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
00133                                                        const TargetMachine &TM){
00134   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
00135          "Can only be used for global definitions");
00136 
00137   Reloc::Model ReloModel = TM.getRelocationModel();
00138 
00139   // Early exit - functions should be always in text sections.
00140   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00141   if (!GVar)
00142     return SectionKind::getText();
00143 
00144   // Handle thread-local data first.
00145   if (GVar->isThreadLocal()) {
00146     if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
00147       return SectionKind::getThreadBSS();
00148     return SectionKind::getThreadData();
00149   }
00150 
00151   // Variables with common linkage always get classified as common.
00152   if (GVar->hasCommonLinkage())
00153     return SectionKind::getCommon();
00154 
00155   // Variable can be easily put to BSS section.
00156   if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
00157     if (GVar->hasLocalLinkage())
00158       return SectionKind::getBSSLocal();
00159     else if (GVar->hasExternalLinkage())
00160       return SectionKind::getBSSExtern();
00161     return SectionKind::getBSS();
00162   }
00163 
00164   const Constant *C = GVar->getInitializer();
00165 
00166   // If the global is marked constant, we can put it into a mergable section,
00167   // a mergable string section, or general .data if it contains relocations.
00168   if (GVar->isConstant()) {
00169     // If the initializer for the global contains something that requires a
00170     // relocation, then we may have to drop this into a writable data section
00171     // even though it is marked const.
00172     if (!C->needsRelocation()) {
00173       // If the global is required to have a unique address, it can't be put
00174       // into a mergable section: just drop it into the general read-only
00175       // section instead.
00176       if (!GVar->hasUnnamedAddr())
00177         return SectionKind::getReadOnly();
00178 
00179       // If initializer is a null-terminated string, put it in a "cstring"
00180       // section of the right width.
00181       if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
00182         if (IntegerType *ITy =
00183               dyn_cast<IntegerType>(ATy->getElementType())) {
00184           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
00185                ITy->getBitWidth() == 32) &&
00186               IsNullTerminatedString(C)) {
00187             if (ITy->getBitWidth() == 8)
00188               return SectionKind::getMergeable1ByteCString();
00189             if (ITy->getBitWidth() == 16)
00190               return SectionKind::getMergeable2ByteCString();
00191 
00192             assert(ITy->getBitWidth() == 32 && "Unknown width");
00193             return SectionKind::getMergeable4ByteCString();
00194           }
00195         }
00196       }
00197 
00198       // Otherwise, just drop it into a mergable constant section.  If we have
00199       // a section for this size, use it, otherwise use the arbitrary sized
00200       // mergable section.
00201       switch (GV->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
00202       case 4:  return SectionKind::getMergeableConst4();
00203       case 8:  return SectionKind::getMergeableConst8();
00204       case 16: return SectionKind::getMergeableConst16();
00205       default:
00206         return SectionKind::getReadOnly();
00207       }
00208 
00209     } else {
00210       // In static relocation model, the linker will resolve all addresses, so
00211       // the relocation entries will actually be constants by the time the app
00212       // starts up.  However, we can't put this into a mergable section, because
00213       // the linker doesn't take relocations into consideration when it tries to
00214       // merge entries in the section.
00215       if (ReloModel == Reloc::Static)
00216         return SectionKind::getReadOnly();
00217 
00218       // Otherwise, the dynamic linker needs to fix it up, put it in the
00219       // writable data.rel section.
00220       return SectionKind::getReadOnlyWithRel();
00221     }
00222   }
00223 
00224   // Okay, this isn't a constant.  If the initializer for the global is going
00225   // to require a runtime relocation by the dynamic linker, put it into a more
00226   // specific section to improve startup time of the app.  This coalesces these
00227   // globals together onto fewer pages, improving the locality of the dynamic
00228   // linker.
00229   if (ReloModel == Reloc::Static)
00230     return SectionKind::getData();
00231 
00232   if (C->needsRelocation())
00233     return SectionKind::getData();
00234   return SectionKind::getData();
00235 }
00236 
00237 /// This method computes the appropriate section to emit the specified global
00238 /// variable or function definition.  This should not be passed external (or
00239 /// available externally) globals.
00240 MCSection *
00241 TargetLoweringObjectFile::SectionForGlobal(const GlobalValue *GV,
00242                                            SectionKind Kind, Mangler &Mang,
00243                                            const TargetMachine &TM) const {
00244   // Select section name.
00245   if (GV->hasSection())
00246     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
00247 
00248 
00249   // Use default section depending on the 'type' of global
00250   return SelectSectionForGlobal(GV, Kind, Mang, TM);
00251 }
00252 
00253 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
00254     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
00255   return getSectionForConstant(F.getParent()->getDataLayout(),
00256                                SectionKind::getReadOnly(), /*C=*/nullptr);
00257 }
00258 
00259 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
00260     bool UsesLabelDifference, const Function &F) const {
00261   // In PIC mode, we need to emit the jump table to the same section as the
00262   // function body itself, otherwise the label differences won't make sense.
00263   // FIXME: Need a better predicate for this: what about custom entries?
00264   if (UsesLabelDifference)
00265     return true;
00266 
00267   // We should also do if the section name is NULL or function is declared
00268   // in discardable section
00269   // FIXME: this isn't the right predicate, should be based on the MCSection
00270   // for the function.
00271   if (F.isWeakForLinker())
00272     return true;
00273 
00274   return false;
00275 }
00276 
00277 /// Given a mergable constant with the specified size and relocation
00278 /// information, return a section that it should be placed in.
00279 MCSection *TargetLoweringObjectFile::getSectionForConstant(
00280     const DataLayout &DL, SectionKind Kind, const Constant *C) const {
00281   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
00282     return ReadOnlySection;
00283 
00284   return DataSection;
00285 }
00286 
00287 /// getTTypeGlobalReference - Return an MCExpr to use for a
00288 /// reference to the specified global variable from exception
00289 /// handling information.
00290 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
00291     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00292     const TargetMachine &TM, MachineModuleInfo *MMI,
00293     MCStreamer &Streamer) const {
00294   const MCSymbolRefExpr *Ref =
00295       MCSymbolRefExpr::create(TM.getSymbol(GV, Mang), getContext());
00296 
00297   return getTTypeReference(Ref, Encoding, Streamer);
00298 }
00299 
00300 const MCExpr *TargetLoweringObjectFile::
00301 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
00302                   MCStreamer &Streamer) const {
00303   switch (Encoding & 0x70) {
00304   default:
00305     report_fatal_error("We do not support this DWARF encoding yet!");
00306   case dwarf::DW_EH_PE_absptr:
00307     // Do nothing special
00308     return Sym;
00309   case dwarf::DW_EH_PE_pcrel: {
00310     // Emit a label to the streamer for the current position.  This gives us
00311     // .-foo addressing.
00312     MCSymbol *PCSym = getContext().createTempSymbol();
00313     Streamer.EmitLabel(PCSym);
00314     const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
00315     return MCBinaryExpr::createSub(Sym, PC, getContext());
00316   }
00317   }
00318 }
00319 
00320 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
00321   // FIXME: It's not clear what, if any, default this should have - perhaps a
00322   // null return could mean 'no location' & we should just do that here.
00323   return MCSymbolRefExpr::create(Sym, *Ctx);
00324 }
00325 
00326 void TargetLoweringObjectFile::getNameWithPrefix(
00327     SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
00328     const TargetMachine &TM) const {
00329   Mang.getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
00330 }