1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetLoweringObjectFile.h"
15 #include "llvm/BinaryFormat/Dwarf.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/IR/Module.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/SectionKind.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 using namespace llvm;
32
33 //===----------------------------------------------------------------------===//
34 // Generic Code
35 //===----------------------------------------------------------------------===//
36
37 /// Initialize - this method must be called before any actual lowering is
38 /// done. This specifies the current context for codegen, and gives the
39 /// lowering implementations a chance to set up their default sections.
Initialize(MCContext & ctx,const TargetMachine & TM)40 void TargetLoweringObjectFile::Initialize(MCContext &ctx,
41 const TargetMachine &TM) {
42 // `Initialize` can be called more than once.
43 delete Mang;
44 Mang = new Mangler();
45 initMCObjectFileInfo(ctx, TM.isPositionIndependent(),
46 TM.getCodeModel() == CodeModel::Large);
47
48 // Reset various EH DWARF encodings.
49 PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr;
50 CallSiteEncoding = dwarf::DW_EH_PE_uleb128;
51
52 this->TM = &TM;
53 }
54
~TargetLoweringObjectFile()55 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
56 delete Mang;
57 }
58
getCallSiteEncoding() const59 unsigned TargetLoweringObjectFile::getCallSiteEncoding() const {
60 // If target does not have LEB128 directives, we would need the
61 // call site encoding to be udata4 so that the alternative path
62 // for not having LEB128 directives could work.
63 if (!getContext().getAsmInfo()->hasLEB128Directives())
64 return dwarf::DW_EH_PE_udata4;
65 return CallSiteEncoding;
66 }
67
isNullOrUndef(const Constant * C)68 static bool isNullOrUndef(const Constant *C) {
69 // Check that the constant isn't all zeros or undefs.
70 if (C->isNullValue() || isa<UndefValue>(C))
71 return true;
72 if (!isa<ConstantAggregate>(C))
73 return false;
74 for (const auto *Operand : C->operand_values()) {
75 if (!isNullOrUndef(cast<Constant>(Operand)))
76 return false;
77 }
78 return true;
79 }
80
isSuitableForBSS(const GlobalVariable * GV)81 static bool isSuitableForBSS(const GlobalVariable *GV) {
82 const Constant *C = GV->getInitializer();
83
84 // Must have zero initializer.
85 if (!isNullOrUndef(C))
86 return false;
87
88 // Leave constant zeros in readonly constant sections, so they can be shared.
89 if (GV->isConstant())
90 return false;
91
92 // If the global has an explicit section specified, don't put it in BSS.
93 if (GV->hasSection())
94 return false;
95
96 // Otherwise, put it in BSS!
97 return true;
98 }
99
100 /// IsNullTerminatedString - Return true if the specified constant (which is
101 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
102 /// nul value and contains no other nuls in it. Note that this is more general
103 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
IsNullTerminatedString(const Constant * C)104 static bool IsNullTerminatedString(const Constant *C) {
105 // First check: is we have constant array terminated with zero
106 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
107 uint64_t NumElts = CDS->getNumElements();
108 assert(NumElts != 0 && "Can't have an empty CDS");
109
110 if (CDS->getElementAsInteger(NumElts-1) != 0)
111 return false; // Not null terminated.
112
113 // Verify that the null doesn't occur anywhere else in the string.
114 for (uint64_t i = 0; i != NumElts - 1; ++i)
115 if (CDS->getElementAsInteger(i) == 0)
116 return false;
117 return true;
118 }
119
120 // Another possibility: [1 x i8] zeroinitializer
121 if (isa<ConstantAggregateZero>(C))
122 return cast<ArrayType>(C->getType())->getNumElements() == 1;
123
124 return false;
125 }
126
getSymbolWithGlobalValueBase(const GlobalValue * GV,StringRef Suffix,const TargetMachine & TM) const127 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
128 const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
129 assert(!Suffix.empty());
130
131 SmallString<60> NameStr;
132 NameStr += GV->getDataLayout().getPrivateGlobalPrefix();
133 TM.getNameWithPrefix(NameStr, GV, *Mang);
134 NameStr.append(Suffix.begin(), Suffix.end());
135 return getContext().getOrCreateSymbol(NameStr);
136 }
137
getCFIPersonalitySymbol(const GlobalValue * GV,const TargetMachine & TM,MachineModuleInfo * MMI) const138 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
139 const GlobalValue *GV, const TargetMachine &TM,
140 MachineModuleInfo *MMI) const {
141 return TM.getSymbol(GV);
142 }
143
emitPersonalityValue(MCStreamer & Streamer,const DataLayout &,const MCSymbol * Sym,const MachineModuleInfo * MMI) const144 void TargetLoweringObjectFile::emitPersonalityValue(
145 MCStreamer &Streamer, const DataLayout &, const MCSymbol *Sym,
146 const MachineModuleInfo *MMI) const {}
147
emitCGProfileMetadata(MCStreamer & Streamer,Module & M) const148 void TargetLoweringObjectFile::emitCGProfileMetadata(MCStreamer &Streamer,
149 Module &M) const {
150 MCContext &C = getContext();
151 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
152 M.getModuleFlagsMetadata(ModuleFlags);
153
154 MDNode *CFGProfile = nullptr;
155
156 for (const auto &MFE : ModuleFlags) {
157 StringRef Key = MFE.Key->getString();
158 if (Key == "CG Profile") {
159 CFGProfile = cast<MDNode>(MFE.Val);
160 break;
161 }
162 }
163
164 if (!CFGProfile)
165 return;
166
167 auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
168 if (!MDO)
169 return nullptr;
170 auto *V = cast<ValueAsMetadata>(MDO);
171 const Function *F = cast<Function>(V->getValue()->stripPointerCasts());
172 if (F->hasDLLImportStorageClass())
173 return nullptr;
174 return TM->getSymbol(F);
175 };
176
177 for (const auto &Edge : CFGProfile->operands()) {
178 MDNode *E = cast<MDNode>(Edge);
179 const MCSymbol *From = GetSym(E->getOperand(0));
180 const MCSymbol *To = GetSym(E->getOperand(1));
181 // Skip null functions. This can happen if functions are dead stripped after
182 // the CGProfile pass has been run.
183 if (!From || !To)
184 continue;
185 uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
186 ->getValue()
187 ->getUniqueInteger()
188 .getZExtValue();
189 Streamer.emitCGProfileEntry(MCSymbolRefExpr::create(From, C),
190 MCSymbolRefExpr::create(To, C), Count);
191 }
192 }
193
emitPseudoProbeDescMetadata(MCStreamer & Streamer,Module & M) const194 void TargetLoweringObjectFile::emitPseudoProbeDescMetadata(MCStreamer &Streamer,
195 Module &M) const {
196 NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName);
197 if (!FuncInfo)
198 return;
199
200 // Emit a descriptor for every function including functions that have an
201 // available external linkage. We may not want this for imported functions
202 // that has code in another thinLTO module but we don't have a good way to
203 // tell them apart from inline functions defined in header files. Therefore
204 // we put each descriptor in a separate comdat section and rely on the
205 // linker to deduplicate.
206 auto &C = getContext();
207 for (const auto *Operand : FuncInfo->operands()) {
208 const auto *MD = cast<MDNode>(Operand);
209 auto *GUID = mdconst::extract<ConstantInt>(MD->getOperand(0));
210 auto *Hash = mdconst::extract<ConstantInt>(MD->getOperand(1));
211 auto *Name = cast<MDString>(MD->getOperand(2));
212 auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
213 TM->getFunctionSections() ? Name->getString() : StringRef());
214
215 Streamer.switchSection(S);
216 Streamer.emitInt64(GUID->getZExtValue());
217 Streamer.emitInt64(Hash->getZExtValue());
218 Streamer.emitULEB128IntValue(Name->getString().size());
219 Streamer.emitBytes(Name->getString());
220 }
221 }
222
223 /// getKindForGlobal - This is a top-level target-independent classifier for
224 /// a global object. Given a global variable and information from the TM, this
225 /// function classifies the global in a target independent manner. This function
226 /// may be overridden by the target implementation.
getKindForGlobal(const GlobalObject * GO,const TargetMachine & TM)227 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
228 const TargetMachine &TM){
229 assert(!GO->isDeclarationForLinker() &&
230 "Can only be used for global definitions");
231
232 // Functions are classified as text sections.
233 if (isa<Function>(GO))
234 return SectionKind::getText();
235
236 // Basic blocks are classified as text sections.
237 if (isa<BasicBlock>(GO))
238 return SectionKind::getText();
239
240 // Global variables require more detailed analysis.
241 const auto *GVar = cast<GlobalVariable>(GO);
242
243 // Handle thread-local data first.
244 if (GVar->isThreadLocal()) {
245 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) {
246 // Zero-initialized TLS variables with local linkage always get classified
247 // as ThreadBSSLocal.
248 if (GVar->hasLocalLinkage()) {
249 return SectionKind::getThreadBSSLocal();
250 }
251 return SectionKind::getThreadBSS();
252 }
253 return SectionKind::getThreadData();
254 }
255
256 // Variables with common linkage always get classified as common.
257 if (GVar->hasCommonLinkage())
258 return SectionKind::getCommon();
259
260 // Most non-mergeable zero data can be put in the BSS section unless otherwise
261 // specified.
262 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) {
263 if (GVar->hasLocalLinkage())
264 return SectionKind::getBSSLocal();
265 else if (GVar->hasExternalLinkage())
266 return SectionKind::getBSSExtern();
267 return SectionKind::getBSS();
268 }
269
270 // Global variables with '!exclude' should get the exclude section kind if
271 // they have an explicit section and no other metadata.
272 if (GVar->hasSection())
273 if (MDNode *MD = GVar->getMetadata(LLVMContext::MD_exclude))
274 if (!MD->getNumOperands())
275 return SectionKind::getExclude();
276
277 // If the global is marked constant, we can put it into a mergable section,
278 // a mergable string section, or general .data if it contains relocations.
279 if (GVar->isConstant()) {
280 // If the initializer for the global contains something that requires a
281 // relocation, then we may have to drop this into a writable data section
282 // even though it is marked const.
283 const Constant *C = GVar->getInitializer();
284 if (!C->needsRelocation()) {
285 // If the global is required to have a unique address, it can't be put
286 // into a mergable section: just drop it into the general read-only
287 // section instead.
288 if (!GVar->hasGlobalUnnamedAddr())
289 return SectionKind::getReadOnly();
290
291 // If initializer is a null-terminated string, put it in a "cstring"
292 // section of the right width.
293 if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
294 if (IntegerType *ITy =
295 dyn_cast<IntegerType>(ATy->getElementType())) {
296 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
297 ITy->getBitWidth() == 32) &&
298 IsNullTerminatedString(C)) {
299 if (ITy->getBitWidth() == 8)
300 return SectionKind::getMergeable1ByteCString();
301 if (ITy->getBitWidth() == 16)
302 return SectionKind::getMergeable2ByteCString();
303
304 assert(ITy->getBitWidth() == 32 && "Unknown width");
305 return SectionKind::getMergeable4ByteCString();
306 }
307 }
308 }
309
310 // Otherwise, just drop it into a mergable constant section. If we have
311 // a section for this size, use it, otherwise use the arbitrary sized
312 // mergable section.
313 switch (
314 GVar->getDataLayout().getTypeAllocSize(C->getType())) {
315 case 4: return SectionKind::getMergeableConst4();
316 case 8: return SectionKind::getMergeableConst8();
317 case 16: return SectionKind::getMergeableConst16();
318 case 32: return SectionKind::getMergeableConst32();
319 default:
320 return SectionKind::getReadOnly();
321 }
322
323 } else {
324 // In static, ROPI and RWPI relocation models, the linker will resolve
325 // all addresses, so the relocation entries will actually be constants by
326 // the time the app starts up. However, we can't put this into a
327 // mergable section, because the linker doesn't take relocations into
328 // consideration when it tries to merge entries in the section.
329 Reloc::Model ReloModel = TM.getRelocationModel();
330 if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI ||
331 ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI ||
332 !C->needsDynamicRelocation())
333 return SectionKind::getReadOnly();
334
335 // Otherwise, the dynamic linker needs to fix it up, put it in the
336 // writable data.rel section.
337 return SectionKind::getReadOnlyWithRel();
338 }
339 }
340
341 // Okay, this isn't a constant.
342 return SectionKind::getData();
343 }
344
345 /// This method computes the appropriate section to emit the specified global
346 /// variable or function definition. This should not be passed external (or
347 /// available externally) globals.
SectionForGlobal(const GlobalObject * GO,SectionKind Kind,const TargetMachine & TM) const348 MCSection *TargetLoweringObjectFile::SectionForGlobal(
349 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
350 // Select section name.
351 if (GO->hasSection())
352 return getExplicitSectionGlobal(GO, Kind, TM);
353
354 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
355 auto Attrs = GVar->getAttributes();
356 if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) ||
357 (Attrs.hasAttribute("data-section") && Kind.isData()) ||
358 (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) ||
359 (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) {
360 return getExplicitSectionGlobal(GO, Kind, TM);
361 }
362 }
363
364 // Use default section depending on the 'type' of global
365 return SelectSectionForGlobal(GO, Kind, TM);
366 }
367
368 /// This method computes the appropriate section to emit the specified global
369 /// variable or function definition. This should not be passed external (or
370 /// available externally) globals.
371 MCSection *
SectionForGlobal(const GlobalObject * GO,const TargetMachine & TM) const372 TargetLoweringObjectFile::SectionForGlobal(const GlobalObject *GO,
373 const TargetMachine &TM) const {
374 return SectionForGlobal(GO, getKindForGlobal(GO, TM), TM);
375 }
376
getSectionForJumpTable(const Function & F,const TargetMachine & TM) const377 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
378 const Function &F, const TargetMachine &TM) const {
379 return getSectionForJumpTable(F, TM, /*JTE=*/nullptr);
380 }
381
getSectionForJumpTable(const Function & F,const TargetMachine & TM,const MachineJumpTableEntry * JTE) const382 MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
383 const Function &F, const TargetMachine &TM,
384 const MachineJumpTableEntry *JTE) const {
385 Align Alignment(1);
386 return getSectionForConstant(F.getDataLayout(),
387 SectionKind::getReadOnly(), /*C=*/nullptr,
388 Alignment);
389 }
390
shouldPutJumpTableInFunctionSection(bool UsesLabelDifference,const Function & F) const391 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
392 bool UsesLabelDifference, const Function &F) const {
393 // In PIC mode, we need to emit the jump table to the same section as the
394 // function body itself, otherwise the label differences won't make sense.
395 // FIXME: Need a better predicate for this: what about custom entries?
396 if (UsesLabelDifference)
397 return true;
398
399 // We should also do if the section name is NULL or function is declared
400 // in discardable section
401 // FIXME: this isn't the right predicate, should be based on the MCSection
402 // for the function.
403 return F.isWeakForLinker();
404 }
405
406 /// Given a mergable constant with the specified size and relocation
407 /// information, return a section that it should be placed in.
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment) const408 MCSection *TargetLoweringObjectFile::getSectionForConstant(
409 const DataLayout &DL, SectionKind Kind, const Constant *C,
410 Align &Alignment) const {
411 if (Kind.isReadOnly() && ReadOnlySection != nullptr)
412 return ReadOnlySection;
413
414 return DataSection;
415 }
416
getSectionForConstant(const DataLayout & DL,SectionKind Kind,const Constant * C,Align & Alignment,StringRef SectionPrefix) const417 MCSection *TargetLoweringObjectFile::getSectionForConstant(
418 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
419 StringRef SectionPrefix) const {
420 // Fallback to `getSectionForConstant` without `SectionPrefix` parameter if it
421 // is empty.
422 if (SectionPrefix.empty())
423 return getSectionForConstant(DL, Kind, C, Alignment);
424 report_fatal_error(
425 "TargetLoweringObjectFile::getSectionForConstant that "
426 "accepts SectionPrefix is not implemented for the object file format");
427 }
428
getSectionForMachineBasicBlock(const Function & F,const MachineBasicBlock & MBB,const TargetMachine & TM) const429 MCSection *TargetLoweringObjectFile::getSectionForMachineBasicBlock(
430 const Function &F, const MachineBasicBlock &MBB,
431 const TargetMachine &TM) const {
432 return nullptr;
433 }
434
getUniqueSectionForFunction(const Function & F,const TargetMachine & TM) const435 MCSection *TargetLoweringObjectFile::getUniqueSectionForFunction(
436 const Function &F, const TargetMachine &TM) const {
437 return nullptr;
438 }
439
440 /// getTTypeGlobalReference - Return an MCExpr to use for a
441 /// reference to the specified global variable from exception
442 /// handling information.
getTTypeGlobalReference(const GlobalValue * GV,unsigned Encoding,const TargetMachine & TM,MachineModuleInfo * MMI,MCStreamer & Streamer) const443 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
444 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
445 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
446 const MCSymbolRefExpr *Ref =
447 MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
448
449 return getTTypeReference(Ref, Encoding, Streamer);
450 }
451
452 const MCExpr *TargetLoweringObjectFile::
getTTypeReference(const MCSymbolRefExpr * Sym,unsigned Encoding,MCStreamer & Streamer) const453 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
454 MCStreamer &Streamer) const {
455 switch (Encoding & 0x70) {
456 default:
457 report_fatal_error("We do not support this DWARF encoding yet!");
458 case dwarf::DW_EH_PE_absptr:
459 // Do nothing special
460 return Sym;
461 case dwarf::DW_EH_PE_pcrel: {
462 // Emit a label to the streamer for the current position. This gives us
463 // .-foo addressing.
464 MCSymbol *PCSym = getContext().createTempSymbol();
465 Streamer.emitLabel(PCSym);
466 const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
467 return MCBinaryExpr::createSub(Sym, PC, getContext());
468 }
469 }
470 }
471
getDebugThreadLocalSymbol(const MCSymbol * Sym) const472 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
473 // FIXME: It's not clear what, if any, default this should have - perhaps a
474 // null return could mean 'no location' & we should just do that here.
475 return MCSymbolRefExpr::create(Sym, getContext());
476 }
477
getNameWithPrefix(SmallVectorImpl<char> & OutName,const GlobalValue * GV,const TargetMachine & TM) const478 void TargetLoweringObjectFile::getNameWithPrefix(
479 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
480 const TargetMachine &TM) const {
481 Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
482 }
483