LLVM API Documentation

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 using namespace llvm;
00034 
00035 //===----------------------------------------------------------------------===//
00036 //                              Generic Code
00037 //===----------------------------------------------------------------------===//
00038 
00039 /// Initialize - this method must be called before any actual lowering is
00040 /// done.  This specifies the current context for codegen, and gives the
00041 /// lowering implementations a chance to set up their default sections.
00042 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
00043                                           const TargetMachine &TM) {
00044   Ctx = &ctx;
00045   DL = TM.getDataLayout();
00046   InitMCObjectFileInfo(TM.getTargetTriple(),
00047                        TM.getRelocationModel(), 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 += DL->getPrivateGlobalPrefix();
00110   TM.getNameWithPrefix(NameStr, GV, Mang);
00111   NameStr.append(Suffix.begin(), Suffix.end());
00112   return Ctx->GetOrCreateSymbol(NameStr.str());
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 TargetMachine &TM,
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     switch (C->getRelocationInfo()) {
00173     case Constant::NoRelocation:
00174       // If the global is required to have a unique address, it can't be put
00175       // into a mergable section: just drop it into the general read-only
00176       // section instead.
00177       if (!GVar->hasUnnamedAddr())
00178         return SectionKind::getReadOnly();
00179         
00180       // If initializer is a null-terminated string, put it in a "cstring"
00181       // section of the right width.
00182       if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
00183         if (IntegerType *ITy =
00184               dyn_cast<IntegerType>(ATy->getElementType())) {
00185           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
00186                ITy->getBitWidth() == 32) &&
00187               IsNullTerminatedString(C)) {
00188             if (ITy->getBitWidth() == 8)
00189               return SectionKind::getMergeable1ByteCString();
00190             if (ITy->getBitWidth() == 16)
00191               return SectionKind::getMergeable2ByteCString();
00192 
00193             assert(ITy->getBitWidth() == 32 && "Unknown width");
00194             return SectionKind::getMergeable4ByteCString();
00195           }
00196         }
00197       }
00198 
00199       // Otherwise, just drop it into a mergable constant section.  If we have
00200       // a section for this size, use it, otherwise use the arbitrary sized
00201       // mergable section.
00202       switch (TM.getDataLayout()->getTypeAllocSize(C->getType())) {
00203       case 4:  return SectionKind::getMergeableConst4();
00204       case 8:  return SectionKind::getMergeableConst8();
00205       case 16: return SectionKind::getMergeableConst16();
00206       default: return SectionKind::getMergeableConst();
00207       }
00208 
00209     case Constant::LocalRelocation:
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.local section.
00220       return SectionKind::getReadOnlyWithRelLocal();
00221 
00222     case Constant::GlobalRelocations:
00223       // In static relocation model, the linker will resolve all addresses, so
00224       // the relocation entries will actually be constants by the time the app
00225       // starts up.  However, we can't put this into a mergable section, because
00226       // the linker doesn't take relocations into consideration when it tries to
00227       // merge entries in the section.
00228       if (ReloModel == Reloc::Static)
00229         return SectionKind::getReadOnly();
00230 
00231       // Otherwise, the dynamic linker needs to fix it up, put it in the
00232       // writable data.rel section.
00233       return SectionKind::getReadOnlyWithRel();
00234     }
00235   }
00236 
00237   // Okay, this isn't a constant.  If the initializer for the global is going
00238   // to require a runtime relocation by the dynamic linker, put it into a more
00239   // specific section to improve startup time of the app.  This coalesces these
00240   // globals together onto fewer pages, improving the locality of the dynamic
00241   // linker.
00242   if (ReloModel == Reloc::Static)
00243     return SectionKind::getDataNoRel();
00244 
00245   switch (C->getRelocationInfo()) {
00246   case Constant::NoRelocation:
00247     return SectionKind::getDataNoRel();
00248   case Constant::LocalRelocation:
00249     return SectionKind::getDataRelLocal();
00250   case Constant::GlobalRelocations:
00251     return SectionKind::getDataRel();
00252   }
00253   llvm_unreachable("Invalid relocation");
00254 }
00255 
00256 /// SectionForGlobal - This method computes the appropriate section to emit
00257 /// the specified global variable or function definition.  This should not
00258 /// be passed external (or available externally) globals.
00259 const MCSection *TargetLoweringObjectFile::
00260 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00261                  const TargetMachine &TM) const {
00262   // Select section name.
00263   if (GV->hasSection())
00264     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
00265 
00266 
00267   // Use default section depending on the 'type' of global
00268   return SelectSectionForGlobal(GV, Kind, Mang, TM);
00269 }
00270 
00271 bool TargetLoweringObjectFile::isSectionAtomizableBySymbols(
00272     const MCSection &Section) const {
00273   return false;
00274 }
00275 
00276 // Lame default implementation. Calculate the section name for global.
00277 const MCSection *
00278 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
00279                                                  SectionKind Kind,
00280                                                  Mangler &Mang,
00281                                                  const TargetMachine &TM) const{
00282   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
00283 
00284   if (Kind.isText())
00285     return getTextSection();
00286 
00287   if (Kind.isBSS() && BSSSection != nullptr)
00288     return BSSSection;
00289 
00290   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
00291     return ReadOnlySection;
00292 
00293   return getDataSection();
00294 }
00295 
00296 /// getSectionForConstant - Given a mergable constant with the
00297 /// specified size and relocation information, return a section that it
00298 /// should be placed in.
00299 const MCSection *
00300 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind,
00301                                                 const Constant *C) const {
00302   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
00303     return ReadOnlySection;
00304 
00305   return DataSection;
00306 }
00307 
00308 /// getTTypeGlobalReference - Return an MCExpr to use for a
00309 /// reference to the specified global variable from exception
00310 /// handling information.
00311 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
00312     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00313     const TargetMachine &TM, MachineModuleInfo *MMI,
00314     MCStreamer &Streamer) const {
00315   const MCSymbolRefExpr *Ref =
00316       MCSymbolRefExpr::Create(TM.getSymbol(GV, Mang), getContext());
00317 
00318   return getTTypeReference(Ref, Encoding, Streamer);
00319 }
00320 
00321 const MCExpr *TargetLoweringObjectFile::
00322 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
00323                   MCStreamer &Streamer) const {
00324   switch (Encoding & 0x70) {
00325   default:
00326     report_fatal_error("We do not support this DWARF encoding yet!");
00327   case dwarf::DW_EH_PE_absptr:
00328     // Do nothing special
00329     return Sym;
00330   case dwarf::DW_EH_PE_pcrel: {
00331     // Emit a label to the streamer for the current position.  This gives us
00332     // .-foo addressing.
00333     MCSymbol *PCSym = getContext().CreateTempSymbol();
00334     Streamer.EmitLabel(PCSym);
00335     const MCExpr *PC = MCSymbolRefExpr::Create(PCSym, getContext());
00336     return MCBinaryExpr::CreateSub(Sym, PC, getContext());
00337   }
00338   }
00339 }
00340 
00341 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
00342   // FIXME: It's not clear what, if any, default this should have - perhaps a
00343   // null return could mean 'no location' & we should just do that here.
00344   return MCSymbolRefExpr::Create(Sym, *Ctx);
00345 }