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 #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   DL = TM.getSubtargetImpl()->getDataLayout();
00047   InitMCObjectFileInfo(TM.getTargetTriple(),
00048                        TM.getRelocationModel(), TM.getCodeModel(), *Ctx);
00049 }
00050 
00051 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
00052 }
00053 
00054 static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
00055   const Constant *C = GV->getInitializer();
00056 
00057   // Must have zero initializer.
00058   if (!C->isNullValue())
00059     return false;
00060 
00061   // Leave constant zeros in readonly constant sections, so they can be shared.
00062   if (GV->isConstant())
00063     return false;
00064 
00065   // If the global has an explicit section specified, don't put it in BSS.
00066   if (GV->hasSection())
00067     return false;
00068 
00069   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
00070   if (NoZerosInBSS)
00071     return false;
00072 
00073   // Otherwise, put it in BSS!
00074   return true;
00075 }
00076 
00077 /// IsNullTerminatedString - Return true if the specified constant (which is
00078 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
00079 /// nul value and contains no other nuls in it.  Note that this is more general
00080 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
00081 static bool IsNullTerminatedString(const Constant *C) {
00082   // First check: is we have constant array terminated with zero
00083   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
00084     unsigned NumElts = CDS->getNumElements();
00085     assert(NumElts != 0 && "Can't have an empty CDS");
00086     
00087     if (CDS->getElementAsInteger(NumElts-1) != 0)
00088       return false; // Not null terminated.
00089     
00090     // Verify that the null doesn't occur anywhere else in the string.
00091     for (unsigned i = 0; i != NumElts-1; ++i)
00092       if (CDS->getElementAsInteger(i) == 0)
00093         return false;
00094     return true;
00095   }
00096 
00097   // Another possibility: [1 x i8] zeroinitializer
00098   if (isa<ConstantAggregateZero>(C))
00099     return cast<ArrayType>(C->getType())->getNumElements() == 1;
00100 
00101   return false;
00102 }
00103 
00104 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
00105     const GlobalValue *GV, StringRef Suffix, Mangler &Mang,
00106     const TargetMachine &TM) const {
00107   assert(!Suffix.empty());
00108 
00109   SmallString<60> NameStr;
00110   NameStr += DL->getPrivateGlobalPrefix();
00111   TM.getNameWithPrefix(NameStr, GV, Mang);
00112   NameStr.append(Suffix.begin(), Suffix.end());
00113   return Ctx->GetOrCreateSymbol(NameStr.str());
00114 }
00115 
00116 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
00117     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00118     MachineModuleInfo *MMI) const {
00119   return TM.getSymbol(GV, Mang);
00120 }
00121 
00122 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
00123                                                     const TargetMachine &TM,
00124                                                     const MCSymbol *Sym) const {
00125 }
00126 
00127 
00128 /// getKindForGlobal - This is a top-level target-independent classifier for
00129 /// a global variable.  Given an global variable and information from TM, it
00130 /// classifies the global in a variety of ways that make various target
00131 /// implementations simpler.  The target implementation is free to ignore this
00132 /// extra info of course.
00133 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
00134                                                        const TargetMachine &TM){
00135   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
00136          "Can only be used for global definitions");
00137 
00138   Reloc::Model ReloModel = TM.getRelocationModel();
00139 
00140   // Early exit - functions should be always in text sections.
00141   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00142   if (!GVar)
00143     return SectionKind::getText();
00144 
00145   // Handle thread-local data first.
00146   if (GVar->isThreadLocal()) {
00147     if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
00148       return SectionKind::getThreadBSS();
00149     return SectionKind::getThreadData();
00150   }
00151 
00152   // Variables with common linkage always get classified as common.
00153   if (GVar->hasCommonLinkage())
00154     return SectionKind::getCommon();
00155 
00156   // Variable can be easily put to BSS section.
00157   if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
00158     if (GVar->hasLocalLinkage())
00159       return SectionKind::getBSSLocal();
00160     else if (GVar->hasExternalLinkage())
00161       return SectionKind::getBSSExtern();
00162     return SectionKind::getBSS();
00163   }
00164 
00165   const Constant *C = GVar->getInitializer();
00166 
00167   // If the global is marked constant, we can put it into a mergable section,
00168   // a mergable string section, or general .data if it contains relocations.
00169   if (GVar->isConstant()) {
00170     // If the initializer for the global contains something that requires a
00171     // relocation, then we may have to drop this into a writable data section
00172     // even though it is marked const.
00173     switch (C->getRelocationInfo()) {
00174     case Constant::NoRelocation:
00175       // If the global is required to have a unique address, it can't be put
00176       // into a mergable section: just drop it into the general read-only
00177       // section instead.
00178       if (!GVar->hasUnnamedAddr())
00179         return SectionKind::getReadOnly();
00180         
00181       // If initializer is a null-terminated string, put it in a "cstring"
00182       // section of the right width.
00183       if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
00184         if (IntegerType *ITy =
00185               dyn_cast<IntegerType>(ATy->getElementType())) {
00186           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
00187                ITy->getBitWidth() == 32) &&
00188               IsNullTerminatedString(C)) {
00189             if (ITy->getBitWidth() == 8)
00190               return SectionKind::getMergeable1ByteCString();
00191             if (ITy->getBitWidth() == 16)
00192               return SectionKind::getMergeable2ByteCString();
00193 
00194             assert(ITy->getBitWidth() == 32 && "Unknown width");
00195             return SectionKind::getMergeable4ByteCString();
00196           }
00197         }
00198       }
00199 
00200       // Otherwise, just drop it into a mergable constant section.  If we have
00201       // a section for this size, use it, otherwise use the arbitrary sized
00202       // mergable section.
00203       switch (TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(
00204           C->getType())) {
00205       case 4:  return SectionKind::getMergeableConst4();
00206       case 8:  return SectionKind::getMergeableConst8();
00207       case 16: return SectionKind::getMergeableConst16();
00208       default: return SectionKind::getMergeableConst();
00209       }
00210 
00211     case Constant::LocalRelocation:
00212       // In static relocation model, the linker will resolve all addresses, so
00213       // the relocation entries will actually be constants by the time the app
00214       // starts up.  However, we can't put this into a mergable section, because
00215       // the linker doesn't take relocations into consideration when it tries to
00216       // merge entries in the section.
00217       if (ReloModel == Reloc::Static)
00218         return SectionKind::getReadOnly();
00219 
00220       // Otherwise, the dynamic linker needs to fix it up, put it in the
00221       // writable data.rel.local section.
00222       return SectionKind::getReadOnlyWithRelLocal();
00223 
00224     case Constant::GlobalRelocations:
00225       // In static relocation model, the linker will resolve all addresses, so
00226       // the relocation entries will actually be constants by the time the app
00227       // starts up.  However, we can't put this into a mergable section, because
00228       // the linker doesn't take relocations into consideration when it tries to
00229       // merge entries in the section.
00230       if (ReloModel == Reloc::Static)
00231         return SectionKind::getReadOnly();
00232 
00233       // Otherwise, the dynamic linker needs to fix it up, put it in the
00234       // writable data.rel section.
00235       return SectionKind::getReadOnlyWithRel();
00236     }
00237   }
00238 
00239   // Okay, this isn't a constant.  If the initializer for the global is going
00240   // to require a runtime relocation by the dynamic linker, put it into a more
00241   // specific section to improve startup time of the app.  This coalesces these
00242   // globals together onto fewer pages, improving the locality of the dynamic
00243   // linker.
00244   if (ReloModel == Reloc::Static)
00245     return SectionKind::getDataNoRel();
00246 
00247   switch (C->getRelocationInfo()) {
00248   case Constant::NoRelocation:
00249     return SectionKind::getDataNoRel();
00250   case Constant::LocalRelocation:
00251     return SectionKind::getDataRelLocal();
00252   case Constant::GlobalRelocations:
00253     return SectionKind::getDataRel();
00254   }
00255   llvm_unreachable("Invalid relocation");
00256 }
00257 
00258 /// SectionForGlobal - This method computes the appropriate section to emit
00259 /// the specified global variable or function definition.  This should not
00260 /// be passed external (or available externally) globals.
00261 const MCSection *TargetLoweringObjectFile::
00262 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00263                  const TargetMachine &TM) const {
00264   // Select section name.
00265   if (GV->hasSection())
00266     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
00267 
00268 
00269   // Use default section depending on the 'type' of global
00270   return SelectSectionForGlobal(GV, Kind, Mang, TM);
00271 }
00272 
00273 bool TargetLoweringObjectFile::isSectionAtomizableBySymbols(
00274     const MCSection &Section) const {
00275   return false;
00276 }
00277 
00278 
00279 /// getSectionForConstant - Given a mergable constant with the
00280 /// specified size and relocation information, return a section that it
00281 /// should be placed in.
00282 const MCSection *
00283 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind,
00284                                                 const Constant *C) const {
00285   if (Kind.isReadOnly() && ReadOnlySection != nullptr)
00286     return ReadOnlySection;
00287 
00288   return DataSection;
00289 }
00290 
00291 /// getTTypeGlobalReference - Return an MCExpr to use for a
00292 /// reference to the specified global variable from exception
00293 /// handling information.
00294 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
00295     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00296     const TargetMachine &TM, MachineModuleInfo *MMI,
00297     MCStreamer &Streamer) const {
00298   const MCSymbolRefExpr *Ref =
00299       MCSymbolRefExpr::Create(TM.getSymbol(GV, Mang), getContext());
00300 
00301   return getTTypeReference(Ref, Encoding, Streamer);
00302 }
00303 
00304 const MCExpr *TargetLoweringObjectFile::
00305 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
00306                   MCStreamer &Streamer) const {
00307   switch (Encoding & 0x70) {
00308   default:
00309     report_fatal_error("We do not support this DWARF encoding yet!");
00310   case dwarf::DW_EH_PE_absptr:
00311     // Do nothing special
00312     return Sym;
00313   case dwarf::DW_EH_PE_pcrel: {
00314     // Emit a label to the streamer for the current position.  This gives us
00315     // .-foo addressing.
00316     MCSymbol *PCSym = getContext().CreateTempSymbol();
00317     Streamer.EmitLabel(PCSym);
00318     const MCExpr *PC = MCSymbolRefExpr::Create(PCSym, getContext());
00319     return MCBinaryExpr::CreateSub(Sym, PC, getContext());
00320   }
00321   }
00322 }
00323 
00324 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
00325   // FIXME: It's not clear what, if any, default this should have - perhaps a
00326   // null return could mean 'no location' & we should just do that here.
00327   return MCSymbolRefExpr::Create(Sym, *Ctx);
00328 }