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   DL = TM.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);
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.getDataLayout()->getTypeAllocSize(C->getType())) {
00204       case 4:  return SectionKind::getMergeableConst4();
00205       case 8:  return SectionKind::getMergeableConst8();
00206       case 16: return SectionKind::getMergeableConst16();
00207       default:
00208         return SectionKind::getReadOnly();
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 /// This method computes the appropriate section to emit the specified global
00259 /// variable or function definition.  This should not be passed external (or
00260 /// available externally) globals.
00261 MCSection *
00262 TargetLoweringObjectFile::SectionForGlobal(const GlobalValue *GV,
00263                                            SectionKind Kind, Mangler &Mang,
00264                                            const TargetMachine &TM) const {
00265   // Select section name.
00266   if (GV->hasSection())
00267     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
00268 
00269 
00270   // Use default section depending on the 'type' of global
00271   return SelectSectionForGlobal(GV, Kind, Mang, TM);
00272 }
00273 
00274 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
00275     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
00276   return getSectionForConstant(SectionKind::getReadOnly(), /*C=*/nullptr);
00277 }
00278 
00279 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
00280     bool UsesLabelDifference, const Function &F) const {
00281   // In PIC mode, we need to emit the jump table to the same section as the
00282   // function body itself, otherwise the label differences won't make sense.
00283   // FIXME: Need a better predicate for this: what about custom entries?
00284   if (UsesLabelDifference)
00285     return true;
00286 
00287   // We should also do if the section name is NULL or function is declared
00288   // in discardable section
00289   // FIXME: this isn't the right predicate, should be based on the MCSection
00290   // for the function.
00291   if (F.isWeakForLinker())
00292     return true;
00293 
00294   return false;
00295 }
00296 
00297 /// Given a mergable constant with the specified size and relocation
00298 /// information, return a section that it should be placed in.
00299 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 }
00346 
00347 void TargetLoweringObjectFile::getNameWithPrefix(
00348     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
00349     bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
00350   Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
00351 }