Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Target/TargetLoweringObjectFile.cpp
Line
Count
Source (jump to first uncovered line)
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/MC/MCContext.h"
23
#include "llvm/MC/MCExpr.h"
24
#include "llvm/MC/MCStreamer.h"
25
#include "llvm/MC/MCSymbol.h"
26
#include "llvm/Support/ErrorHandling.h"
27
#include "llvm/Support/raw_ostream.h"
28
#include "llvm/Target/TargetMachine.h"
29
#include "llvm/Target/TargetOptions.h"
30
using namespace llvm;
31
32
//===----------------------------------------------------------------------===//
33
//                              Generic Code
34
//===----------------------------------------------------------------------===//
35
36
/// Initialize - this method must be called before any actual lowering is
37
/// done.  This specifies the current context for codegen, and gives the
38
/// lowering implementations a chance to set up their default sections.
39
void TargetLoweringObjectFile::Initialize(MCContext &ctx,
40
36.1k
                                          const TargetMachine &TM) {
41
36.1k
  Ctx = &ctx;
42
36.1k
  // `Initialize` can be called more than once.
43
36.1k
  delete Mang;
44
36.1k
  Mang = new Mangler();
45
36.1k
  InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), *Ctx,
46
36.1k
                       TM.getCodeModel() == CodeModel::Large);
47
36.1k
48
36.1k
  // Reset various EH DWARF encodings.
49
36.1k
  PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr;
50
36.1k
  CallSiteEncoding = dwarf::DW_EH_PE_uleb128;
51
36.1k
}
52
53
39.6k
TargetLoweringObjectFile::~TargetLoweringObjectFile() {
54
39.6k
  delete Mang;
55
39.6k
}
56
57
621k
static bool isNullOrUndef(const Constant *C) {
58
621k
  // Check that the constant isn't all zeros or undefs.
59
621k
  if (C->isNullValue() || 
isa<UndefValue>(C)564k
)
60
57.8k
    return true;
61
564k
  if (!isa<ConstantAggregate>(C))
62
525k
    return false;
63
51.2k
  
for (auto Operand : C->operand_values())38.9k
{
64
51.2k
    if (!isNullOrUndef(cast<Constant>(Operand)))
65
38.8k
      return false;
66
51.2k
  }
67
38.9k
  
return true94
;
68
38.9k
}
69
70
570k
static bool isSuitableForBSS(const GlobalVariable *GV) {
71
570k
  const Constant *C = GV->getInitializer();
72
570k
73
570k
  // Must have zero initializer.
74
570k
  if (!isNullOrUndef(C))
75
525k
    return false;
76
45.4k
77
45.4k
  // Leave constant zeros in readonly constant sections, so they can be shared.
78
45.4k
  if (GV->isConstant())
79
2.48k
    return false;
80
43.0k
81
43.0k
  // If the global has an explicit section specified, don't put it in BSS.
82
43.0k
  if (GV->hasSection())
83
93
    return false;
84
42.9k
85
42.9k
  // Otherwise, put it in BSS!
86
42.9k
  return true;
87
42.9k
}
88
89
/// IsNullTerminatedString - Return true if the specified constant (which is
90
/// known to have a type that is an array of 1/2/4 byte elements) ends with a
91
/// nul value and contains no other nuls in it.  Note that this is more general
92
/// than ConstantDataSequential::isString because we allow 2 & 4 byte strings.
93
400k
static bool IsNullTerminatedString(const Constant *C) {
94
400k
  // First check: is we have constant array terminated with zero
95
400k
  if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) {
96
398k
    unsigned NumElts = CDS->getNumElements();
97
398k
    assert(NumElts != 0 && "Can't have an empty CDS");
98
398k
99
398k
    if (CDS->getElementAsInteger(NumElts-1) != 0)
100
794
      return false; // Not null terminated.
101
397k
102
397k
    // Verify that the null doesn't occur anywhere else in the string.
103
15.5M
    
for (unsigned i = 0; 397k
i != NumElts-1;
++i15.1M
)
104
15.1M
      if (CDS->getElementAsInteger(i) == 0)
105
217
        return false;
106
397k
    
return true397k
;
107
2.25k
  }
108
2.25k
109
2.25k
  // Another possibility: [1 x i8] zeroinitializer
110
2.25k
  if (isa<ConstantAggregateZero>(C))
111
2.24k
    return cast<ArrayType>(C->getType())->getNumElements() == 1;
112
4
113
4
  return false;
114
4
}
115
116
MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase(
117
14.3k
    const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const {
118
14.3k
  assert(!Suffix.empty());
119
14.3k
120
14.3k
  SmallString<60> NameStr;
121
14.3k
  NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix();
122
14.3k
  TM.getNameWithPrefix(NameStr, GV, *Mang);
123
14.3k
  NameStr.append(Suffix.begin(), Suffix.end());
124
14.3k
  return Ctx->getOrCreateSymbol(NameStr);
125
14.3k
}
126
127
MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol(
128
    const GlobalValue *GV, const TargetMachine &TM,
129
197
    MachineModuleInfo *MMI) const {
130
197
  return TM.getSymbol(GV);
131
197
}
132
133
void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer,
134
                                                    const DataLayout &,
135
483
                                                    const MCSymbol *Sym) const {
136
483
}
137
138
139
/// getKindForGlobal - This is a top-level target-independent classifier for
140
/// a global object.  Given a global variable and information from the TM, this
141
/// function classifies the global in a target independent manner. This function
142
/// may be overridden by the target implementation.
143
SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO,
144
1.08M
                                                       const TargetMachine &TM){
145
1.08M
  assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() &&
146
1.08M
         "Can only be used for global definitions");
147
1.08M
148
1.08M
  // Functions are classified as text sections.
149
1.08M
  if (isa<Function>(GO))
150
498k
    return SectionKind::getText();
151
584k
152
584k
  // Global variables require more detailed analysis.
153
584k
  const auto *GVar = cast<GlobalVariable>(GO);
154
584k
155
584k
  // Handle thread-local data first.
156
584k
  if (GVar->isThreadLocal()) {
157
425
    if (isSuitableForBSS(GVar) && 
!TM.Options.NoZerosInBSS261
)
158
261
      return SectionKind::getThreadBSS();
159
164
    return SectionKind::getThreadData();
160
164
  }
161
584k
162
584k
  // Variables with common linkage always get classified as common.
163
584k
  if (GVar->hasCommonLinkage())
164
14.3k
    return SectionKind::getCommon();
165
570k
166
570k
  // Most non-mergeable zero data can be put in the BSS section unless otherwise
167
570k
  // specified.
168
570k
  if (isSuitableForBSS(GVar) && 
!TM.Options.NoZerosInBSS42.6k
) {
169
42.6k
    if (GVar->hasLocalLinkage())
170
11.3k
      return SectionKind::getBSSLocal();
171
31.2k
    else if (GVar->hasExternalLinkage())
172
7.39k
      return SectionKind::getBSSExtern();
173
23.8k
    return SectionKind::getBSS();
174
23.8k
  }
175
527k
176
527k
  // If the global is marked constant, we can put it into a mergable section,
177
527k
  // a mergable string section, or general .data if it contains relocations.
178
527k
  if (GVar->isConstant()) {
179
489k
    // If the initializer for the global contains something that requires a
180
489k
    // relocation, then we may have to drop this into a writable data section
181
489k
    // even though it is marked const.
182
489k
    const Constant *C = GVar->getInitializer();
183
489k
    if (!C->needsRelocation()) {
184
469k
      // If the global is required to have a unique address, it can't be put
185
469k
      // into a mergable section: just drop it into the general read-only
186
469k
      // section instead.
187
469k
      if (!GVar->hasGlobalUnnamedAddr())
188
68.5k
        return SectionKind::getReadOnly();
189
401k
190
401k
      // If initializer is a null-terminated string, put it in a "cstring"
191
401k
      // section of the right width.
192
401k
      if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
193
401k
        if (IntegerType *ITy =
194
400k
              dyn_cast<IntegerType>(ATy->getElementType())) {
195
400k
          if ((ITy->getBitWidth() == 8 || 
ITy->getBitWidth() == 161.08k
||
196
400k
               
ITy->getBitWidth() == 32850
) &&
197
400k
              
IsNullTerminatedString(C)400k
) {
198
399k
            if (ITy->getBitWidth() == 8)
199
399k
              return SectionKind::getMergeable1ByteCString();
200
270
            if (ITy->getBitWidth() == 16)
201
24
              return SectionKind::getMergeable2ByteCString();
202
246
203
246
            assert(ITy->getBitWidth() == 32 && "Unknown width");
204
246
            return SectionKind::getMergeable4ByteCString();
205
246
          }
206
400k
        }
207
401k
      }
208
2.00k
209
2.00k
      // Otherwise, just drop it into a mergable constant section.  If we have
210
2.00k
      // a section for this size, use it, otherwise use the arbitrary sized
211
2.00k
      // mergable section.
212
2.00k
      switch (
213
2.00k
          GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) {
214
2.00k
      
case 4: return SectionKind::getMergeableConst4()112
;
215
2.00k
      
case 8: return SectionKind::getMergeableConst8()65
;
216
2.00k
      
case 16: return SectionKind::getMergeableConst16()443
;
217
2.00k
      
case 32: return SectionKind::getMergeableConst32()136
;
218
2.00k
      default:
219
1.24k
        return SectionKind::getReadOnly();
220
19.0k
      }
221
19.0k
222
19.0k
    } else {
223
19.0k
      // In static, ROPI and RWPI relocation models, the linker will resolve
224
19.0k
      // all addresses, so the relocation entries will actually be constants by
225
19.0k
      // the time the app starts up.  However, we can't put this into a
226
19.0k
      // mergable section, because the linker doesn't take relocations into
227
19.0k
      // consideration when it tries to merge entries in the section.
228
19.0k
      Reloc::Model ReloModel = TM.getRelocationModel();
229
19.0k
      if (ReloModel == Reloc::Static || 
ReloModel == Reloc::ROPI18.9k
||
230
19.0k
          
ReloModel == Reloc::RWPI18.9k
||
ReloModel == Reloc::ROPI_RWPI18.9k
)
231
169
        return SectionKind::getReadOnly();
232
18.9k
233
18.9k
      // Otherwise, the dynamic linker needs to fix it up, put it in the
234
18.9k
      // writable data.rel section.
235
18.9k
      return SectionKind::getReadOnlyWithRel();
236
18.9k
    }
237
489k
  }
238
38.3k
239
38.3k
  // Okay, this isn't a constant.
240
38.3k
  return SectionKind::getData();
241
38.3k
}
242
243
/// This method computes the appropriate section to emit the specified global
244
/// variable or function definition.  This should not be passed external (or
245
/// available externally) globals.
246
MCSection *TargetLoweringObjectFile::SectionForGlobal(
247
1.05M
    const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
248
1.05M
  // Select section name.
249
1.05M
  if (GO->hasSection())
250
8.58k
    return getExplicitSectionGlobal(GO, Kind, TM);
251
1.04M
252
1.04M
  if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
253
545k
    auto Attrs = GVar->getAttributes();
254
545k
    if ((Attrs.hasAttribute("bss-section") && 
Kind.isBSS()13
) ||
255
545k
        
(545k
Attrs.hasAttribute("data-section")545k
&&
Kind.isData()6
) ||
256
545k
        
(545k
Attrs.hasAttribute("rodata-section")545k
&&
Kind.isReadOnly()4
)) {
257
13
       return getExplicitSectionGlobal(GO, Kind, TM);
258
13
    }
259
1.04M
  }
260
1.04M
261
1.04M
  if (auto *F = dyn_cast<Function>(GO)) {
262
498k
    if (F->hasFnAttribute("implicit-section-name"))
263
2
      return getExplicitSectionGlobal(GO, Kind, TM);
264
1.04M
  }
265
1.04M
266
1.04M
  // Use default section depending on the 'type' of global
267
1.04M
  return SelectSectionForGlobal(GO, Kind, TM);
268
1.04M
}
269
270
MCSection *TargetLoweringObjectFile::getSectionForJumpTable(
271
2.18k
    const Function &F, const TargetMachine &TM) const {
272
2.18k
  unsigned Align = 0;
273
2.18k
  return getSectionForConstant(F.getParent()->getDataLayout(),
274
2.18k
                               SectionKind::getReadOnly(), /*C=*/nullptr,
275
2.18k
                               Align);
276
2.18k
}
277
278
bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection(
279
236
    bool UsesLabelDifference, const Function &F) const {
280
236
  // In PIC mode, we need to emit the jump table to the same section as the
281
236
  // function body itself, otherwise the label differences won't make sense.
282
236
  // FIXME: Need a better predicate for this: what about custom entries?
283
236
  if (UsesLabelDifference)
284
218
    return true;
285
18
286
18
  // We should also do if the section name is NULL or function is declared
287
18
  // in discardable section
288
18
  // FIXME: this isn't the right predicate, should be based on the MCSection
289
18
  // for the function.
290
18
  return F.isWeakForLinker();
291
18
}
292
293
/// Given a mergable constant with the specified size and relocation
294
/// information, return a section that it should be placed in.
295
MCSection *TargetLoweringObjectFile::getSectionForConstant(
296
    const DataLayout &DL, SectionKind Kind, const Constant *C,
297
21
    unsigned &Align) const {
298
21
  if (Kind.isReadOnly() && ReadOnlySection != nullptr)
299
21
    return ReadOnlySection;
300
0
301
0
  return DataSection;
302
0
}
303
304
/// getTTypeGlobalReference - Return an MCExpr to use for a
305
/// reference to the specified global variable from exception
306
/// handling information.
307
const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference(
308
    const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
309
45
    MachineModuleInfo *MMI, MCStreamer &Streamer) const {
310
45
  const MCSymbolRefExpr *Ref =
311
45
      MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
312
45
313
45
  return getTTypeReference(Ref, Encoding, Streamer);
314
45
}
315
316
const MCExpr *TargetLoweringObjectFile::
317
getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding,
318
68
                  MCStreamer &Streamer) const {
319
68
  switch (Encoding & 0x70) {
320
68
  default:
321
0
    report_fatal_error("We do not support this DWARF encoding yet!");
322
68
  case dwarf::DW_EH_PE_absptr:
323
45
    // Do nothing special
324
45
    return Sym;
325
68
  case dwarf::DW_EH_PE_pcrel: {
326
23
    // Emit a label to the streamer for the current position.  This gives us
327
23
    // .-foo addressing.
328
23
    MCSymbol *PCSym = getContext().createTempSymbol();
329
23
    Streamer.EmitLabel(PCSym);
330
23
    const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext());
331
23
    return MCBinaryExpr::createSub(Sym, PC, getContext());
332
68
  }
333
68
  }
334
68
}
335
336
9
const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const {
337
9
  // FIXME: It's not clear what, if any, default this should have - perhaps a
338
9
  // null return could mean 'no location' & we should just do that here.
339
9
  return MCSymbolRefExpr::create(Sym, *Ctx);
340
9
}
341
342
void TargetLoweringObjectFile::getNameWithPrefix(
343
    SmallVectorImpl<char> &OutName, const GlobalValue *GV,
344
3.95k
    const TargetMachine &TM) const {
345
3.95k
  Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false);
346
3.95k
}