Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/Alignment.h
Warning:line 85, column 47
The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'uint64_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DwarfUnit.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Analysis -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ASMParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/BinaryFormat -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitstream -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /include/llvm/CodeGen -I /include/llvm/CodeGen/PBQP -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Coroutines -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData/Coverage -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/CodeView -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/DWARF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/MSF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/PDB -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Demangle -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/JITLink -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/Orc -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenACC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenMP -I /include/llvm/CodeGen/GlobalISel -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IRReader -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/LTO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Linker -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCParser -I /include/llvm/CodeGen/MIRParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Option -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Passes -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Scalar -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/Symbolize -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Target -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Utils -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Vectorize -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/IPO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVM/../include -I /usr/src/gnu/usr.bin/clang/libLLVM/obj -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -D PIC -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -D_RET_PROTECTOR -ret-protector -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp

1//===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===//
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 contains support for constructing a dwarf compile unit.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DwarfUnit.h"
14#include "AddressPool.h"
15#include "DwarfCompileUnit.h"
16#include "DwarfExpression.h"
17#include "llvm/ADT/APFloat.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/iterator_range.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineOperand.h"
24#include "llvm/CodeGen/TargetRegisterInfo.h"
25#include "llvm/CodeGen/TargetSubtargetInfo.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/Metadata.h"
30#include "llvm/MC/MCAsmInfo.h"
31#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCDwarf.h"
33#include "llvm/MC/MCSection.h"
34#include "llvm/MC/MCStreamer.h"
35#include "llvm/MC/MachineLocation.h"
36#include "llvm/Support/Casting.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Target/TargetLoweringObjectFile.h"
39#include <cassert>
40#include <cstdint>
41#include <string>
42#include <utility>
43
44using namespace llvm;
45
46#define DEBUG_TYPE"dwarfdebug" "dwarfdebug"
47
48DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP,
49 DwarfCompileUnit &CU, DIELoc &DIE)
50 : DwarfExpression(AP.getDwarfVersion(), CU), AP(AP), OutDIE(DIE) {}
51
52void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) {
53 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Op);
54}
55
56void DIEDwarfExpression::emitSigned(int64_t Value) {
57 CU.addSInt(getActiveDIE(), dwarf::DW_FORM_sdata, Value);
58}
59
60void DIEDwarfExpression::emitUnsigned(uint64_t Value) {
61 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_udata, Value);
62}
63
64void DIEDwarfExpression::emitData1(uint8_t Value) {
65 CU.addUInt(getActiveDIE(), dwarf::DW_FORM_data1, Value);
66}
67
68void DIEDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
69 CU.addBaseTypeRef(getActiveDIE(), Idx);
70}
71
72void DIEDwarfExpression::enableTemporaryBuffer() {
73 assert(!IsBuffering && "Already buffering?")((void)0);
74 IsBuffering = true;
75}
76
77void DIEDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
78
79unsigned DIEDwarfExpression::getTemporaryBufferSize() {
80 return TmpDIE.ComputeSize(&AP);
81}
82
83void DIEDwarfExpression::commitTemporaryBuffer() { OutDIE.takeValues(TmpDIE); }
84
85bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
86 llvm::Register MachineReg) {
87 return MachineReg == TRI.getFrameRegister(*AP.MF);
88}
89
90DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node,
91 AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU)
92 : DIEUnit(UnitTag), CUNode(Node), Asm(A), DD(DW), DU(DWU),
93 IndexTyDie(nullptr) {}
94
95DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A,
96 DwarfDebug *DW, DwarfFile *DWU,
97 MCDwarfDwoLineTable *SplitLineTable)
98 : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU),
99 SplitLineTable(SplitLineTable) {
100}
101
102DwarfUnit::~DwarfUnit() {
103 for (DIEBlock *B : DIEBlocks)
104 B->~DIEBlock();
105 for (DIELoc *L : DIELocs)
106 L->~DIELoc();
107}
108
109int64_t DwarfUnit::getDefaultLowerBound() const {
110 switch (getLanguage()) {
111 default:
112 break;
113
114 // The languages below have valid values in all DWARF versions.
115 case dwarf::DW_LANG_C:
116 case dwarf::DW_LANG_C89:
117 case dwarf::DW_LANG_C_plus_plus:
118 return 0;
119
120 case dwarf::DW_LANG_Fortran77:
121 case dwarf::DW_LANG_Fortran90:
122 return 1;
123
124 // The languages below have valid values only if the DWARF version >= 3.
125 case dwarf::DW_LANG_C99:
126 case dwarf::DW_LANG_ObjC:
127 case dwarf::DW_LANG_ObjC_plus_plus:
128 if (DD->getDwarfVersion() >= 3)
129 return 0;
130 break;
131
132 case dwarf::DW_LANG_Fortran95:
133 if (DD->getDwarfVersion() >= 3)
134 return 1;
135 break;
136
137 // Starting with DWARF v4, all defined languages have valid values.
138 case dwarf::DW_LANG_D:
139 case dwarf::DW_LANG_Java:
140 case dwarf::DW_LANG_Python:
141 case dwarf::DW_LANG_UPC:
142 if (DD->getDwarfVersion() >= 4)
143 return 0;
144 break;
145
146 case dwarf::DW_LANG_Ada83:
147 case dwarf::DW_LANG_Ada95:
148 case dwarf::DW_LANG_Cobol74:
149 case dwarf::DW_LANG_Cobol85:
150 case dwarf::DW_LANG_Modula2:
151 case dwarf::DW_LANG_Pascal83:
152 case dwarf::DW_LANG_PLI:
153 if (DD->getDwarfVersion() >= 4)
154 return 1;
155 break;
156
157 // The languages below are new in DWARF v5.
158 case dwarf::DW_LANG_BLISS:
159 case dwarf::DW_LANG_C11:
160 case dwarf::DW_LANG_C_plus_plus_03:
161 case dwarf::DW_LANG_C_plus_plus_11:
162 case dwarf::DW_LANG_C_plus_plus_14:
163 case dwarf::DW_LANG_Dylan:
164 case dwarf::DW_LANG_Go:
165 case dwarf::DW_LANG_Haskell:
166 case dwarf::DW_LANG_OCaml:
167 case dwarf::DW_LANG_OpenCL:
168 case dwarf::DW_LANG_RenderScript:
169 case dwarf::DW_LANG_Rust:
170 case dwarf::DW_LANG_Swift:
171 if (DD->getDwarfVersion() >= 5)
172 return 0;
173 break;
174
175 case dwarf::DW_LANG_Fortran03:
176 case dwarf::DW_LANG_Fortran08:
177 case dwarf::DW_LANG_Julia:
178 case dwarf::DW_LANG_Modula3:
179 if (DD->getDwarfVersion() >= 5)
180 return 1;
181 break;
182 }
183
184 return -1;
185}
186
187/// Check whether the DIE for this MDNode can be shared across CUs.
188bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const {
189 // When the MDNode can be part of the type system, the DIE can be shared
190 // across CUs.
191 // Combining type units and cross-CU DIE sharing is lower value (since
192 // cross-CU DIE sharing is used in LTO and removes type redundancy at that
193 // level already) but may be implementable for some value in projects
194 // building multiple independent libraries with LTO and then linking those
195 // together.
196 if (isDwoUnit() && !DD->shareAcrossDWOCUs())
197 return false;
198 return (isa<DIType>(D) ||
199 (isa<DISubprogram>(D) && !cast<DISubprogram>(D)->isDefinition())) &&
200 !DD->generateTypeUnits();
201}
202
203DIE *DwarfUnit::getDIE(const DINode *D) const {
204 if (isShareableAcrossCUs(D))
205 return DU->getDIE(D);
206 return MDNodeToDieMap.lookup(D);
207}
208
209void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) {
210 if (isShareableAcrossCUs(Desc)) {
211 DU->insertDIE(Desc, D);
212 return;
213 }
214 MDNodeToDieMap.insert(std::make_pair(Desc, D));
215}
216
217void DwarfUnit::insertDIE(DIE *D) {
218 MDNodeToDieMap.insert(std::make_pair(nullptr, D));
219}
220
221void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) {
222 if (DD->getDwarfVersion() >= 4)
223 addAttribute(Die, Attribute, dwarf::DW_FORM_flag_present, DIEInteger(1));
224 else
225 addAttribute(Die, Attribute, dwarf::DW_FORM_flag, DIEInteger(1));
226}
227
228void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute,
229 Optional<dwarf::Form> Form, uint64_t Integer) {
230 if (!Form)
231 Form = DIEInteger::BestForm(false, Integer);
232 assert(Form != dwarf::DW_FORM_implicit_const &&((void)0)
233 "DW_FORM_implicit_const is used only for signed integers")((void)0);
234 addAttribute(Die, Attribute, *Form, DIEInteger(Integer));
235}
236
237void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form,
238 uint64_t Integer) {
239 addUInt(Block, (dwarf::Attribute)0, Form, Integer);
240}
241
242void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute,
243 Optional<dwarf::Form> Form, int64_t Integer) {
244 if (!Form)
245 Form = DIEInteger::BestForm(true, Integer);
246 addAttribute(Die, Attribute, *Form, DIEInteger(Integer));
247}
248
249void DwarfUnit::addSInt(DIELoc &Die, Optional<dwarf::Form> Form,
250 int64_t Integer) {
251 addSInt(Die, (dwarf::Attribute)0, Form, Integer);
252}
253
254void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute,
255 StringRef String) {
256 if (CUNode->isDebugDirectivesOnly())
257 return;
258
259 if (DD->useInlineStrings()) {
260 addAttribute(Die, Attribute, dwarf::DW_FORM_string,
261 new (DIEValueAllocator)
262 DIEInlineString(String, DIEValueAllocator));
263 return;
264 }
265 dwarf::Form IxForm =
266 isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp;
267
268 auto StringPoolEntry =
269 useSegmentedStringOffsetsTable() || IxForm == dwarf::DW_FORM_GNU_str_index
270 ? DU->getStringPool().getIndexedEntry(*Asm, String)
271 : DU->getStringPool().getEntry(*Asm, String);
272
273 // For DWARF v5 and beyond, use the smallest strx? form possible.
274 if (useSegmentedStringOffsetsTable()) {
275 IxForm = dwarf::DW_FORM_strx1;
276 unsigned Index = StringPoolEntry.getIndex();
277 if (Index > 0xffffff)
278 IxForm = dwarf::DW_FORM_strx4;
279 else if (Index > 0xffff)
280 IxForm = dwarf::DW_FORM_strx3;
281 else if (Index > 0xff)
282 IxForm = dwarf::DW_FORM_strx2;
283 }
284 addAttribute(Die, Attribute, IxForm, DIEString(StringPoolEntry));
285}
286
287void DwarfUnit::addLabel(DIEValueList &Die, dwarf::Attribute Attribute,
288 dwarf::Form Form, const MCSymbol *Label) {
289 addAttribute(Die, Attribute, Form, DIELabel(Label));
290}
291
292void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) {
293 addLabel(Die, (dwarf::Attribute)0, Form, Label);
294}
295
296void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute,
297 uint64_t Integer) {
298 addUInt(Die, Attribute, DD->getDwarfSectionOffsetForm(), Integer);
299}
300
301unsigned DwarfTypeUnit::getOrCreateSourceID(const DIFile *File) {
302 if (!SplitLineTable)
303 return getCU().getOrCreateSourceID(File);
304 if (!UsedLineTable) {
305 UsedLineTable = true;
306 // This is a split type unit that needs a line table.
307 addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0);
308 }
309 return SplitLineTable->getFile(
310 File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
311 Asm->OutContext.getDwarfVersion(), File->getSource());
312}
313
314void DwarfUnit::addPoolOpAddress(DIEValueList &Die, const MCSymbol *Label) {
315 bool UseAddrOffsetFormOrExpressions =
316 DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
317
318 const MCSymbol *Base = nullptr;
319 if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
320 Base = DD->getSectionLabel(&Label->getSection());
321
322 uint32_t Index = DD->getAddressPool().getIndex(Base ? Base : Label);
323
324 if (DD->getDwarfVersion() >= 5) {
325 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addrx);
326 addUInt(Die, dwarf::DW_FORM_addrx, Index);
327 } else {
328 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index);
329 addUInt(Die, dwarf::DW_FORM_GNU_addr_index, Index);
330 }
331
332 if (Base && Base != Label) {
333 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_const4u);
334 addLabelDelta(Die, (dwarf::Attribute)0, Label, Base);
335 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
336 }
337}
338
339void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) {
340 if (DD->getDwarfVersion() >= 5) {
341 addPoolOpAddress(Die, Sym);
342 return;
343 }
344
345 if (DD->useSplitDwarf()) {
346 addPoolOpAddress(Die, Sym);
347 return;
348 }
349
350 addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
351 addLabel(Die, dwarf::DW_FORM_addr, Sym);
352}
353
354void DwarfUnit::addLabelDelta(DIEValueList &Die, dwarf::Attribute Attribute,
355 const MCSymbol *Hi, const MCSymbol *Lo) {
356 addAttribute(Die, Attribute, dwarf::DW_FORM_data4,
357 new (DIEValueAllocator) DIEDelta(Hi, Lo));
358}
359
360void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) {
361 addDIEEntry(Die, Attribute, DIEEntry(Entry));
362}
363
364void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) {
365 // Flag the type unit reference as a declaration so that if it contains
366 // members (implicit special members, static data member definitions, member
367 // declarations for definitions in this CU, etc) consumers don't get confused
368 // and think this is a full definition.
369 addFlag(Die, dwarf::DW_AT_declaration);
370
371 addAttribute(Die, dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8,
372 DIEInteger(Signature));
373}
374
375void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute,
376 DIEEntry Entry) {
377 const DIEUnit *CU = Die.getUnit();
378 const DIEUnit *EntryCU = Entry.getEntry().getUnit();
379 if (!CU)
380 // We assume that Die belongs to this CU, if it is not linked to any CU yet.
381 CU = getUnitDie().getUnit();
382 if (!EntryCU)
383 EntryCU = getUnitDie().getUnit();
384 addAttribute(Die, Attribute,
385 EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
386 Entry);
387}
388
389DIE &DwarfUnit::createAndAddDIE(dwarf::Tag Tag, DIE &Parent, const DINode *N) {
390 DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, Tag));
2
Calling 'DIE::get'
391 if (N)
392 insertDIE(N, &Die);
393 return Die;
394}
395
396void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) {
397 Loc->ComputeSize(Asm);
398 DIELocs.push_back(Loc); // Memoize so we can call the destructor later on.
399 addAttribute(Die, Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc);
400}
401
402void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form,
403 DIEBlock *Block) {
404 Block->ComputeSize(Asm);
405 DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
406 addAttribute(Die, Attribute, Form, Block);
407}
408
409void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute,
410 DIEBlock *Block) {
411 addBlock(Die, Attribute, Block->BestForm(), Block);
412}
413
414void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, const DIFile *File) {
415 if (Line == 0)
416 return;
417
418 unsigned FileID = getOrCreateSourceID(File);
419 addUInt(Die, dwarf::DW_AT_decl_file, None, FileID);
420 addUInt(Die, dwarf::DW_AT_decl_line, None, Line);
421}
422
423void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) {
424 assert(V)((void)0);
425
426 addSourceLine(Die, V->getLine(), V->getFile());
427}
428
429void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) {
430 assert(G)((void)0);
431
432 addSourceLine(Die, G->getLine(), G->getFile());
433}
434
435void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) {
436 assert(SP)((void)0);
437
438 addSourceLine(Die, SP->getLine(), SP->getFile());
439}
440
441void DwarfUnit::addSourceLine(DIE &Die, const DILabel *L) {
442 assert(L)((void)0);
443
444 addSourceLine(Die, L->getLine(), L->getFile());
445}
446
447void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) {
448 assert(Ty)((void)0);
449
450 addSourceLine(Die, Ty->getLine(), Ty->getFile());
451}
452
453void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) {
454 assert(Ty)((void)0);
455
456 addSourceLine(Die, Ty->getLine(), Ty->getFile());
457}
458
459void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) {
460 // Pass this down to addConstantValue as an unsigned bag of bits.
461 addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true);
462}
463
464void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI,
465 const DIType *Ty) {
466 addConstantValue(Die, CI->getValue(), Ty);
467}
468
469void DwarfUnit::addConstantValue(DIE &Die, uint64_t Val, const DIType *Ty) {
470 addConstantValue(Die, DD->isUnsignedDIType(Ty), Val);
471}
472
473void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) {
474 // FIXME: This is a bit conservative/simple - it emits negative values always
475 // sign extended to 64 bits rather than minimizing the number of bytes.
476 addUInt(Die, dwarf::DW_AT_const_value,
477 Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val);
478}
479
480void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) {
481 addConstantValue(Die, Val, DD->isUnsignedDIType(Ty));
482}
483
484void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) {
485 unsigned CIBitWidth = Val.getBitWidth();
486 if (CIBitWidth <= 64) {
487 addConstantValue(Die, Unsigned,
488 Unsigned ? Val.getZExtValue() : Val.getSExtValue());
489 return;
490 }
491
492 DIEBlock *Block = new (DIEValueAllocator) DIEBlock;
493
494 // Get the raw data form of the large APInt.
495 const uint64_t *Ptr64 = Val.getRawData();
496
497 int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte.
498 bool LittleEndian = Asm->getDataLayout().isLittleEndian();
499
500 // Output the constant to DWARF one byte at a time.
501 for (int i = 0; i < NumBytes; i++) {
502 uint8_t c;
503 if (LittleEndian)
504 c = Ptr64[i / 8] >> (8 * (i & 7));
505 else
506 c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7));
507 addUInt(*Block, dwarf::DW_FORM_data1, c);
508 }
509
510 addBlock(Die, dwarf::DW_AT_const_value, Block);
511}
512
513void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) {
514 if (!LinkageName.empty())
515 addString(Die,
516 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
517 : dwarf::DW_AT_MIPS_linkage_name,
518 GlobalValue::dropLLVMManglingEscape(LinkageName));
519}
520
521void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) {
522 // Add template parameters.
523 for (const auto *Element : TParams) {
524 if (auto *TTP = dyn_cast<DITemplateTypeParameter>(Element))
525 constructTemplateTypeParameterDIE(Buffer, TTP);
526 else if (auto *TVP = dyn_cast<DITemplateValueParameter>(Element))
527 constructTemplateValueParameterDIE(Buffer, TVP);
528 }
529}
530
531/// Add thrown types.
532void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) {
533 for (const auto *Ty : ThrownTypes) {
534 DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die);
1
Calling 'DwarfUnit::createAndAddDIE'
535 addType(TT, cast<DIType>(Ty));
536 }
537}
538
539DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) {
540 if (!Context || isa<DIFile>(Context))
541 return &getUnitDie();
542 if (auto *T = dyn_cast<DIType>(Context))
543 return getOrCreateTypeDIE(T);
544 if (auto *NS = dyn_cast<DINamespace>(Context))
545 return getOrCreateNameSpace(NS);
546 if (auto *SP = dyn_cast<DISubprogram>(Context))
547 return getOrCreateSubprogramDIE(SP);
548 if (auto *M = dyn_cast<DIModule>(Context))
549 return getOrCreateModule(M);
550 return getDIE(Context);
551}
552
553DIE *DwarfUnit::createTypeDIE(const DICompositeType *Ty) {
554 auto *Context = Ty->getScope();
555 DIE *ContextDIE = getOrCreateContextDIE(Context);
556
557 if (DIE *TyDIE = getDIE(Ty))
558 return TyDIE;
559
560 // Create new type.
561 DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty);
562
563 constructTypeDIE(TyDIE, cast<DICompositeType>(Ty));
564
565 updateAcceleratorTables(Context, Ty, TyDIE);
566 return &TyDIE;
567}
568
569DIE *DwarfUnit::createTypeDIE(const DIScope *Context, DIE &ContextDIE,
570 const DIType *Ty) {
571 // Create new type.
572 DIE &TyDIE = createAndAddDIE(Ty->getTag(), ContextDIE, Ty);
573
574 updateAcceleratorTables(Context, Ty, TyDIE);
575
576 if (auto *BT = dyn_cast<DIBasicType>(Ty))
577 constructTypeDIE(TyDIE, BT);
578 else if (auto *ST = dyn_cast<DIStringType>(Ty))
579 constructTypeDIE(TyDIE, ST);
580 else if (auto *STy = dyn_cast<DISubroutineType>(Ty))
581 constructTypeDIE(TyDIE, STy);
582 else if (auto *CTy = dyn_cast<DICompositeType>(Ty)) {
583 if (DD->generateTypeUnits() && !Ty->isForwardDecl() &&
584 (Ty->getRawName() || CTy->getRawIdentifier())) {
585 // Skip updating the accelerator tables since this is not the full type.
586 if (MDString *TypeId = CTy->getRawIdentifier())
587 DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy);
588 else {
589 auto X = DD->enterNonTypeUnitContext();
590 finishNonUnitTypeDIE(TyDIE, CTy);
591 }
592 return &TyDIE;
593 }
594 constructTypeDIE(TyDIE, CTy);
595 } else {
596 constructTypeDIE(TyDIE, cast<DIDerivedType>(Ty));
597 }
598
599 return &TyDIE;
600}
601
602DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) {
603 if (!TyNode)
604 return nullptr;
605
606 auto *Ty = cast<DIType>(TyNode);
607
608 // DW_TAG_restrict_type is not supported in DWARF2
609 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2)
610 return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType());
611
612 // DW_TAG_atomic_type is not supported in DWARF < 5
613 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5)
614 return getOrCreateTypeDIE(cast<DIDerivedType>(Ty)->getBaseType());
615
616 // Construct the context before querying for the existence of the DIE in case
617 // such construction creates the DIE.
618 auto *Context = Ty->getScope();
619 DIE *ContextDIE = getOrCreateContextDIE(Context);
620 assert(ContextDIE)((void)0);
621
622 if (DIE *TyDIE = getDIE(Ty))
623 return TyDIE;
624
625 return static_cast<DwarfUnit *>(ContextDIE->getUnit())
626 ->createTypeDIE(Context, *ContextDIE, Ty);
627}
628
629void DwarfUnit::updateAcceleratorTables(const DIScope *Context,
630 const DIType *Ty, const DIE &TyDIE) {
631 if (!Ty->getName().empty() && !Ty->isForwardDecl()) {
632 bool IsImplementation = false;
633 if (auto *CT = dyn_cast<DICompositeType>(Ty)) {
634 // A runtime language of 0 actually means C/C++ and that any
635 // non-negative value is some version of Objective-C/C++.
636 IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete();
637 }
638 unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0;
639 DD->addAccelType(*CUNode, Ty->getName(), TyDIE, Flags);
640
641 if (!Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
642 isa<DINamespace>(Context) || isa<DICommonBlock>(Context))
643 addGlobalType(Ty, TyDIE, Context);
644 }
645}
646
647void DwarfUnit::addType(DIE &Entity, const DIType *Ty,
648 dwarf::Attribute Attribute) {
649 assert(Ty && "Trying to add a type that doesn't exist?")((void)0);
650 addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty)));
651}
652
653std::string DwarfUnit::getParentContextString(const DIScope *Context) const {
654 if (!Context)
655 return "";
656
657 // FIXME: Decide whether to implement this for non-C++ languages.
658 if (!dwarf::isCPlusPlus((dwarf::SourceLanguage)getLanguage()))
659 return "";
660
661 std::string CS;
662 SmallVector<const DIScope *, 1> Parents;
663 while (!isa<DICompileUnit>(Context)) {
664 Parents.push_back(Context);
665 if (const DIScope *S = Context->getScope())
666 Context = S;
667 else
668 // Structure, etc types will have a NULL context if they're at the top
669 // level.
670 break;
671 }
672
673 // Reverse iterate over our list to go from the outermost construct to the
674 // innermost.
675 for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) {
676 StringRef Name = Ctx->getName();
677 if (Name.empty() && isa<DINamespace>(Ctx))
678 Name = "(anonymous namespace)";
679 if (!Name.empty()) {
680 CS += Name;
681 CS += "::";
682 }
683 }
684 return CS;
685}
686
687void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) {
688 // Get core information.
689 StringRef Name = BTy->getName();
690 // Add name if not anonymous or intermediate type.
691 if (!Name.empty())
692 addString(Buffer, dwarf::DW_AT_name, Name);
693
694 // An unspecified type only has a name attribute.
695 if (BTy->getTag() == dwarf::DW_TAG_unspecified_type)
696 return;
697
698 if (BTy->getTag() != dwarf::DW_TAG_string_type)
699 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
700 BTy->getEncoding());
701
702 uint64_t Size = BTy->getSizeInBits() >> 3;
703 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
704
705 if (BTy->isBigEndian())
706 addUInt(Buffer, dwarf::DW_AT_endianity, None, dwarf::DW_END_big);
707 else if (BTy->isLittleEndian())
708 addUInt(Buffer, dwarf::DW_AT_endianity, None, dwarf::DW_END_little);
709}
710
711void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIStringType *STy) {
712 // Get core information.
713 StringRef Name = STy->getName();
714 // Add name if not anonymous or intermediate type.
715 if (!Name.empty())
716 addString(Buffer, dwarf::DW_AT_name, Name);
717
718 if (DIVariable *Var = STy->getStringLength()) {
719 if (auto *VarDIE = getDIE(Var))
720 addDIEEntry(Buffer, dwarf::DW_AT_string_length, *VarDIE);
721 } else if (DIExpression *Expr = STy->getStringLengthExp()) {
722 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
723 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
724 // This is to describe the memory location of the
725 // length of a Fortran deferred length string, so
726 // lock it down as such.
727 DwarfExpr.setMemoryLocationKind();
728 DwarfExpr.addExpression(Expr);
729 addBlock(Buffer, dwarf::DW_AT_string_length, DwarfExpr.finalize());
730 } else {
731 uint64_t Size = STy->getSizeInBits() >> 3;
732 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
733 }
734
735 if (STy->getEncoding()) {
736 // For eventual Unicode support.
737 addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
738 STy->getEncoding());
739 }
740}
741
742void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) {
743 // Get core information.
744 StringRef Name = DTy->getName();
745 uint64_t Size = DTy->getSizeInBits() >> 3;
746 uint16_t Tag = Buffer.getTag();
747
748 // Map to main type, void will not have a type.
749 const DIType *FromTy = DTy->getBaseType();
750 if (FromTy)
751 addType(Buffer, FromTy);
752
753 // Add name if not anonymous or intermediate type.
754 if (!Name.empty())
755 addString(Buffer, dwarf::DW_AT_name, Name);
756
757 // If alignment is specified for a typedef , create and insert DW_AT_alignment
758 // attribute in DW_TAG_typedef DIE.
759 if (Tag == dwarf::DW_TAG_typedef && DD->getDwarfVersion() >= 5) {
760 uint32_t AlignInBytes = DTy->getAlignInBytes();
761 if (AlignInBytes > 0)
762 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
763 AlignInBytes);
764 }
765
766 // Add size if non-zero (derived types might be zero-sized.)
767 if (Size && Tag != dwarf::DW_TAG_pointer_type
768 && Tag != dwarf::DW_TAG_ptr_to_member_type
769 && Tag != dwarf::DW_TAG_reference_type
770 && Tag != dwarf::DW_TAG_rvalue_reference_type)
771 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
772
773 if (Tag == dwarf::DW_TAG_ptr_to_member_type)
774 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
775 *getOrCreateTypeDIE(cast<DIDerivedType>(DTy)->getClassType()));
776 // Add source line info if available and TyDesc is not a forward declaration.
777 if (!DTy->isForwardDecl())
778 addSourceLine(Buffer, DTy);
779
780 // If DWARF address space value is other than None, add it. The IR
781 // verifier checks that DWARF address space only exists for pointer
782 // or reference types.
783 if (DTy->getDWARFAddressSpace())
784 addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4,
785 DTy->getDWARFAddressSpace().getValue());
786}
787
788void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) {
789 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
790 const DIType *Ty = Args[i];
791 if (!Ty) {
792 assert(i == N-1 && "Unspecified parameter must be the last argument")((void)0);
793 createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer);
794 } else {
795 DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer);
796 addType(Arg, Ty);
797 if (Ty->isArtificial())
798 addFlag(Arg, dwarf::DW_AT_artificial);
799 }
800 }
801}
802
803void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) {
804 // Add return type. A void return won't have a type.
805 auto Elements = cast<DISubroutineType>(CTy)->getTypeArray();
806 if (Elements.size())
807 if (auto RTy = Elements[0])
808 addType(Buffer, RTy);
809
810 bool isPrototyped = true;
811 if (Elements.size() == 2 && !Elements[1])
812 isPrototyped = false;
813
814 constructSubprogramArguments(Buffer, Elements);
815
816 // Add prototype flag if we're dealing with a C language and the function has
817 // been prototyped.
818 uint16_t Language = getLanguage();
819 if (isPrototyped &&
820 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
821 Language == dwarf::DW_LANG_ObjC))
822 addFlag(Buffer, dwarf::DW_AT_prototyped);
823
824 // Add a DW_AT_calling_convention if this has an explicit convention.
825 if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal)
826 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
827 CTy->getCC());
828
829 if (CTy->isLValueReference())
830 addFlag(Buffer, dwarf::DW_AT_reference);
831
832 if (CTy->isRValueReference())
833 addFlag(Buffer, dwarf::DW_AT_rvalue_reference);
834}
835
836void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
837 // Add name if not anonymous or intermediate type.
838 StringRef Name = CTy->getName();
839
840 uint64_t Size = CTy->getSizeInBits() >> 3;
841 uint16_t Tag = Buffer.getTag();
842
843 switch (Tag) {
844 case dwarf::DW_TAG_array_type:
845 constructArrayTypeDIE(Buffer, CTy);
846 break;
847 case dwarf::DW_TAG_enumeration_type:
848 constructEnumTypeDIE(Buffer, CTy);
849 break;
850 case dwarf::DW_TAG_variant_part:
851 case dwarf::DW_TAG_structure_type:
852 case dwarf::DW_TAG_union_type:
853 case dwarf::DW_TAG_class_type: {
854 // Emit the discriminator for a variant part.
855 DIDerivedType *Discriminator = nullptr;
856 if (Tag == dwarf::DW_TAG_variant_part) {
857 Discriminator = CTy->getDiscriminator();
858 if (Discriminator) {
859 // DWARF says:
860 // If the variant part has a discriminant, the discriminant is
861 // represented by a separate debugging information entry which is
862 // a child of the variant part entry.
863 DIE &DiscMember = constructMemberDIE(Buffer, Discriminator);
864 addDIEEntry(Buffer, dwarf::DW_AT_discr, DiscMember);
865 }
866 }
867
868 // Add template parameters to a class, structure or union types.
869 if (Tag == dwarf::DW_TAG_class_type ||
870 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type)
871 addTemplateParams(Buffer, CTy->getTemplateParams());
872
873 // Add elements to structure type.
874 DINodeArray Elements = CTy->getElements();
875 for (const auto *Element : Elements) {
876 if (!Element)
877 continue;
878 if (auto *SP = dyn_cast<DISubprogram>(Element))
879 getOrCreateSubprogramDIE(SP);
880 else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
881 if (DDTy->getTag() == dwarf::DW_TAG_friend) {
882 DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer);
883 addType(ElemDie, DDTy->getBaseType(), dwarf::DW_AT_friend);
884 } else if (DDTy->isStaticMember()) {
885 getOrCreateStaticMemberDIE(DDTy);
886 } else if (Tag == dwarf::DW_TAG_variant_part) {
887 // When emitting a variant part, wrap each member in
888 // DW_TAG_variant.
889 DIE &Variant = createAndAddDIE(dwarf::DW_TAG_variant, Buffer);
890 if (const ConstantInt *CI =
891 dyn_cast_or_null<ConstantInt>(DDTy->getDiscriminantValue())) {
892 if (DD->isUnsignedDIType(Discriminator->getBaseType()))
893 addUInt(Variant, dwarf::DW_AT_discr_value, None, CI->getZExtValue());
894 else
895 addSInt(Variant, dwarf::DW_AT_discr_value, None, CI->getSExtValue());
896 }
897 constructMemberDIE(Variant, DDTy);
898 } else {
899 constructMemberDIE(Buffer, DDTy);
900 }
901 } else if (auto *Property = dyn_cast<DIObjCProperty>(Element)) {
902 DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer);
903 StringRef PropertyName = Property->getName();
904 addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
905 if (Property->getType())
906 addType(ElemDie, Property->getType());
907 addSourceLine(ElemDie, Property);
908 StringRef GetterName = Property->getGetterName();
909 if (!GetterName.empty())
910 addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
911 StringRef SetterName = Property->getSetterName();
912 if (!SetterName.empty())
913 addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
914 if (unsigned PropertyAttributes = Property->getAttributes())
915 addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None,
916 PropertyAttributes);
917 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
918 if (Composite->getTag() == dwarf::DW_TAG_variant_part) {
919 DIE &VariantPart = createAndAddDIE(Composite->getTag(), Buffer);
920 constructTypeDIE(VariantPart, Composite);
921 }
922 }
923 }
924
925 if (CTy->isAppleBlockExtension())
926 addFlag(Buffer, dwarf::DW_AT_APPLE_block);
927
928 if (CTy->getExportSymbols())
929 addFlag(Buffer, dwarf::DW_AT_export_symbols);
930
931 // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type
932 // inside C++ composite types to point to the base class with the vtable.
933 // Rust uses DW_AT_containing_type to link a vtable to the type
934 // for which it was created.
935 if (auto *ContainingType = CTy->getVTableHolder())
936 addDIEEntry(Buffer, dwarf::DW_AT_containing_type,
937 *getOrCreateTypeDIE(ContainingType));
938
939 if (CTy->isObjcClassComplete())
940 addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type);
941
942 // Add the type's non-standard calling convention.
943 // DW_CC_pass_by_value/DW_CC_pass_by_reference are introduced in DWARF 5.
944 if (!Asm->TM.Options.DebugStrictDwarf || DD->getDwarfVersion() >= 5) {
945 uint8_t CC = 0;
946 if (CTy->isTypePassByValue())
947 CC = dwarf::DW_CC_pass_by_value;
948 else if (CTy->isTypePassByReference())
949 CC = dwarf::DW_CC_pass_by_reference;
950 if (CC)
951 addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1,
952 CC);
953 }
954 break;
955 }
956 default:
957 break;
958 }
959
960 // Add name if not anonymous or intermediate type.
961 if (!Name.empty())
962 addString(Buffer, dwarf::DW_AT_name, Name);
963
964 if (Tag == dwarf::DW_TAG_enumeration_type ||
965 Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type ||
966 Tag == dwarf::DW_TAG_union_type) {
967 // Add size if non-zero (derived types might be zero-sized.)
968 // Ignore the size if it's a non-enum forward decl.
969 // TODO: Do we care about size for enum forward declarations?
970 if (Size &&
971 (!CTy->isForwardDecl() || Tag == dwarf::DW_TAG_enumeration_type))
972 addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size);
973 else if (!CTy->isForwardDecl())
974 // Add zero size if it is not a forward declaration.
975 addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0);
976
977 // If we're a forward decl, say so.
978 if (CTy->isForwardDecl())
979 addFlag(Buffer, dwarf::DW_AT_declaration);
980
981 // Add source line info if available.
982 if (!CTy->isForwardDecl())
983 addSourceLine(Buffer, CTy);
984
985 // No harm in adding the runtime language to the declaration.
986 unsigned RLang = CTy->getRuntimeLang();
987 if (RLang)
988 addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1,
989 RLang);
990
991 // Add align info if available.
992 if (uint32_t AlignInBytes = CTy->getAlignInBytes())
993 addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
994 AlignInBytes);
995 }
996}
997
998void DwarfUnit::constructTemplateTypeParameterDIE(
999 DIE &Buffer, const DITemplateTypeParameter *TP) {
1000 DIE &ParamDIE =
1001 createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer);
1002 // Add the type if it exists, it could be void and therefore no type.
1003 if (TP->getType())
1004 addType(ParamDIE, TP->getType());
1005 if (!TP->getName().empty())
1006 addString(ParamDIE, dwarf::DW_AT_name, TP->getName());
1007 if (TP->isDefault() && (DD->getDwarfVersion() >= 5))
1008 addFlag(ParamDIE, dwarf::DW_AT_default_value);
1009}
1010
1011void DwarfUnit::constructTemplateValueParameterDIE(
1012 DIE &Buffer, const DITemplateValueParameter *VP) {
1013 DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer);
1014
1015 // Add the type if there is one, template template and template parameter
1016 // packs will not have a type.
1017 if (VP->getTag() == dwarf::DW_TAG_template_value_parameter)
1018 addType(ParamDIE, VP->getType());
1019 if (!VP->getName().empty())
1020 addString(ParamDIE, dwarf::DW_AT_name, VP->getName());
1021 if (VP->isDefault() && (DD->getDwarfVersion() >= 5))
1022 addFlag(ParamDIE, dwarf::DW_AT_default_value);
1023 if (Metadata *Val = VP->getValue()) {
1024 if (ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Val))
1025 addConstantValue(ParamDIE, CI, VP->getType());
1026 else if (GlobalValue *GV = mdconst::dyn_extract<GlobalValue>(Val)) {
1027 // We cannot describe the location of dllimport'd entities: the
1028 // computation of their address requires loads from the IAT.
1029 if (!GV->hasDLLImportStorageClass()) {
1030 // For declaration non-type template parameters (such as global values
1031 // and functions)
1032 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1033 addOpAddress(*Loc, Asm->getSymbol(GV));
1034 // Emit DW_OP_stack_value to use the address as the immediate value of
1035 // the parameter, rather than a pointer to it.
1036 addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
1037 addBlock(ParamDIE, dwarf::DW_AT_location, Loc);
1038 }
1039 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) {
1040 assert(isa<MDString>(Val))((void)0);
1041 addString(ParamDIE, dwarf::DW_AT_GNU_template_name,
1042 cast<MDString>(Val)->getString());
1043 } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
1044 addTemplateParams(ParamDIE, cast<MDTuple>(Val));
1045 }
1046 }
1047}
1048
1049DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) {
1050 // Construct the context before querying for the existence of the DIE in case
1051 // such construction creates the DIE.
1052 DIE *ContextDIE = getOrCreateContextDIE(NS->getScope());
1053
1054 if (DIE *NDie = getDIE(NS))
1055 return NDie;
1056 DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS);
1057
1058 StringRef Name = NS->getName();
1059 if (!Name.empty())
1060 addString(NDie, dwarf::DW_AT_name, NS->getName());
1061 else
1062 Name = "(anonymous namespace)";
1063 DD->addAccelNamespace(*CUNode, Name, NDie);
1064 addGlobalName(Name, NDie, NS->getScope());
1065 if (NS->getExportSymbols())
1066 addFlag(NDie, dwarf::DW_AT_export_symbols);
1067 return &NDie;
1068}
1069
1070DIE *DwarfUnit::getOrCreateModule(const DIModule *M) {
1071 // Construct the context before querying for the existence of the DIE in case
1072 // such construction creates the DIE.
1073 DIE *ContextDIE = getOrCreateContextDIE(M->getScope());
1074
1075 if (DIE *MDie = getDIE(M))
1076 return MDie;
1077 DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M);
1078
1079 if (!M->getName().empty()) {
1080 addString(MDie, dwarf::DW_AT_name, M->getName());
1081 addGlobalName(M->getName(), MDie, M->getScope());
1082 }
1083 if (!M->getConfigurationMacros().empty())
1084 addString(MDie, dwarf::DW_AT_LLVM_config_macros,
1085 M->getConfigurationMacros());
1086 if (!M->getIncludePath().empty())
1087 addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath());
1088 if (!M->getAPINotesFile().empty())
1089 addString(MDie, dwarf::DW_AT_LLVM_apinotes, M->getAPINotesFile());
1090 if (M->getFile())
1091 addUInt(MDie, dwarf::DW_AT_decl_file, None,
1092 getOrCreateSourceID(M->getFile()));
1093 if (M->getLineNo())
1094 addUInt(MDie, dwarf::DW_AT_decl_line, None, M->getLineNo());
1095 if (M->getIsDecl())
1096 addFlag(MDie, dwarf::DW_AT_declaration);
1097
1098 return &MDie;
1099}
1100
1101DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) {
1102 // Construct the context before querying for the existence of the DIE in case
1103 // such construction creates the DIE (as is the case for member function
1104 // declarations).
1105 DIE *ContextDIE =
1106 Minimal ? &getUnitDie() : getOrCreateContextDIE(SP->getScope());
1107
1108 if (DIE *SPDie = getDIE(SP))
1109 return SPDie;
1110
1111 if (auto *SPDecl = SP->getDeclaration()) {
1112 if (!Minimal) {
1113 // Add subprogram definitions to the CU die directly.
1114 ContextDIE = &getUnitDie();
1115 // Build the decl now to ensure it precedes the definition.
1116 getOrCreateSubprogramDIE(SPDecl);
1117 }
1118 }
1119
1120 // DW_TAG_inlined_subroutine may refer to this DIE.
1121 DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP);
1122
1123 // Stop here and fill this in later, depending on whether or not this
1124 // subprogram turns out to have inlined instances or not.
1125 if (SP->isDefinition())
1126 return &SPDie;
1127
1128 static_cast<DwarfUnit *>(SPDie.getUnit())
1129 ->applySubprogramAttributes(SP, SPDie);
1130 return &SPDie;
1131}
1132
1133bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP,
1134 DIE &SPDie, bool Minimal) {
1135 DIE *DeclDie = nullptr;
1136 StringRef DeclLinkageName;
1137 if (auto *SPDecl = SP->getDeclaration()) {
1138 if (!Minimal) {
1139 DITypeRefArray DeclArgs, DefinitionArgs;
1140 DeclArgs = SPDecl->getType()->getTypeArray();
1141 DefinitionArgs = SP->getType()->getTypeArray();
1142
1143 if (DeclArgs.size() && DefinitionArgs.size())
1144 if (DefinitionArgs[0] != NULL__null && DeclArgs[0] != DefinitionArgs[0])
1145 addType(SPDie, DefinitionArgs[0]);
1146
1147 DeclDie = getDIE(SPDecl);
1148 assert(DeclDie && "This DIE should've already been constructed when the "((void)0)
1149 "definition DIE was created in "((void)0)
1150 "getOrCreateSubprogramDIE")((void)0);
1151 // Look at the Decl's linkage name only if we emitted it.
1152 if (DD->useAllLinkageNames())
1153 DeclLinkageName = SPDecl->getLinkageName();
1154 unsigned DeclID = getOrCreateSourceID(SPDecl->getFile());
1155 unsigned DefID = getOrCreateSourceID(SP->getFile());
1156 if (DeclID != DefID)
1157 addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID);
1158
1159 if (SP->getLine() != SPDecl->getLine())
1160 addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine());
1161 }
1162 }
1163
1164 // Add function template parameters.
1165 addTemplateParams(SPDie, SP->getTemplateParams());
1166
1167 // Add the linkage name if we have one and it isn't in the Decl.
1168 StringRef LinkageName = SP->getLinkageName();
1169 assert(((LinkageName.empty() || DeclLinkageName.empty()) ||((void)0)
1170 LinkageName == DeclLinkageName) &&((void)0)
1171 "decl has a linkage name and it is different")((void)0);
1172 if (DeclLinkageName.empty() &&
1173 // Always emit it for abstract subprograms.
1174 (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP)))
1175 addLinkageName(SPDie, LinkageName);
1176
1177 if (!DeclDie)
1178 return false;
1179
1180 // Refer to the function declaration where all the other attributes will be
1181 // found.
1182 addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie);
1183 return true;
1184}
1185
1186void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie,
1187 bool SkipSPAttributes) {
1188 // If -fdebug-info-for-profiling is enabled, need to emit the subprogram
1189 // and its source location.
1190 bool SkipSPSourceLocation = SkipSPAttributes &&
1191 !CUNode->getDebugInfoForProfiling();
1192 if (!SkipSPSourceLocation)
1193 if (applySubprogramDefinitionAttributes(SP, SPDie, SkipSPAttributes))
1194 return;
1195
1196 // Constructors and operators for anonymous aggregates do not have names.
1197 if (!SP->getName().empty())
1198 addString(SPDie, dwarf::DW_AT_name, SP->getName());
1199
1200 if (!SkipSPSourceLocation)
1201 addSourceLine(SPDie, SP);
1202
1203 // Skip the rest of the attributes under -gmlt to save space.
1204 if (SkipSPAttributes)
1205 return;
1206
1207 // Add the prototype if we have a prototype and we have a C like
1208 // language.
1209 uint16_t Language = getLanguage();
1210 if (SP->isPrototyped() &&
1211 (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 ||
1212 Language == dwarf::DW_LANG_ObjC))
1213 addFlag(SPDie, dwarf::DW_AT_prototyped);
1214
1215 if (SP->isObjCDirect())
1216 addFlag(SPDie, dwarf::DW_AT_APPLE_objc_direct);
1217
1218 unsigned CC = 0;
1219 DITypeRefArray Args;
1220 if (const DISubroutineType *SPTy = SP->getType()) {
1221 Args = SPTy->getTypeArray();
1222 CC = SPTy->getCC();
1223 }
1224
1225 // Add a DW_AT_calling_convention if this has an explicit convention.
1226 if (CC && CC != dwarf::DW_CC_normal)
1227 addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC);
1228
1229 // Add a return type. If this is a type like a C/C++ void type we don't add a
1230 // return type.
1231 if (Args.size())
1232 if (auto Ty = Args[0])
1233 addType(SPDie, Ty);
1234
1235 unsigned VK = SP->getVirtuality();
1236 if (VK) {
1237 addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
1238 if (SP->getVirtualIndex() != -1u) {
1239 DIELoc *Block = getDIELoc();
1240 addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1241 addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex());
1242 addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block);
1243 }
1244 ContainingTypeMap.insert(std::make_pair(&SPDie, SP->getContainingType()));
1245 }
1246
1247 if (!SP->isDefinition()) {
1248 addFlag(SPDie, dwarf::DW_AT_declaration);
1249
1250 // Add arguments. Do not add arguments for subprogram definition. They will
1251 // be handled while processing variables.
1252 constructSubprogramArguments(SPDie, Args);
1253 }
1254
1255 addThrownTypes(SPDie, SP->getThrownTypes());
1256
1257 if (SP->isArtificial())
1258 addFlag(SPDie, dwarf::DW_AT_artificial);
1259
1260 if (!SP->isLocalToUnit())
1261 addFlag(SPDie, dwarf::DW_AT_external);
1262
1263 if (DD->useAppleExtensionAttributes()) {
1264 if (SP->isOptimized())
1265 addFlag(SPDie, dwarf::DW_AT_APPLE_optimized);
1266
1267 if (unsigned isa = Asm->getISAEncoding())
1268 addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
1269 }
1270
1271 if (SP->isLValueReference())
1272 addFlag(SPDie, dwarf::DW_AT_reference);
1273
1274 if (SP->isRValueReference())
1275 addFlag(SPDie, dwarf::DW_AT_rvalue_reference);
1276
1277 if (SP->isNoReturn())
1278 addFlag(SPDie, dwarf::DW_AT_noreturn);
1279
1280 if (SP->isProtected())
1281 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1282 dwarf::DW_ACCESS_protected);
1283 else if (SP->isPrivate())
1284 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1285 dwarf::DW_ACCESS_private);
1286 else if (SP->isPublic())
1287 addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1288 dwarf::DW_ACCESS_public);
1289
1290 if (SP->isExplicit())
1291 addFlag(SPDie, dwarf::DW_AT_explicit);
1292
1293 if (SP->isMainSubprogram())
1294 addFlag(SPDie, dwarf::DW_AT_main_subprogram);
1295 if (SP->isPure())
1296 addFlag(SPDie, dwarf::DW_AT_pure);
1297 if (SP->isElemental())
1298 addFlag(SPDie, dwarf::DW_AT_elemental);
1299 if (SP->isRecursive())
1300 addFlag(SPDie, dwarf::DW_AT_recursive);
1301
1302 if (DD->getDwarfVersion() >= 5 && SP->isDeleted())
1303 addFlag(SPDie, dwarf::DW_AT_deleted);
1304}
1305
1306void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR,
1307 DIE *IndexTy) {
1308 DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer);
1309 addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy);
1310
1311 // The LowerBound value defines the lower bounds which is typically zero for
1312 // C/C++. The Count value is the number of elements. Values are 64 bit. If
1313 // Count == -1 then the array is unbounded and we do not emit
1314 // DW_AT_lower_bound and DW_AT_count attributes.
1315 int64_t DefaultLowerBound = getDefaultLowerBound();
1316
1317 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
1318 DISubrange::BoundType Bound) -> void {
1319 if (auto *BV = Bound.dyn_cast<DIVariable *>()) {
1320 if (auto *VarDIE = getDIE(BV))
1321 addDIEEntry(DW_Subrange, Attr, *VarDIE);
1322 } else if (auto *BE = Bound.dyn_cast<DIExpression *>()) {
1323 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1324 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1325 DwarfExpr.setMemoryLocationKind();
1326 DwarfExpr.addExpression(BE);
1327 addBlock(DW_Subrange, Attr, DwarfExpr.finalize());
1328 } else if (auto *BI = Bound.dyn_cast<ConstantInt *>()) {
1329 if (Attr == dwarf::DW_AT_count) {
1330 if (BI->getSExtValue() != -1)
1331 addUInt(DW_Subrange, Attr, None, BI->getSExtValue());
1332 } else if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1333 BI->getSExtValue() != DefaultLowerBound)
1334 addSInt(DW_Subrange, Attr, dwarf::DW_FORM_sdata, BI->getSExtValue());
1335 }
1336 };
1337
1338 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, SR->getLowerBound());
1339
1340 AddBoundTypeEntry(dwarf::DW_AT_count, SR->getCount());
1341
1342 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, SR->getUpperBound());
1343
1344 AddBoundTypeEntry(dwarf::DW_AT_byte_stride, SR->getStride());
1345}
1346
1347void DwarfUnit::constructGenericSubrangeDIE(DIE &Buffer,
1348 const DIGenericSubrange *GSR,
1349 DIE *IndexTy) {
1350 DIE &DwGenericSubrange =
1351 createAndAddDIE(dwarf::DW_TAG_generic_subrange, Buffer);
1352 addDIEEntry(DwGenericSubrange, dwarf::DW_AT_type, *IndexTy);
1353
1354 int64_t DefaultLowerBound = getDefaultLowerBound();
1355
1356 auto AddBoundTypeEntry = [&](dwarf::Attribute Attr,
1357 DIGenericSubrange::BoundType Bound) -> void {
1358 if (auto *BV = Bound.dyn_cast<DIVariable *>()) {
1359 if (auto *VarDIE = getDIE(BV))
1360 addDIEEntry(DwGenericSubrange, Attr, *VarDIE);
1361 } else if (auto *BE = Bound.dyn_cast<DIExpression *>()) {
1362 if (BE->isConstant() &&
1363 DIExpression::SignedOrUnsignedConstant::SignedConstant ==
1364 *BE->isConstant()) {
1365 if (Attr != dwarf::DW_AT_lower_bound || DefaultLowerBound == -1 ||
1366 static_cast<int64_t>(BE->getElement(1)) != DefaultLowerBound)
1367 addSInt(DwGenericSubrange, Attr, dwarf::DW_FORM_sdata,
1368 BE->getElement(1));
1369 } else {
1370 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1371 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1372 DwarfExpr.setMemoryLocationKind();
1373 DwarfExpr.addExpression(BE);
1374 addBlock(DwGenericSubrange, Attr, DwarfExpr.finalize());
1375 }
1376 }
1377 };
1378
1379 AddBoundTypeEntry(dwarf::DW_AT_lower_bound, GSR->getLowerBound());
1380 AddBoundTypeEntry(dwarf::DW_AT_count, GSR->getCount());
1381 AddBoundTypeEntry(dwarf::DW_AT_upper_bound, GSR->getUpperBound());
1382 AddBoundTypeEntry(dwarf::DW_AT_byte_stride, GSR->getStride());
1383}
1384
1385DIE *DwarfUnit::getIndexTyDie() {
1386 if (IndexTyDie)
1387 return IndexTyDie;
1388 // Construct an integer type to use for indexes.
1389 IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie());
1390 StringRef Name = "__ARRAY_SIZE_TYPE__";
1391 addString(*IndexTyDie, dwarf::DW_AT_name, Name);
1392 addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t));
1393 addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1394 dwarf::DW_ATE_unsigned);
1395 DD->addAccelType(*CUNode, Name, *IndexTyDie, /*Flags*/ 0);
1396 return IndexTyDie;
1397}
1398
1399/// Returns true if the vector's size differs from the sum of sizes of elements
1400/// the user specified. This can occur if the vector has been rounded up to
1401/// fit memory alignment constraints.
1402static bool hasVectorBeenPadded(const DICompositeType *CTy) {
1403 assert(CTy && CTy->isVector() && "Composite type is not a vector")((void)0);
1404 const uint64_t ActualSize = CTy->getSizeInBits();
1405
1406 // Obtain the size of each element in the vector.
1407 DIType *BaseTy = CTy->getBaseType();
1408 assert(BaseTy && "Unknown vector element type.")((void)0);
1409 const uint64_t ElementSize = BaseTy->getSizeInBits();
1410
1411 // Locate the number of elements in the vector.
1412 const DINodeArray Elements = CTy->getElements();
1413 assert(Elements.size() == 1 &&((void)0)
1414 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type &&((void)0)
1415 "Invalid vector element array, expected one element of type subrange")((void)0);
1416 const auto Subrange = cast<DISubrange>(Elements[0]);
1417 const auto NumVecElements =
1418 Subrange->getCount()
1419 ? Subrange->getCount().get<ConstantInt *>()->getSExtValue()
1420 : 0;
1421
1422 // Ensure we found the element count and that the actual size is wide
1423 // enough to contain the requested size.
1424 assert(ActualSize >= (NumVecElements * ElementSize) && "Invalid vector size")((void)0);
1425 return ActualSize != (NumVecElements * ElementSize);
1426}
1427
1428void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1429 if (CTy->isVector()) {
1430 addFlag(Buffer, dwarf::DW_AT_GNU_vector);
1431 if (hasVectorBeenPadded(CTy))
1432 addUInt(Buffer, dwarf::DW_AT_byte_size, None,
1433 CTy->getSizeInBits() / CHAR_BIT8);
1434 }
1435
1436 if (DIVariable *Var = CTy->getDataLocation()) {
1437 if (auto *VarDIE = getDIE(Var))
1438 addDIEEntry(Buffer, dwarf::DW_AT_data_location, *VarDIE);
1439 } else if (DIExpression *Expr = CTy->getDataLocationExp()) {
1440 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1441 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1442 DwarfExpr.setMemoryLocationKind();
1443 DwarfExpr.addExpression(Expr);
1444 addBlock(Buffer, dwarf::DW_AT_data_location, DwarfExpr.finalize());
1445 }
1446
1447 if (DIVariable *Var = CTy->getAssociated()) {
1448 if (auto *VarDIE = getDIE(Var))
1449 addDIEEntry(Buffer, dwarf::DW_AT_associated, *VarDIE);
1450 } else if (DIExpression *Expr = CTy->getAssociatedExp()) {
1451 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1452 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1453 DwarfExpr.setMemoryLocationKind();
1454 DwarfExpr.addExpression(Expr);
1455 addBlock(Buffer, dwarf::DW_AT_associated, DwarfExpr.finalize());
1456 }
1457
1458 if (DIVariable *Var = CTy->getAllocated()) {
1459 if (auto *VarDIE = getDIE(Var))
1460 addDIEEntry(Buffer, dwarf::DW_AT_allocated, *VarDIE);
1461 } else if (DIExpression *Expr = CTy->getAllocatedExp()) {
1462 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1463 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1464 DwarfExpr.setMemoryLocationKind();
1465 DwarfExpr.addExpression(Expr);
1466 addBlock(Buffer, dwarf::DW_AT_allocated, DwarfExpr.finalize());
1467 }
1468
1469 if (auto *RankConst = CTy->getRankConst()) {
1470 addSInt(Buffer, dwarf::DW_AT_rank, dwarf::DW_FORM_sdata,
1471 RankConst->getSExtValue());
1472 } else if (auto *RankExpr = CTy->getRankExp()) {
1473 DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1474 DIEDwarfExpression DwarfExpr(*Asm, getCU(), *Loc);
1475 DwarfExpr.setMemoryLocationKind();
1476 DwarfExpr.addExpression(RankExpr);
1477 addBlock(Buffer, dwarf::DW_AT_rank, DwarfExpr.finalize());
1478 }
1479
1480 // Emit the element type.
1481 addType(Buffer, CTy->getBaseType());
1482
1483 // Get an anonymous type for index type.
1484 // FIXME: This type should be passed down from the front end
1485 // as different languages may have different sizes for indexes.
1486 DIE *IdxTy = getIndexTyDie();
1487
1488 // Add subranges to array type.
1489 DINodeArray Elements = CTy->getElements();
1490 for (DINode *E : Elements) {
1491 // FIXME: Should this really be such a loose cast?
1492 if (auto *Element = dyn_cast_or_null<DINode>(E)) {
1493 if (Element->getTag() == dwarf::DW_TAG_subrange_type)
1494 constructSubrangeDIE(Buffer, cast<DISubrange>(Element), IdxTy);
1495 else if (Element->getTag() == dwarf::DW_TAG_generic_subrange)
1496 constructGenericSubrangeDIE(Buffer, cast<DIGenericSubrange>(Element),
1497 IdxTy);
1498 }
1499 }
1500}
1501
1502void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) {
1503 const DIType *DTy = CTy->getBaseType();
1504 bool IsUnsigned = DTy && DD->isUnsignedDIType(DTy);
1505 if (DTy) {
1506 if (DD->getDwarfVersion() >= 3)
1507 addType(Buffer, DTy);
1508 if (DD->getDwarfVersion() >= 4 && (CTy->getFlags() & DINode::FlagEnumClass))
1509 addFlag(Buffer, dwarf::DW_AT_enum_class);
1510 }
1511
1512 auto *Context = CTy->getScope();
1513 bool IndexEnumerators = !Context || isa<DICompileUnit>(Context) || isa<DIFile>(Context) ||
1514 isa<DINamespace>(Context) || isa<DICommonBlock>(Context);
1515 DINodeArray Elements = CTy->getElements();
1516
1517 // Add enumerators to enumeration type.
1518 for (const DINode *E : Elements) {
1519 auto *Enum = dyn_cast_or_null<DIEnumerator>(E);
1520 if (Enum) {
1521 DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer);
1522 StringRef Name = Enum->getName();
1523 addString(Enumerator, dwarf::DW_AT_name, Name);
1524 addConstantValue(Enumerator, Enum->getValue(), IsUnsigned);
1525 if (IndexEnumerators)
1526 addGlobalName(Name, Enumerator, Context);
1527 }
1528 }
1529}
1530
1531void DwarfUnit::constructContainingTypeDIEs() {
1532 for (auto &P : ContainingTypeMap) {
1533 DIE &SPDie = *P.first;
1534 const DINode *D = P.second;
1535 if (!D)
1536 continue;
1537 DIE *NDie = getDIE(D);
1538 if (!NDie)
1539 continue;
1540 addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie);
1541 }
1542}
1543
1544DIE &DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) {
1545 DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer);
1546 StringRef Name = DT->getName();
1547 if (!Name.empty())
1548 addString(MemberDie, dwarf::DW_AT_name, Name);
1549
1550 if (DIType *Resolved = DT->getBaseType())
1551 addType(MemberDie, Resolved);
1552
1553 addSourceLine(MemberDie, DT);
1554
1555 if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) {
1556
1557 // For C++, virtual base classes are not at fixed offset. Use following
1558 // expression to extract appropriate offset from vtable.
1559 // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1560
1561 DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc;
1562 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1563 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1564 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1565 addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits());
1566 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1567 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1568 addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1569
1570 addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie);
1571 } else {
1572 uint64_t Size = DT->getSizeInBits();
1573 uint64_t FieldSize = DD->getBaseTypeSize(DT);
1574 uint32_t AlignInBytes = DT->getAlignInBytes();
1575 uint64_t OffsetInBytes;
1576
1577 bool IsBitfield = FieldSize && Size != FieldSize;
1578 if (IsBitfield) {
1579 // Handle bitfield, assume bytes are 8 bits.
1580 if (DD->useDWARF2Bitfields())
1581 addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8);
1582 addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size);
1583
1584 uint64_t Offset = DT->getOffsetInBits();
1585 // We can't use DT->getAlignInBits() here: AlignInBits for member type
1586 // is non-zero if and only if alignment was forced (e.g. _Alignas()),
1587 // which can't be done with bitfields. Thus we use FieldSize here.
1588 uint32_t AlignInBits = FieldSize;
1589 uint32_t AlignMask = ~(AlignInBits - 1);
1590 // The bits from the start of the storage unit to the start of the field.
1591 uint64_t StartBitOffset = Offset - (Offset & AlignMask);
1592 // The byte offset of the field's aligned storage unit inside the struct.
1593 OffsetInBytes = (Offset - StartBitOffset) / 8;
1594
1595 if (DD->useDWARF2Bitfields()) {
1596 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1597 uint64_t FieldOffset = (HiMark - FieldSize);
1598 Offset -= FieldOffset;
1599
1600 // Maybe we need to work from the other end.
1601 if (Asm->getDataLayout().isLittleEndian())
1602 Offset = FieldSize - (Offset + Size);
1603
1604 addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset);
1605 OffsetInBytes = FieldOffset >> 3;
1606 } else {
1607 addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset);
1608 }
1609 } else {
1610 // This is not a bitfield.
1611 OffsetInBytes = DT->getOffsetInBits() / 8;
1612 if (AlignInBytes)
1613 addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1614 AlignInBytes);
1615 }
1616
1617 if (DD->getDwarfVersion() <= 2) {
1618 DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc;
1619 addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1620 addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes);
1621 addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie);
1622 } else if (!IsBitfield || DD->useDWARF2Bitfields()) {
1623 // In DWARF v3, DW_FORM_data4/8 in DW_AT_data_member_location are
1624 // interpreted as location-list pointers. Interpreting constants as
1625 // pointers is not expected, so we use DW_FORM_udata to encode the
1626 // constants here.
1627 if (DD->getDwarfVersion() == 3)
1628 addUInt(MemberDie, dwarf::DW_AT_data_member_location,
1629 dwarf::DW_FORM_udata, OffsetInBytes);
1630 else
1631 addUInt(MemberDie, dwarf::DW_AT_data_member_location, None,
1632 OffsetInBytes);
1633 }
1634 }
1635
1636 if (DT->isProtected())
1637 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1638 dwarf::DW_ACCESS_protected);
1639 else if (DT->isPrivate())
1640 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1641 dwarf::DW_ACCESS_private);
1642 // Otherwise C++ member and base classes are considered public.
1643 else if (DT->isPublic())
1644 addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1645 dwarf::DW_ACCESS_public);
1646 if (DT->isVirtual())
1647 addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
1648 dwarf::DW_VIRTUALITY_virtual);
1649
1650 // Objective-C properties.
1651 if (DINode *PNode = DT->getObjCProperty())
1652 if (DIE *PDie = getDIE(PNode))
1653 addAttribute(MemberDie, dwarf::DW_AT_APPLE_property,
1654 dwarf::DW_FORM_ref4, DIEEntry(*PDie));
1655
1656 if (DT->isArtificial())
1657 addFlag(MemberDie, dwarf::DW_AT_artificial);
1658
1659 return MemberDie;
1660}
1661
1662DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) {
1663 if (!DT)
1664 return nullptr;
1665
1666 // Construct the context before querying for the existence of the DIE in case
1667 // such construction creates the DIE.
1668 DIE *ContextDIE = getOrCreateContextDIE(DT->getScope());
1669 assert(dwarf::isType(ContextDIE->getTag()) &&((void)0)
1670 "Static member should belong to a type.")((void)0);
1671
1672 if (DIE *StaticMemberDIE = getDIE(DT))
1673 return StaticMemberDIE;
1674
1675 DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT);
1676
1677 const DIType *Ty = DT->getBaseType();
1678
1679 addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName());
1680 addType(StaticMemberDIE, Ty);
1681 addSourceLine(StaticMemberDIE, DT);
1682 addFlag(StaticMemberDIE, dwarf::DW_AT_external);
1683 addFlag(StaticMemberDIE, dwarf::DW_AT_declaration);
1684
1685 // FIXME: We could omit private if the parent is a class_type, and
1686 // public if the parent is something else.
1687 if (DT->isProtected())
1688 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1689 dwarf::DW_ACCESS_protected);
1690 else if (DT->isPrivate())
1691 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1692 dwarf::DW_ACCESS_private);
1693 else if (DT->isPublic())
1694 addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
1695 dwarf::DW_ACCESS_public);
1696
1697 if (const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DT->getConstant()))
1698 addConstantValue(StaticMemberDIE, CI, Ty);
1699 if (const ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(DT->getConstant()))
1700 addConstantFPValue(StaticMemberDIE, CFP);
1701
1702 if (uint32_t AlignInBytes = DT->getAlignInBytes())
1703 addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1704 AlignInBytes);
1705
1706 return &StaticMemberDIE;
1707}
1708
1709void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) {
1710 // Emit size of content not including length itself
1711 if (!DD->useSectionsAsReferences())
1712 EndLabel = Asm->emitDwarfUnitLength(
1713 isDwoUnit() ? "debug_info_dwo" : "debug_info", "Length of Unit");
1714 else
1715 Asm->emitDwarfUnitLength(getHeaderSize() + getUnitDie().getSize(),
1716 "Length of Unit");
1717
1718 Asm->OutStreamer->AddComment("DWARF version number");
1719 unsigned Version = DD->getDwarfVersion();
1720 Asm->emitInt16(Version);
1721
1722 // DWARF v5 reorders the address size and adds a unit type.
1723 if (Version >= 5) {
1724 Asm->OutStreamer->AddComment("DWARF Unit Type");
1725 Asm->emitInt8(UT);
1726 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1727 Asm->emitInt8(Asm->MAI->getCodePointerSize());
1728 }
1729
1730 // We share one abbreviations table across all units so it's always at the
1731 // start of the section. Use a relocatable offset where needed to ensure
1732 // linking doesn't invalidate that offset.
1733 Asm->OutStreamer->AddComment("Offset Into Abbrev. Section");
1734 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1735 if (UseOffsets)
1736 Asm->emitDwarfLengthOrOffset(0);
1737 else
1738 Asm->emitDwarfSymbolReference(
1739 TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false);
1740
1741 if (Version <= 4) {
1742 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1743 Asm->emitInt8(Asm->MAI->getCodePointerSize());
1744 }
1745}
1746
1747void DwarfTypeUnit::emitHeader(bool UseOffsets) {
1748 DwarfUnit::emitCommonHeader(UseOffsets,
1749 DD->useSplitDwarf() ? dwarf::DW_UT_split_type
1750 : dwarf::DW_UT_type);
1751 Asm->OutStreamer->AddComment("Type Signature");
1752 Asm->OutStreamer->emitIntValue(TypeSignature, sizeof(TypeSignature));
1753 Asm->OutStreamer->AddComment("Type DIE Offset");
1754 // In a skeleton type unit there is no type DIE so emit a zero offset.
1755 Asm->emitDwarfLengthOrOffset(Ty ? Ty->getOffset() : 0);
1756}
1757
1758void DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
1759 const MCSymbol *Hi, const MCSymbol *Lo) {
1760 addAttribute(Die, Attribute, DD->getDwarfSectionOffsetForm(),
1761 new (DIEValueAllocator) DIEDelta(Hi, Lo));
1762}
1763
1764void DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
1765 const MCSymbol *Label, const MCSymbol *Sec) {
1766 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1767 addLabel(Die, Attribute, DD->getDwarfSectionOffsetForm(), Label);
1768 else
1769 addSectionDelta(Die, Attribute, Label, Sec);
1770}
1771
1772bool DwarfTypeUnit::isDwoUnit() const {
1773 // Since there are no skeleton type units, all type units are dwo type units
1774 // when split DWARF is being used.
1775 return DD->useSplitDwarf();
1776}
1777
1778void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die,
1779 const DIScope *Context) {
1780 getCU().addGlobalNameForTypeUnit(Name, Context);
1781}
1782
1783void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1784 const DIScope *Context) {
1785 getCU().addGlobalTypeUnitType(Ty, Context);
1786}
1787
1788const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const {
1789 if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1790 return nullptr;
1791 if (isDwoUnit())
1792 return nullptr;
1793 return getSection()->getBeginSymbol();
1794}
1795
1796void DwarfUnit::addStringOffsetsStart() {
1797 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1798 addSectionLabel(getUnitDie(), dwarf::DW_AT_str_offsets_base,
1799 DU->getStringOffsetsStartSym(),
1800 TLOF.getDwarfStrOffSection()->getBeginSymbol());
1801}
1802
1803void DwarfUnit::addRnglistsBase() {
1804 assert(DD->getDwarfVersion() >= 5 &&((void)0)
1805 "DW_AT_rnglists_base requires DWARF version 5 or later")((void)0);
1806 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1807 addSectionLabel(getUnitDie(), dwarf::DW_AT_rnglists_base,
1808 DU->getRnglistsTableBaseSym(),
1809 TLOF.getDwarfRnglistsSection()->getBeginSymbol());
1810}
1811
1812void DwarfTypeUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1813 addFlag(D, dwarf::DW_AT_declaration);
1814 StringRef Name = CTy->getName();
1815 if (!Name.empty())
1816 addString(D, dwarf::DW_AT_name, Name);
1817 getCU().createTypeDIE(CTy);
1818}

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/CodeGen/DIE.h

1//===- lib/CodeGen/DIE.h - DWARF Info Entries -------------------*- C++ -*-===//
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// Data structures for DWARF info entries.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CODEGEN_DIE_H
14#define LLVM_CODEGEN_DIE_H
15
16#include "llvm/ADT/FoldingSet.h"
17#include "llvm/ADT/PointerIntPair.h"
18#include "llvm/ADT/PointerUnion.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/iterator.h"
22#include "llvm/ADT/iterator_range.h"
23#include "llvm/BinaryFormat/Dwarf.h"
24#include "llvm/CodeGen/DwarfStringPoolEntry.h"
25#include "llvm/Support/AlignOf.h"
26#include "llvm/Support/Allocator.h"
27#include <cassert>
28#include <cstddef>
29#include <cstdint>
30#include <iterator>
31#include <new>
32#include <type_traits>
33#include <utility>
34#include <vector>
35
36namespace llvm {
37
38class AsmPrinter;
39class DIE;
40class DIEUnit;
41class DwarfCompileUnit;
42class MCExpr;
43class MCSection;
44class MCSymbol;
45class raw_ostream;
46
47//===--------------------------------------------------------------------===//
48/// Dwarf abbreviation data, describes one attribute of a Dwarf abbreviation.
49class DIEAbbrevData {
50 /// Dwarf attribute code.
51 dwarf::Attribute Attribute;
52
53 /// Dwarf form code.
54 dwarf::Form Form;
55
56 /// Dwarf attribute value for DW_FORM_implicit_const
57 int64_t Value = 0;
58
59public:
60 DIEAbbrevData(dwarf::Attribute A, dwarf::Form F)
61 : Attribute(A), Form(F) {}
62 DIEAbbrevData(dwarf::Attribute A, int64_t V)
63 : Attribute(A), Form(dwarf::DW_FORM_implicit_const), Value(V) {}
64
65 /// Accessors.
66 /// @{
67 dwarf::Attribute getAttribute() const { return Attribute; }
68 dwarf::Form getForm() const { return Form; }
69 int64_t getValue() const { return Value; }
70 /// @}
71
72 /// Used to gather unique data for the abbreviation folding set.
73 void Profile(FoldingSetNodeID &ID) const;
74};
75
76//===--------------------------------------------------------------------===//
77/// Dwarf abbreviation, describes the organization of a debug information
78/// object.
79class DIEAbbrev : public FoldingSetNode {
80 /// Unique number for node.
81 unsigned Number = 0;
82
83 /// Dwarf tag code.
84 dwarf::Tag Tag;
85
86 /// Whether or not this node has children.
87 ///
88 /// This cheats a bit in all of the uses since the values in the standard
89 /// are 0 and 1 for no children and children respectively.
90 bool Children;
91
92 /// Raw data bytes for abbreviation.
93 SmallVector<DIEAbbrevData, 12> Data;
94
95public:
96 DIEAbbrev(dwarf::Tag T, bool C) : Tag(T), Children(C) {}
97
98 /// Accessors.
99 /// @{
100 dwarf::Tag getTag() const { return Tag; }
101 unsigned getNumber() const { return Number; }
102 bool hasChildren() const { return Children; }
103 const SmallVectorImpl<DIEAbbrevData> &getData() const { return Data; }
104 void setChildrenFlag(bool hasChild) { Children = hasChild; }
105 void setNumber(unsigned N) { Number = N; }
106 /// @}
107
108 /// Adds another set of attribute information to the abbreviation.
109 void AddAttribute(dwarf::Attribute Attribute, dwarf::Form Form) {
110 Data.push_back(DIEAbbrevData(Attribute, Form));
111 }
112
113 /// Adds attribute with DW_FORM_implicit_const value
114 void AddImplicitConstAttribute(dwarf::Attribute Attribute, int64_t Value) {
115 Data.push_back(DIEAbbrevData(Attribute, Value));
116 }
117
118 /// Used to gather unique data for the abbreviation folding set.
119 void Profile(FoldingSetNodeID &ID) const;
120
121 /// Print the abbreviation using the specified asm printer.
122 void Emit(const AsmPrinter *AP) const;
123
124 void print(raw_ostream &O) const;
125 void dump() const;
126};
127
128//===--------------------------------------------------------------------===//
129/// Helps unique DIEAbbrev objects and assigns abbreviation numbers.
130///
131/// This class will unique the DIE abbreviations for a llvm::DIE object and
132/// assign a unique abbreviation number to each unique DIEAbbrev object it
133/// finds. The resulting collection of DIEAbbrev objects can then be emitted
134/// into the .debug_abbrev section.
135class DIEAbbrevSet {
136 /// The bump allocator to use when creating DIEAbbrev objects in the uniqued
137 /// storage container.
138 BumpPtrAllocator &Alloc;
139 /// FoldingSet that uniques the abbreviations.
140 FoldingSet<DIEAbbrev> AbbreviationsSet;
141 /// A list of all the unique abbreviations in use.
142 std::vector<DIEAbbrev *> Abbreviations;
143
144public:
145 DIEAbbrevSet(BumpPtrAllocator &A) : Alloc(A) {}
146 ~DIEAbbrevSet();
147
148 /// Generate the abbreviation declaration for a DIE and return a pointer to
149 /// the generated abbreviation.
150 ///
151 /// \param Die the debug info entry to generate the abbreviation for.
152 /// \returns A reference to the uniqued abbreviation declaration that is
153 /// owned by this class.
154 DIEAbbrev &uniqueAbbreviation(DIE &Die);
155
156 /// Print all abbreviations using the specified asm printer.
157 void Emit(const AsmPrinter *AP, MCSection *Section) const;
158};
159
160//===--------------------------------------------------------------------===//
161/// An integer value DIE.
162///
163class DIEInteger {
164 uint64_t Integer;
165
166public:
167 explicit DIEInteger(uint64_t I) : Integer(I) {}
168
169 /// Choose the best form for integer.
170 static dwarf::Form BestForm(bool IsSigned, uint64_t Int) {
171 if (IsSigned) {
172 const int64_t SignedInt = Int;
173 if ((char)Int == SignedInt)
174 return dwarf::DW_FORM_data1;
175 if ((short)Int == SignedInt)
176 return dwarf::DW_FORM_data2;
177 if ((int)Int == SignedInt)
178 return dwarf::DW_FORM_data4;
179 } else {
180 if ((unsigned char)Int == Int)
181 return dwarf::DW_FORM_data1;
182 if ((unsigned short)Int == Int)
183 return dwarf::DW_FORM_data2;
184 if ((unsigned int)Int == Int)
185 return dwarf::DW_FORM_data4;
186 }
187 return dwarf::DW_FORM_data8;
188 }
189
190 uint64_t getValue() const { return Integer; }
191 void setValue(uint64_t Val) { Integer = Val; }
192
193 void emitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
194 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
195
196 void print(raw_ostream &O) const;
197};
198
199//===--------------------------------------------------------------------===//
200/// An expression DIE.
201class DIEExpr {
202 const MCExpr *Expr;
203
204public:
205 explicit DIEExpr(const MCExpr *E) : Expr(E) {}
206
207 /// Get MCExpr.
208 const MCExpr *getValue() const { return Expr; }
209
210 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
211 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
212
213 void print(raw_ostream &O) const;
214};
215
216//===--------------------------------------------------------------------===//
217/// A label DIE.
218class DIELabel {
219 const MCSymbol *Label;
220
221public:
222 explicit DIELabel(const MCSymbol *L) : Label(L) {}
223
224 /// Get MCSymbol.
225 const MCSymbol *getValue() const { return Label; }
226
227 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
228 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
229
230 void print(raw_ostream &O) const;
231};
232
233//===--------------------------------------------------------------------===//
234/// A BaseTypeRef DIE.
235class DIEBaseTypeRef {
236 const DwarfCompileUnit *CU;
237 const uint64_t Index;
238 static constexpr unsigned ULEB128PadSize = 4;
239
240public:
241 explicit DIEBaseTypeRef(const DwarfCompileUnit *TheCU, uint64_t Idx)
242 : CU(TheCU), Index(Idx) {}
243
244 /// EmitValue - Emit base type reference.
245 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
246 /// SizeOf - Determine size of the base type reference in bytes.
247 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
248
249 void print(raw_ostream &O) const;
250 uint64_t getIndex() const { return Index; }
251};
252
253//===--------------------------------------------------------------------===//
254/// A simple label difference DIE.
255///
256class DIEDelta {
257 const MCSymbol *LabelHi;
258 const MCSymbol *LabelLo;
259
260public:
261 DIEDelta(const MCSymbol *Hi, const MCSymbol *Lo) : LabelHi(Hi), LabelLo(Lo) {}
262
263 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
264 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
265
266 void print(raw_ostream &O) const;
267};
268
269//===--------------------------------------------------------------------===//
270/// A container for string pool string values.
271///
272/// This class is used with the DW_FORM_strp and DW_FORM_GNU_str_index forms.
273class DIEString {
274 DwarfStringPoolEntryRef S;
275
276public:
277 DIEString(DwarfStringPoolEntryRef S) : S(S) {}
278
279 /// Grab the string out of the object.
280 StringRef getString() const { return S.getString(); }
281
282 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
283 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
284
285 void print(raw_ostream &O) const;
286};
287
288//===--------------------------------------------------------------------===//
289/// A container for inline string values.
290///
291/// This class is used with the DW_FORM_string form.
292class DIEInlineString {
293 StringRef S;
294
295public:
296 template <typename Allocator>
297 explicit DIEInlineString(StringRef Str, Allocator &A) : S(Str.copy(A)) {}
298
299 ~DIEInlineString() = default;
300
301 /// Grab the string out of the object.
302 StringRef getString() const { return S; }
303
304 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
305 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
306
307 void print(raw_ostream &O) const;
308};
309
310//===--------------------------------------------------------------------===//
311/// A pointer to another debug information entry. An instance of this class can
312/// also be used as a proxy for a debug information entry not yet defined
313/// (ie. types.)
314class DIEEntry {
315 DIE *Entry;
316
317public:
318 DIEEntry() = delete;
319 explicit DIEEntry(DIE &E) : Entry(&E) {}
320
321 DIE &getEntry() const { return *Entry; }
322
323 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
324 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
325
326 void print(raw_ostream &O) const;
327};
328
329//===--------------------------------------------------------------------===//
330/// Represents a pointer to a location list in the debug_loc
331/// section.
332class DIELocList {
333 /// Index into the .debug_loc vector.
334 size_t Index;
335
336public:
337 DIELocList(size_t I) : Index(I) {}
338
339 /// Grab the current index out.
340 size_t getValue() const { return Index; }
341
342 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
343 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
344
345 void print(raw_ostream &O) const;
346};
347
348//===--------------------------------------------------------------------===//
349/// A BaseTypeRef DIE.
350class DIEAddrOffset {
351 DIEInteger Addr;
352 DIEDelta Offset;
353
354public:
355 explicit DIEAddrOffset(uint64_t Idx, const MCSymbol *Hi, const MCSymbol *Lo)
356 : Addr(Idx), Offset(Hi, Lo) {}
357
358 void emitValue(const AsmPrinter *AP, dwarf::Form Form) const;
359 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
360
361 void print(raw_ostream &O) const;
362};
363
364//===--------------------------------------------------------------------===//
365/// A debug information entry value. Some of these roughly correlate
366/// to DWARF attribute classes.
367class DIEBlock;
368class DIELoc;
369class DIEValue {
370public:
371 enum Type {
372 isNone,
373#define HANDLE_DIEVALUE(T) is##T,
374#include "llvm/CodeGen/DIEValue.def"
375 };
376
377private:
378 /// Type of data stored in the value.
379 Type Ty = isNone;
380 dwarf::Attribute Attribute = (dwarf::Attribute)0;
381 dwarf::Form Form = (dwarf::Form)0;
382
383 /// Storage for the value.
384 ///
385 /// All values that aren't standard layout (or are larger than 8 bytes)
386 /// should be stored by reference instead of by value.
387 using ValTy =
388 AlignedCharArrayUnion<DIEInteger, DIEString, DIEExpr, DIELabel,
389 DIEDelta *, DIEEntry, DIEBlock *, DIELoc *,
390 DIELocList, DIEBaseTypeRef *, DIEAddrOffset *>;
391
392 static_assert(sizeof(ValTy) <= sizeof(uint64_t) ||
393 sizeof(ValTy) <= sizeof(void *),
394 "Expected all large types to be stored via pointer");
395
396 /// Underlying stored value.
397 ValTy Val;
398
399 template <class T> void construct(T V) {
400 static_assert(std::is_standard_layout<T>::value ||
401 std::is_pointer<T>::value,
402 "Expected standard layout or pointer");
403 new (reinterpret_cast<void *>(&Val)) T(V);
404 }
405
406 template <class T> T *get() { return reinterpret_cast<T *>(&Val); }
407 template <class T> const T *get() const {
408 return reinterpret_cast<const T *>(&Val);
409 }
410 template <class T> void destruct() { get<T>()->~T(); }
411
412 /// Destroy the underlying value.
413 ///
414 /// This should get optimized down to a no-op. We could skip it if we could
415 /// add a static assert on \a std::is_trivially_copyable(), but we currently
416 /// support versions of GCC that don't understand that.
417 void destroyVal() {
418 switch (Ty) {
419 case isNone:
420 return;
421#define HANDLE_DIEVALUE_SMALL(T) \
422 case is##T: \
423 destruct<DIE##T>(); \
424 return;
425#define HANDLE_DIEVALUE_LARGE(T) \
426 case is##T: \
427 destruct<const DIE##T *>(); \
428 return;
429#include "llvm/CodeGen/DIEValue.def"
430 }
431 }
432
433 /// Copy the underlying value.
434 ///
435 /// This should get optimized down to a simple copy. We need to actually
436 /// construct the value, rather than calling memcpy, to satisfy strict
437 /// aliasing rules.
438 void copyVal(const DIEValue &X) {
439 switch (Ty) {
440 case isNone:
441 return;
442#define HANDLE_DIEVALUE_SMALL(T) \
443 case is##T: \
444 construct<DIE##T>(*X.get<DIE##T>()); \
445 return;
446#define HANDLE_DIEVALUE_LARGE(T) \
447 case is##T: \
448 construct<const DIE##T *>(*X.get<const DIE##T *>()); \
449 return;
450#include "llvm/CodeGen/DIEValue.def"
451 }
452 }
453
454public:
455 DIEValue() = default;
456
457 DIEValue(const DIEValue &X) : Ty(X.Ty), Attribute(X.Attribute), Form(X.Form) {
458 copyVal(X);
459 }
460
461 DIEValue &operator=(const DIEValue &X) {
462 destroyVal();
463 Ty = X.Ty;
464 Attribute = X.Attribute;
465 Form = X.Form;
466 copyVal(X);
467 return *this;
468 }
469
470 ~DIEValue() { destroyVal(); }
471
472#define HANDLE_DIEVALUE_SMALL(T) \
473 DIEValue(dwarf::Attribute Attribute, dwarf::Form Form, const DIE##T &V) \
474 : Ty(is##T), Attribute(Attribute), Form(Form) { \
475 construct<DIE##T>(V); \
476 }
477#define HANDLE_DIEVALUE_LARGE(T) \
478 DIEValue(dwarf::Attribute Attribute, dwarf::Form Form, const DIE##T *V) \
479 : Ty(is##T), Attribute(Attribute), Form(Form) { \
480 assert(V && "Expected valid value")((void)0); \
481 construct<const DIE##T *>(V); \
482 }
483#include "llvm/CodeGen/DIEValue.def"
484
485 /// Accessors.
486 /// @{
487 Type getType() const { return Ty; }
488 dwarf::Attribute getAttribute() const { return Attribute; }
489 dwarf::Form getForm() const { return Form; }
490 explicit operator bool() const { return Ty; }
491 /// @}
492
493#define HANDLE_DIEVALUE_SMALL(T) \
494 const DIE##T &getDIE##T() const { \
495 assert(getType() == is##T && "Expected " #T)((void)0); \
496 return *get<DIE##T>(); \
497 }
498#define HANDLE_DIEVALUE_LARGE(T) \
499 const DIE##T &getDIE##T() const { \
500 assert(getType() == is##T && "Expected " #T)((void)0); \
501 return **get<const DIE##T *>(); \
502 }
503#include "llvm/CodeGen/DIEValue.def"
504
505 /// Emit value via the Dwarf writer.
506 void emitValue(const AsmPrinter *AP) const;
507
508 /// Return the size of a value in bytes.
509 unsigned SizeOf(const AsmPrinter *AP) const;
510
511 void print(raw_ostream &O) const;
512 void dump() const;
513};
514
515struct IntrusiveBackListNode {
516 PointerIntPair<IntrusiveBackListNode *, 1> Next;
517
518 IntrusiveBackListNode() : Next(this, true) {}
519
520 IntrusiveBackListNode *getNext() const {
521 return Next.getInt() ? nullptr : Next.getPointer();
522 }
523};
524
525struct IntrusiveBackListBase {
526 using Node = IntrusiveBackListNode;
527
528 Node *Last = nullptr;
529
530 bool empty() const { return !Last; }
531
532 void push_back(Node &N) {
533 assert(N.Next.getPointer() == &N && "Expected unlinked node")((void)0);
534 assert(N.Next.getInt() == true && "Expected unlinked node")((void)0);
535
536 if (Last) {
537 N.Next = Last->Next;
538 Last->Next.setPointerAndInt(&N, false);
539 }
540 Last = &N;
541 }
542
543 void push_front(Node &N) {
544 assert(N.Next.getPointer() == &N && "Expected unlinked node")((void)0);
545 assert(N.Next.getInt() == true && "Expected unlinked node")((void)0);
546
547 if (Last) {
548 N.Next.setPointerAndInt(Last->Next.getPointer(), false);
549 Last->Next.setPointerAndInt(&N, true);
550 } else {
551 Last = &N;
552 }
553 }
554};
555
556template <class T> class IntrusiveBackList : IntrusiveBackListBase {
557public:
558 using IntrusiveBackListBase::empty;
559
560 void push_back(T &N) { IntrusiveBackListBase::push_back(N); }
561 void push_front(T &N) { IntrusiveBackListBase::push_front(N); }
562 T &back() { return *static_cast<T *>(Last); }
563 const T &back() const { return *static_cast<T *>(Last); }
564 T &front() {
565 return *static_cast<T *>(Last ? Last->Next.getPointer() : nullptr);
566 }
567 const T &front() const {
568 return *static_cast<T *>(Last ? Last->Next.getPointer() : nullptr);
569 }
570
571 void takeNodes(IntrusiveBackList<T> &Other) {
572 if (Other.empty())
573 return;
574
575 T *FirstNode = static_cast<T *>(Other.Last->Next.getPointer());
576 T *IterNode = FirstNode;
577 do {
578 // Keep a pointer to the node and increment the iterator.
579 T *TmpNode = IterNode;
580 IterNode = static_cast<T *>(IterNode->Next.getPointer());
581
582 // Unlink the node and push it back to this list.
583 TmpNode->Next.setPointerAndInt(TmpNode, true);
584 push_back(*TmpNode);
585 } while (IterNode != FirstNode);
586
587 Other.Last = nullptr;
588 }
589
590 class const_iterator;
591 class iterator
592 : public iterator_facade_base<iterator, std::forward_iterator_tag, T> {
593 friend class const_iterator;
594
595 Node *N = nullptr;
596
597 public:
598 iterator() = default;
599 explicit iterator(T *N) : N(N) {}
600
601 iterator &operator++() {
602 N = N->getNext();
603 return *this;
604 }
605
606 explicit operator bool() const { return N; }
607 T &operator*() const { return *static_cast<T *>(N); }
608
609 bool operator==(const iterator &X) const { return N == X.N; }
610 };
611
612 class const_iterator
613 : public iterator_facade_base<const_iterator, std::forward_iterator_tag,
614 const T> {
615 const Node *N = nullptr;
616
617 public:
618 const_iterator() = default;
619 // Placate MSVC by explicitly scoping 'iterator'.
620 const_iterator(typename IntrusiveBackList<T>::iterator X) : N(X.N) {}
621 explicit const_iterator(const T *N) : N(N) {}
622
623 const_iterator &operator++() {
624 N = N->getNext();
625 return *this;
626 }
627
628 explicit operator bool() const { return N; }
629 const T &operator*() const { return *static_cast<const T *>(N); }
630
631 bool operator==(const const_iterator &X) const { return N == X.N; }
632 };
633
634 iterator begin() {
635 return Last ? iterator(static_cast<T *>(Last->Next.getPointer())) : end();
636 }
637 const_iterator begin() const {
638 return const_cast<IntrusiveBackList *>(this)->begin();
639 }
640 iterator end() { return iterator(); }
641 const_iterator end() const { return const_iterator(); }
642
643 static iterator toIterator(T &N) { return iterator(&N); }
644 static const_iterator toIterator(const T &N) { return const_iterator(&N); }
645};
646
647/// A list of DIE values.
648///
649/// This is a singly-linked list, but instead of reversing the order of
650/// insertion, we keep a pointer to the back of the list so we can push in
651/// order.
652///
653/// There are two main reasons to choose a linked list over a customized
654/// vector-like data structure.
655///
656/// 1. For teardown efficiency, we want DIEs to be BumpPtrAllocated. Using a
657/// linked list here makes this way easier to accomplish.
658/// 2. Carrying an extra pointer per \a DIEValue isn't expensive. 45% of DIEs
659/// have 2 or fewer values, and 90% have 5 or fewer. A vector would be
660/// over-allocated by 50% on average anyway, the same cost as the
661/// linked-list node.
662class DIEValueList {
663 struct Node : IntrusiveBackListNode {
664 DIEValue V;
665
666 explicit Node(DIEValue V) : V(V) {}
667 };
668
669 using ListTy = IntrusiveBackList<Node>;
670
671 ListTy List;
672
673public:
674 class const_value_iterator;
675 class value_iterator
676 : public iterator_adaptor_base<value_iterator, ListTy::iterator,
677 std::forward_iterator_tag, DIEValue> {
678 friend class const_value_iterator;
679
680 using iterator_adaptor =
681 iterator_adaptor_base<value_iterator, ListTy::iterator,
682 std::forward_iterator_tag, DIEValue>;
683
684 public:
685 value_iterator() = default;
686 explicit value_iterator(ListTy::iterator X) : iterator_adaptor(X) {}
687
688 explicit operator bool() const { return bool(wrapped()); }
689 DIEValue &operator*() const { return wrapped()->V; }
690 };
691
692 class const_value_iterator : public iterator_adaptor_base<
693 const_value_iterator, ListTy::const_iterator,
694 std::forward_iterator_tag, const DIEValue> {
695 using iterator_adaptor =
696 iterator_adaptor_base<const_value_iterator, ListTy::const_iterator,
697 std::forward_iterator_tag, const DIEValue>;
698
699 public:
700 const_value_iterator() = default;
701 const_value_iterator(DIEValueList::value_iterator X)
702 : iterator_adaptor(X.wrapped()) {}
703 explicit const_value_iterator(ListTy::const_iterator X)
704 : iterator_adaptor(X) {}
705
706 explicit operator bool() const { return bool(wrapped()); }
707 const DIEValue &operator*() const { return wrapped()->V; }
708 };
709
710 using value_range = iterator_range<value_iterator>;
711 using const_value_range = iterator_range<const_value_iterator>;
712
713 value_iterator addValue(BumpPtrAllocator &Alloc, const DIEValue &V) {
714 List.push_back(*new (Alloc) Node(V));
715 return value_iterator(ListTy::toIterator(List.back()));
716 }
717 template <class T>
718 value_iterator addValue(BumpPtrAllocator &Alloc, dwarf::Attribute Attribute,
719 dwarf::Form Form, T &&Value) {
720 return addValue(Alloc, DIEValue(Attribute, Form, std::forward<T>(Value)));
721 }
722
723 /// Take ownership of the nodes in \p Other, and append them to the back of
724 /// the list.
725 void takeValues(DIEValueList &Other) { List.takeNodes(Other.List); }
726
727 value_range values() {
728 return make_range(value_iterator(List.begin()), value_iterator(List.end()));
729 }
730 const_value_range values() const {
731 return make_range(const_value_iterator(List.begin()),
732 const_value_iterator(List.end()));
733 }
734};
735
736//===--------------------------------------------------------------------===//
737/// A structured debug information entry. Has an abbreviation which
738/// describes its organization.
739class DIE : IntrusiveBackListNode, public DIEValueList {
740 friend class IntrusiveBackList<DIE>;
741 friend class DIEUnit;
742
743 /// Dwarf unit relative offset.
744 unsigned Offset = 0;
745 /// Size of instance + children.
746 unsigned Size = 0;
747 unsigned AbbrevNumber = ~0u;
748 /// Dwarf tag code.
749 dwarf::Tag Tag = (dwarf::Tag)0;
750 /// Set to true to force a DIE to emit an abbreviation that says it has
751 /// children even when it doesn't. This is used for unit testing purposes.
752 bool ForceChildren = false;
753 /// Children DIEs.
754 IntrusiveBackList<DIE> Children;
755
756 /// The owner is either the parent DIE for children of other DIEs, or a
757 /// DIEUnit which contains this DIE as its unit DIE.
758 PointerUnion<DIE *, DIEUnit *> Owner;
759
760 explicit DIE(dwarf::Tag Tag) : Tag(Tag) {}
761
762public:
763 DIE() = delete;
764 DIE(const DIE &RHS) = delete;
765 DIE(DIE &&RHS) = delete;
766 DIE &operator=(const DIE &RHS) = delete;
767 DIE &operator=(const DIE &&RHS) = delete;
768
769 static DIE *get(BumpPtrAllocator &Alloc, dwarf::Tag Tag) {
770 return new (Alloc) DIE(Tag);
3
Calling 'operator new<llvm::MallocAllocator, 4096UL, 4096UL, 128UL>'
771 }
772
773 // Accessors.
774 unsigned getAbbrevNumber() const { return AbbrevNumber; }
775 dwarf::Tag getTag() const { return Tag; }
776 /// Get the compile/type unit relative offset of this DIE.
777 unsigned getOffset() const { return Offset; }
778 unsigned getSize() const { return Size; }
779 bool hasChildren() const { return ForceChildren || !Children.empty(); }
780 void setForceChildren(bool B) { ForceChildren = B; }
781
782 using child_iterator = IntrusiveBackList<DIE>::iterator;
783 using const_child_iterator = IntrusiveBackList<DIE>::const_iterator;
784 using child_range = iterator_range<child_iterator>;
785 using const_child_range = iterator_range<const_child_iterator>;
786
787 child_range children() {
788 return make_range(Children.begin(), Children.end());
789 }
790 const_child_range children() const {
791 return make_range(Children.begin(), Children.end());
792 }
793
794 DIE *getParent() const;
795
796 /// Generate the abbreviation for this DIE.
797 ///
798 /// Calculate the abbreviation for this, which should be uniqued and
799 /// eventually used to call \a setAbbrevNumber().
800 DIEAbbrev generateAbbrev() const;
801
802 /// Set the abbreviation number for this DIE.
803 void setAbbrevNumber(unsigned I) { AbbrevNumber = I; }
804
805 /// Get the absolute offset within the .debug_info or .debug_types section
806 /// for this DIE.
807 uint64_t getDebugSectionOffset() const;
808
809 /// Compute the offset of this DIE and all its children.
810 ///
811 /// This function gets called just before we are going to generate the debug
812 /// information and gives each DIE a chance to figure out its CU relative DIE
813 /// offset, unique its abbreviation and fill in the abbreviation code, and
814 /// return the unit offset that points to where the next DIE will be emitted
815 /// within the debug unit section. After this function has been called for all
816 /// DIE objects, the DWARF can be generated since all DIEs will be able to
817 /// properly refer to other DIE objects since all DIEs have calculated their
818 /// offsets.
819 ///
820 /// \param AP AsmPrinter to use when calculating sizes.
821 /// \param AbbrevSet the abbreviation used to unique DIE abbreviations.
822 /// \param CUOffset the compile/type unit relative offset in bytes.
823 /// \returns the offset for the DIE that follows this DIE within the
824 /// current compile/type unit.
825 unsigned computeOffsetsAndAbbrevs(const AsmPrinter *AP,
826 DIEAbbrevSet &AbbrevSet, unsigned CUOffset);
827
828 /// Climb up the parent chain to get the compile unit or type unit DIE that
829 /// this DIE belongs to.
830 ///
831 /// \returns the compile or type unit DIE that owns this DIE, or NULL if
832 /// this DIE hasn't been added to a unit DIE.
833 const DIE *getUnitDie() const;
834
835 /// Climb up the parent chain to get the compile unit or type unit that this
836 /// DIE belongs to.
837 ///
838 /// \returns the DIEUnit that represents the compile or type unit that owns
839 /// this DIE, or NULL if this DIE hasn't been added to a unit DIE.
840 DIEUnit *getUnit() const;
841
842 void setOffset(unsigned O) { Offset = O; }
843 void setSize(unsigned S) { Size = S; }
844
845 /// Add a child to the DIE.
846 DIE &addChild(DIE *Child) {
847 assert(!Child->getParent() && "Child should be orphaned")((void)0);
848 Child->Owner = this;
849 Children.push_back(*Child);
850 return Children.back();
851 }
852
853 DIE &addChildFront(DIE *Child) {
854 assert(!Child->getParent() && "Child should be orphaned")((void)0);
855 Child->Owner = this;
856 Children.push_front(*Child);
857 return Children.front();
858 }
859
860 /// Find a value in the DIE with the attribute given.
861 ///
862 /// Returns a default-constructed DIEValue (where \a DIEValue::getType()
863 /// gives \a DIEValue::isNone) if no such attribute exists.
864 DIEValue findAttribute(dwarf::Attribute Attribute) const;
865
866 void print(raw_ostream &O, unsigned IndentCount = 0) const;
867 void dump() const;
868};
869
870//===--------------------------------------------------------------------===//
871/// Represents a compile or type unit.
872class DIEUnit {
873 /// The compile unit or type unit DIE. This variable must be an instance of
874 /// DIE so that we can calculate the DIEUnit from any DIE by traversing the
875 /// parent backchain and getting the Unit DIE, and then casting itself to a
876 /// DIEUnit. This allows us to be able to find the DIEUnit for any DIE without
877 /// having to store a pointer to the DIEUnit in each DIE instance.
878 DIE Die;
879 /// The section this unit will be emitted in. This may or may not be set to
880 /// a valid section depending on the client that is emitting DWARF.
881 MCSection *Section;
882 uint64_t Offset; /// .debug_info or .debug_types absolute section offset.
883protected:
884 virtual ~DIEUnit() = default;
885
886public:
887 explicit DIEUnit(dwarf::Tag UnitTag);
888 DIEUnit(const DIEUnit &RHS) = delete;
889 DIEUnit(DIEUnit &&RHS) = delete;
890 void operator=(const DIEUnit &RHS) = delete;
891 void operator=(const DIEUnit &&RHS) = delete;
892 /// Set the section that this DIEUnit will be emitted into.
893 ///
894 /// This function is used by some clients to set the section. Not all clients
895 /// that emit DWARF use this section variable.
896 void setSection(MCSection *Section) {
897 assert(!this->Section)((void)0);
898 this->Section = Section;
899 }
900
901 virtual const MCSymbol *getCrossSectionRelativeBaseAddress() const {
902 return nullptr;
903 }
904
905 /// Return the section that this DIEUnit will be emitted into.
906 ///
907 /// \returns Section pointer which can be NULL.
908 MCSection *getSection() const { return Section; }
909 void setDebugSectionOffset(uint64_t O) { Offset = O; }
910 uint64_t getDebugSectionOffset() const { return Offset; }
911 DIE &getUnitDie() { return Die; }
912 const DIE &getUnitDie() const { return Die; }
913};
914
915struct BasicDIEUnit final : DIEUnit {
916 explicit BasicDIEUnit(dwarf::Tag UnitTag) : DIEUnit(UnitTag) {}
917};
918
919//===--------------------------------------------------------------------===//
920/// DIELoc - Represents an expression location.
921//
922class DIELoc : public DIEValueList {
923 mutable unsigned Size = 0; // Size in bytes excluding size header.
924
925public:
926 DIELoc() = default;
927
928 /// ComputeSize - Calculate the size of the location expression.
929 ///
930 unsigned ComputeSize(const AsmPrinter *AP) const;
931
932 // TODO: move setSize() and Size to DIEValueList.
933 void setSize(unsigned size) { Size = size; }
934
935 /// BestForm - Choose the best form for data.
936 ///
937 dwarf::Form BestForm(unsigned DwarfVersion) const {
938 if (DwarfVersion > 3)
939 return dwarf::DW_FORM_exprloc;
940 // Pre-DWARF4 location expressions were blocks and not exprloc.
941 if ((unsigned char)Size == Size)
942 return dwarf::DW_FORM_block1;
943 if ((unsigned short)Size == Size)
944 return dwarf::DW_FORM_block2;
945 if ((unsigned int)Size == Size)
946 return dwarf::DW_FORM_block4;
947 return dwarf::DW_FORM_block;
948 }
949
950 void emitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
951 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
952
953 void print(raw_ostream &O) const;
954};
955
956//===--------------------------------------------------------------------===//
957/// DIEBlock - Represents a block of values.
958//
959class DIEBlock : public DIEValueList {
960 mutable unsigned Size = 0; // Size in bytes excluding size header.
961
962public:
963 DIEBlock() = default;
964
965 /// ComputeSize - Calculate the size of the location expression.
966 ///
967 unsigned ComputeSize(const AsmPrinter *AP) const;
968
969 // TODO: move setSize() and Size to DIEValueList.
970 void setSize(unsigned size) { Size = size; }
971
972 /// BestForm - Choose the best form for data.
973 ///
974 dwarf::Form BestForm() const {
975 if ((unsigned char)Size == Size)
976 return dwarf::DW_FORM_block1;
977 if ((unsigned short)Size == Size)
978 return dwarf::DW_FORM_block2;
979 if ((unsigned int)Size == Size)
980 return dwarf::DW_FORM_block4;
981 return dwarf::DW_FORM_block;
982 }
983
984 void emitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
985 unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
986
987 void print(raw_ostream &O) const;
988};
989
990} // end namespace llvm
991
992#endif // LLVM_CODEGEN_DIE_H

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/Allocator.h

1//===- Allocator.h - Simple memory allocation abstraction -------*- C++ -*-===//
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/// \file
9///
10/// This file defines the BumpPtrAllocator interface. BumpPtrAllocator conforms
11/// to the LLVM "Allocator" concept and is similar to MallocAllocator, but
12/// objects cannot be deallocated. Their lifetime is tied to the lifetime of the
13/// allocator.
14///
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_SUPPORT_ALLOCATOR_H
18#define LLVM_SUPPORT_ALLOCATOR_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/Support/Alignment.h"
23#include "llvm/Support/AllocatorBase.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/MemAlloc.h"
28#include <algorithm>
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <cstdlib>
33#include <iterator>
34#include <type_traits>
35#include <utility>
36
37namespace llvm {
38
39namespace detail {
40
41// We call out to an external function to actually print the message as the
42// printing code uses Allocator.h in its implementation.
43void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
44 size_t TotalMemory);
45
46} // end namespace detail
47
48/// Allocate memory in an ever growing pool, as if by bump-pointer.
49///
50/// This isn't strictly a bump-pointer allocator as it uses backing slabs of
51/// memory rather than relying on a boundless contiguous heap. However, it has
52/// bump-pointer semantics in that it is a monotonically growing pool of memory
53/// where every allocation is found by merely allocating the next N bytes in
54/// the slab, or the next N bytes in the next slab.
55///
56/// Note that this also has a threshold for forcing allocations above a certain
57/// size into their own slab.
58///
59/// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
60/// object, which wraps malloc, to allocate memory, but it can be changed to
61/// use a custom allocator.
62///
63/// The GrowthDelay specifies after how many allocated slabs the allocator
64/// increases the size of the slabs.
65template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
66 size_t SizeThreshold = SlabSize, size_t GrowthDelay = 128>
67class BumpPtrAllocatorImpl
68 : public AllocatorBase<BumpPtrAllocatorImpl<AllocatorT, SlabSize,
69 SizeThreshold, GrowthDelay>>,
70 private AllocatorT {
71public:
72 static_assert(SizeThreshold <= SlabSize,
73 "The SizeThreshold must be at most the SlabSize to ensure "
74 "that objects larger than a slab go into their own memory "
75 "allocation.");
76 static_assert(GrowthDelay > 0,
77 "GrowthDelay must be at least 1 which already increases the"
78 "slab size after each allocated slab.");
79
80 BumpPtrAllocatorImpl() = default;
81
82 template <typename T>
83 BumpPtrAllocatorImpl(T &&Allocator)
84 : AllocatorT(std::forward<T &&>(Allocator)) {}
85
86 // Manually implement a move constructor as we must clear the old allocator's
87 // slabs as a matter of correctness.
88 BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
89 : AllocatorT(static_cast<AllocatorT &&>(Old)), CurPtr(Old.CurPtr),
90 End(Old.End), Slabs(std::move(Old.Slabs)),
91 CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
92 BytesAllocated(Old.BytesAllocated), RedZoneSize(Old.RedZoneSize) {
93 Old.CurPtr = Old.End = nullptr;
94 Old.BytesAllocated = 0;
95 Old.Slabs.clear();
96 Old.CustomSizedSlabs.clear();
97 }
98
99 ~BumpPtrAllocatorImpl() {
100 DeallocateSlabs(Slabs.begin(), Slabs.end());
101 DeallocateCustomSizedSlabs();
102 }
103
104 BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
105 DeallocateSlabs(Slabs.begin(), Slabs.end());
106 DeallocateCustomSizedSlabs();
107
108 CurPtr = RHS.CurPtr;
109 End = RHS.End;
110 BytesAllocated = RHS.BytesAllocated;
111 RedZoneSize = RHS.RedZoneSize;
112 Slabs = std::move(RHS.Slabs);
113 CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
114 AllocatorT::operator=(static_cast<AllocatorT &&>(RHS));
115
116 RHS.CurPtr = RHS.End = nullptr;
117 RHS.BytesAllocated = 0;
118 RHS.Slabs.clear();
119 RHS.CustomSizedSlabs.clear();
120 return *this;
121 }
122
123 /// Deallocate all but the current slab and reset the current pointer
124 /// to the beginning of it, freeing all memory allocated so far.
125 void Reset() {
126 // Deallocate all but the first slab, and deallocate all custom-sized slabs.
127 DeallocateCustomSizedSlabs();
128 CustomSizedSlabs.clear();
129
130 if (Slabs.empty())
131 return;
132
133 // Reset the state.
134 BytesAllocated = 0;
135 CurPtr = (char *)Slabs.front();
136 End = CurPtr + SlabSize;
137
138 __asan_poison_memory_region(*Slabs.begin(), computeSlabSize(0));
139 DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
140 Slabs.erase(std::next(Slabs.begin()), Slabs.end());
141 }
142
143 /// Allocate space at the specified alignment.
144 LLVM_ATTRIBUTE_RETURNS_NONNULL__attribute__((returns_nonnull)) LLVM_ATTRIBUTE_RETURNS_NOALIAS__attribute__((__malloc__)) void *
145 Allocate(size_t Size, Align Alignment) {
146 // Keep track of how many bytes we've allocated.
147 BytesAllocated += Size;
148
149 size_t Adjustment = offsetToAlignedAddr(CurPtr, Alignment);
6
Calling 'offsetToAlignedAddr'
150 assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow")((void)0);
151
152 size_t SizeToAllocate = Size;
153#if LLVM_ADDRESS_SANITIZER_BUILD0
154 // Add trailing bytes as a "red zone" under ASan.
155 SizeToAllocate += RedZoneSize;
156#endif
157
158 // Check if we have enough space.
159 if (Adjustment + SizeToAllocate <= size_t(End - CurPtr)) {
160 char *AlignedPtr = CurPtr + Adjustment;
161 CurPtr = AlignedPtr + SizeToAllocate;
162 // Update the allocation point of this memory block in MemorySanitizer.
163 // Without this, MemorySanitizer messages for values originated from here
164 // will point to the allocation of the entire slab.
165 __msan_allocated_memory(AlignedPtr, Size);
166 // Similarly, tell ASan about this space.
167 __asan_unpoison_memory_region(AlignedPtr, Size);
168 return AlignedPtr;
169 }
170
171 // If Size is really big, allocate a separate slab for it.
172 size_t PaddedSize = SizeToAllocate + Alignment.value() - 1;
173 if (PaddedSize > SizeThreshold) {
174 void *NewSlab =
175 AllocatorT::Allocate(PaddedSize, alignof(std::max_align_t));
176 // We own the new slab and don't want anyone reading anyting other than
177 // pieces returned from this method. So poison the whole slab.
178 __asan_poison_memory_region(NewSlab, PaddedSize);
179 CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
180
181 uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment);
182 assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize)((void)0);
183 char *AlignedPtr = (char*)AlignedAddr;
184 __msan_allocated_memory(AlignedPtr, Size);
185 __asan_unpoison_memory_region(AlignedPtr, Size);
186 return AlignedPtr;
187 }
188
189 // Otherwise, start a new slab and try again.
190 StartNewSlab();
191 uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment);
192 assert(AlignedAddr + SizeToAllocate <= (uintptr_t)End &&((void)0)
193 "Unable to allocate memory!")((void)0);
194 char *AlignedPtr = (char*)AlignedAddr;
195 CurPtr = AlignedPtr + SizeToAllocate;
196 __msan_allocated_memory(AlignedPtr, Size);
197 __asan_unpoison_memory_region(AlignedPtr, Size);
198 return AlignedPtr;
199 }
200
201 inline LLVM_ATTRIBUTE_RETURNS_NONNULL__attribute__((returns_nonnull)) LLVM_ATTRIBUTE_RETURNS_NOALIAS__attribute__((__malloc__)) void *
202 Allocate(size_t Size, size_t Alignment) {
203 assert(Alignment > 0 && "0-byte alignment is not allowed. Use 1 instead.")((void)0);
204 return Allocate(Size, Align(Alignment));
5
Calling 'BumpPtrAllocatorImpl::Allocate'
205 }
206
207 // Pull in base class overloads.
208 using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
209
210 // Bump pointer allocators are expected to never free their storage; and
211 // clients expect pointers to remain valid for non-dereferencing uses even
212 // after deallocation.
213 void Deallocate(const void *Ptr, size_t Size, size_t /*Alignment*/) {
214 __asan_poison_memory_region(Ptr, Size);
215 }
216
217 // Pull in base class overloads.
218 using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
219
220 size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
221
222 /// \return An index uniquely and reproducibly identifying
223 /// an input pointer \p Ptr in the given allocator.
224 /// The returned value is negative iff the object is inside a custom-size
225 /// slab.
226 /// Returns an empty optional if the pointer is not found in the allocator.
227 llvm::Optional<int64_t> identifyObject(const void *Ptr) {
228 const char *P = static_cast<const char *>(Ptr);
229 int64_t InSlabIdx = 0;
230 for (size_t Idx = 0, E = Slabs.size(); Idx < E; Idx++) {
231 const char *S = static_cast<const char *>(Slabs[Idx]);
232 if (P >= S && P < S + computeSlabSize(Idx))
233 return InSlabIdx + static_cast<int64_t>(P - S);
234 InSlabIdx += static_cast<int64_t>(computeSlabSize(Idx));
235 }
236
237 // Use negative index to denote custom sized slabs.
238 int64_t InCustomSizedSlabIdx = -1;
239 for (size_t Idx = 0, E = CustomSizedSlabs.size(); Idx < E; Idx++) {
240 const char *S = static_cast<const char *>(CustomSizedSlabs[Idx].first);
241 size_t Size = CustomSizedSlabs[Idx].second;
242 if (P >= S && P < S + Size)
243 return InCustomSizedSlabIdx - static_cast<int64_t>(P - S);
244 InCustomSizedSlabIdx -= static_cast<int64_t>(Size);
245 }
246 return None;
247 }
248
249 /// A wrapper around identifyObject that additionally asserts that
250 /// the object is indeed within the allocator.
251 /// \return An index uniquely and reproducibly identifying
252 /// an input pointer \p Ptr in the given allocator.
253 int64_t identifyKnownObject(const void *Ptr) {
254 Optional<int64_t> Out = identifyObject(Ptr);
255 assert(Out && "Wrong allocator used")((void)0);
256 return *Out;
257 }
258
259 /// A wrapper around identifyKnownObject. Accepts type information
260 /// about the object and produces a smaller identifier by relying on
261 /// the alignment information. Note that sub-classes may have different
262 /// alignment, so the most base class should be passed as template parameter
263 /// in order to obtain correct results. For that reason automatic template
264 /// parameter deduction is disabled.
265 /// \return An index uniquely and reproducibly identifying
266 /// an input pointer \p Ptr in the given allocator. This identifier is
267 /// different from the ones produced by identifyObject and
268 /// identifyAlignedObject.
269 template <typename T>
270 int64_t identifyKnownAlignedObject(const void *Ptr) {
271 int64_t Out = identifyKnownObject(Ptr);
272 assert(Out % alignof(T) == 0 && "Wrong alignment information")((void)0);
273 return Out / alignof(T);
274 }
275
276 size_t getTotalMemory() const {
277 size_t TotalMemory = 0;
278 for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
279 TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
280 for (auto &PtrAndSize : CustomSizedSlabs)
281 TotalMemory += PtrAndSize.second;
282 return TotalMemory;
283 }
284
285 size_t getBytesAllocated() const { return BytesAllocated; }
286
287 void setRedZoneSize(size_t NewSize) {
288 RedZoneSize = NewSize;
289 }
290
291 void PrintStats() const {
292 detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
293 getTotalMemory());
294 }
295
296private:
297 /// The current pointer into the current slab.
298 ///
299 /// This points to the next free byte in the slab.
300 char *CurPtr = nullptr;
301
302 /// The end of the current slab.
303 char *End = nullptr;
304
305 /// The slabs allocated so far.
306 SmallVector<void *, 4> Slabs;
307
308 /// Custom-sized slabs allocated for too-large allocation requests.
309 SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
310
311 /// How many bytes we've allocated.
312 ///
313 /// Used so that we can compute how much space was wasted.
314 size_t BytesAllocated = 0;
315
316 /// The number of bytes to put between allocations when running under
317 /// a sanitizer.
318 size_t RedZoneSize = 1;
319
320 static size_t computeSlabSize(unsigned SlabIdx) {
321 // Scale the actual allocated slab size based on the number of slabs
322 // allocated. Every GrowthDelay slabs allocated, we double
323 // the allocated size to reduce allocation frequency, but saturate at
324 // multiplying the slab size by 2^30.
325 return SlabSize *
326 ((size_t)1 << std::min<size_t>(30, SlabIdx / GrowthDelay));
327 }
328
329 /// Allocate a new slab and move the bump pointers over into the new
330 /// slab, modifying CurPtr and End.
331 void StartNewSlab() {
332 size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
333
334 void *NewSlab =
335 AllocatorT::Allocate(AllocatedSlabSize, alignof(std::max_align_t));
336 // We own the new slab and don't want anyone reading anything other than
337 // pieces returned from this method. So poison the whole slab.
338 __asan_poison_memory_region(NewSlab, AllocatedSlabSize);
339
340 Slabs.push_back(NewSlab);
341 CurPtr = (char *)(NewSlab);
342 End = ((char *)NewSlab) + AllocatedSlabSize;
343 }
344
345 /// Deallocate a sequence of slabs.
346 void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
347 SmallVectorImpl<void *>::iterator E) {
348 for (; I != E; ++I) {
349 size_t AllocatedSlabSize =
350 computeSlabSize(std::distance(Slabs.begin(), I));
351 AllocatorT::Deallocate(*I, AllocatedSlabSize, alignof(std::max_align_t));
352 }
353 }
354
355 /// Deallocate all memory for custom sized slabs.
356 void DeallocateCustomSizedSlabs() {
357 for (auto &PtrAndSize : CustomSizedSlabs) {
358 void *Ptr = PtrAndSize.first;
359 size_t Size = PtrAndSize.second;
360 AllocatorT::Deallocate(Ptr, Size, alignof(std::max_align_t));
361 }
362 }
363
364 template <typename T> friend class SpecificBumpPtrAllocator;
365};
366
367/// The standard BumpPtrAllocator which just uses the default template
368/// parameters.
369typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
370
371/// A BumpPtrAllocator that allows only elements of a specific type to be
372/// allocated.
373///
374/// This allows calling the destructor in DestroyAll() and when the allocator is
375/// destroyed.
376template <typename T> class SpecificBumpPtrAllocator {
377 BumpPtrAllocator Allocator;
378
379public:
380 SpecificBumpPtrAllocator() {
381 // Because SpecificBumpPtrAllocator walks the memory to call destructors,
382 // it can't have red zones between allocations.
383 Allocator.setRedZoneSize(0);
384 }
385 SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
386 : Allocator(std::move(Old.Allocator)) {}
387 ~SpecificBumpPtrAllocator() { DestroyAll(); }
388
389 SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
390 Allocator = std::move(RHS.Allocator);
391 return *this;
392 }
393
394 /// Call the destructor of each allocated object and deallocate all but the
395 /// current slab and reset the current pointer to the beginning of it, freeing
396 /// all memory allocated so far.
397 void DestroyAll() {
398 auto DestroyElements = [](char *Begin, char *End) {
399 assert(Begin == (char *)alignAddr(Begin, Align::Of<T>()))((void)0);
400 for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
401 reinterpret_cast<T *>(Ptr)->~T();
402 };
403
404 for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
405 ++I) {
406 size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
407 std::distance(Allocator.Slabs.begin(), I));
408 char *Begin = (char *)alignAddr(*I, Align::Of<T>());
409 char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
410 : (char *)*I + AllocatedSlabSize;
411
412 DestroyElements(Begin, End);
413 }
414
415 for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
416 void *Ptr = PtrAndSize.first;
417 size_t Size = PtrAndSize.second;
418 DestroyElements((char *)alignAddr(Ptr, Align::Of<T>()),
419 (char *)Ptr + Size);
420 }
421
422 Allocator.Reset();
423 }
424
425 /// Allocate space for an array of objects without constructing them.
426 T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
427};
428
429} // end namespace llvm
430
431template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
432 size_t GrowthDelay>
433void *
434operator new(size_t Size,
435 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold,
436 GrowthDelay> &Allocator) {
437 return Allocator.Allocate(Size, std::min((size_t)llvm::NextPowerOf2(Size),
4
Calling 'BumpPtrAllocatorImpl::Allocate'
438 alignof(std::max_align_t)));
439}
440
441template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
442 size_t GrowthDelay>
443void operator delete(void *,
444 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
445 SizeThreshold, GrowthDelay> &) {
446}
447
448#endif // LLVM_SUPPORT_ALLOCATOR_H

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/Alignment.h

1//===-- llvm/Support/Alignment.h - Useful alignment functions ---*- C++ -*-===//
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 contains types to represent alignments.
10// They are instrumented to guarantee some invariants are preserved and prevent
11// invalid manipulations.
12//
13// - Align represents an alignment in bytes, it is always set and always a valid
14// power of two, its minimum value is 1 which means no alignment requirements.
15//
16// - MaybeAlign is an optional type, it may be undefined or set. When it's set
17// you can get the underlying Align type by using the getValue() method.
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_SUPPORT_ALIGNMENT_H_
22#define LLVM_SUPPORT_ALIGNMENT_H_
23
24#include "llvm/ADT/Optional.h"
25#include "llvm/Support/MathExtras.h"
26#include <cassert>
27#ifndef NDEBUG1
28#include <string>
29#endif // NDEBUG
30
31namespace llvm {
32
33#define ALIGN_CHECK_ISPOSITIVE(decl) \
34 assert(decl > 0 && (#decl " should be defined"))((void)0)
35
36/// This struct is a compact representation of a valid (non-zero power of two)
37/// alignment.
38/// It is suitable for use as static global constants.
39struct Align {
40private:
41 uint8_t ShiftValue = 0; /// The log2 of the required alignment.
42 /// ShiftValue is less than 64 by construction.
43
44 friend struct MaybeAlign;
45 friend unsigned Log2(Align);
46 friend bool operator==(Align Lhs, Align Rhs);
47 friend bool operator!=(Align Lhs, Align Rhs);
48 friend bool operator<=(Align Lhs, Align Rhs);
49 friend bool operator>=(Align Lhs, Align Rhs);
50 friend bool operator<(Align Lhs, Align Rhs);
51 friend bool operator>(Align Lhs, Align Rhs);
52 friend unsigned encode(struct MaybeAlign A);
53 friend struct MaybeAlign decodeMaybeAlign(unsigned Value);
54
55 /// A trivial type to allow construction of constexpr Align.
56 /// This is currently needed to workaround a bug in GCC 5.3 which prevents
57 /// definition of constexpr assign operators.
58 /// https://stackoverflow.com/questions/46756288/explicitly-defaulted-function-cannot-be-declared-as-constexpr-because-the-implic
59 /// FIXME: Remove this, make all assign operators constexpr and introduce user
60 /// defined literals when we don't have to support GCC 5.3 anymore.
61 /// https://llvm.org/docs/GettingStarted.html#getting-a-modern-host-c-toolchain
62 struct LogValue {
63 uint8_t Log;
64 };
65
66public:
67 /// Default is byte-aligned.
68 constexpr Align() = default;
69 /// Do not perform checks in case of copy/move construct/assign, because the
70 /// checks have been performed when building `Other`.
71 constexpr Align(const Align &Other) = default;
72 constexpr Align(Align &&Other) = default;
73 Align &operator=(const Align &Other) = default;
74 Align &operator=(Align &&Other) = default;
75
76 explicit Align(uint64_t Value) {
77 assert(Value > 0 && "Value must not be 0")((void)0);
78 assert(llvm::isPowerOf2_64(Value) && "Alignment is not a power of 2")((void)0);
79 ShiftValue = Log2_64(Value);
80 assert(ShiftValue < 64 && "Broken invariant")((void)0);
81 }
82
83 /// This is a hole in the type system and should not be abused.
84 /// Needed to interact with C for instance.
85 uint64_t value() const { return uint64_t(1) << ShiftValue; }
11
The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'uint64_t'
86
87 /// Allow constructions of constexpr Align.
88 template <size_t kValue> constexpr static LogValue Constant() {
89 return LogValue{static_cast<uint8_t>(CTLog2<kValue>())};
90 }
91
92 /// Allow constructions of constexpr Align from types.
93 /// Compile time equivalent to Align(alignof(T)).
94 template <typename T> constexpr static LogValue Of() {
95 return Constant<std::alignment_of<T>::value>();
96 }
97
98 /// Constexpr constructor from LogValue type.
99 constexpr Align(LogValue CA) : ShiftValue(CA.Log) {}
100};
101
102/// Treats the value 0 as a 1, so Align is always at least 1.
103inline Align assumeAligned(uint64_t Value) {
104 return Value ? Align(Value) : Align();
105}
106
107/// This struct is a compact representation of a valid (power of two) or
108/// undefined (0) alignment.
109struct MaybeAlign : public llvm::Optional<Align> {
110private:
111 using UP = llvm::Optional<Align>;
112
113public:
114 /// Default is undefined.
115 MaybeAlign() = default;
116 /// Do not perform checks in case of copy/move construct/assign, because the
117 /// checks have been performed when building `Other`.
118 MaybeAlign(const MaybeAlign &Other) = default;
119 MaybeAlign &operator=(const MaybeAlign &Other) = default;
120 MaybeAlign(MaybeAlign &&Other) = default;
121 MaybeAlign &operator=(MaybeAlign &&Other) = default;
122
123 /// Use llvm::Optional<Align> constructor.
124 using UP::UP;
125
126 explicit MaybeAlign(uint64_t Value) {
127 assert((Value == 0 || llvm::isPowerOf2_64(Value)) &&((void)0)
128 "Alignment is neither 0 nor a power of 2")((void)0);
129 if (Value)
130 emplace(Value);
131 }
132
133 /// For convenience, returns a valid alignment or 1 if undefined.
134 Align valueOrOne() const { return hasValue() ? getValue() : Align(); }
135};
136
137/// Checks that SizeInBytes is a multiple of the alignment.
138inline bool isAligned(Align Lhs, uint64_t SizeInBytes) {
139 return SizeInBytes % Lhs.value() == 0;
140}
141
142/// Checks that Addr is a multiple of the alignment.
143inline bool isAddrAligned(Align Lhs, const void *Addr) {
144 return isAligned(Lhs, reinterpret_cast<uintptr_t>(Addr));
145}
146
147/// Returns a multiple of A needed to store `Size` bytes.
148inline uint64_t alignTo(uint64_t Size, Align A) {
149 const uint64_t Value = A.value();
10
Calling 'Align::value'
150 // The following line is equivalent to `(Size + Value - 1) / Value * Value`.
151
152 // The division followed by a multiplication can be thought of as a right
153 // shift followed by a left shift which zeros out the extra bits produced in
154 // the bump; `~(Value - 1)` is a mask where all those bits being zeroed out
155 // are just zero.
156
157 // Most compilers can generate this code but the pattern may be missed when
158 // multiple functions gets inlined.
159 return (Size + Value - 1) & ~(Value - 1U);
160}
161
162/// If non-zero \p Skew is specified, the return value will be a minimal integer
163/// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
164/// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
165/// Skew mod \p A'.
166///
167/// Examples:
168/// \code
169/// alignTo(5, Align(8), 7) = 7
170/// alignTo(17, Align(8), 1) = 17
171/// alignTo(~0LL, Align(8), 3) = 3
172/// \endcode
173inline uint64_t alignTo(uint64_t Size, Align A, uint64_t Skew) {
174 const uint64_t Value = A.value();
175 Skew %= Value;
176 return ((Size + Value - 1 - Skew) & ~(Value - 1U)) + Skew;
177}
178
179/// Returns a multiple of A needed to store `Size` bytes.
180/// Returns `Size` if current alignment is undefined.
181inline uint64_t alignTo(uint64_t Size, MaybeAlign A) {
182 return A ? alignTo(Size, A.getValue()) : Size;
183}
184
185/// Aligns `Addr` to `Alignment` bytes, rounding up.
186inline uintptr_t alignAddr(const void *Addr, Align Alignment) {
187 uintptr_t ArithAddr = reinterpret_cast<uintptr_t>(Addr);
188 assert(static_cast<uintptr_t>(ArithAddr + Alignment.value() - 1) >=((void)0)
189 ArithAddr &&((void)0)
190 "Overflow")((void)0);
191 return alignTo(ArithAddr, Alignment);
192}
193
194/// Returns the offset to the next integer (mod 2**64) that is greater than
195/// or equal to \p Value and is a multiple of \p Align.
196inline uint64_t offsetToAlignment(uint64_t Value, Align Alignment) {
197 return alignTo(Value, Alignment) - Value;
8
The value 255 is assigned to 'A.ShiftValue'
9
Calling 'alignTo'
198}
199
200/// Returns the necessary adjustment for aligning `Addr` to `Alignment`
201/// bytes, rounding up.
202inline uint64_t offsetToAlignedAddr(const void *Addr, Align Alignment) {
203 return offsetToAlignment(reinterpret_cast<uintptr_t>(Addr), Alignment);
7
Calling 'offsetToAlignment'
204}
205
206/// Returns the log2 of the alignment.
207inline unsigned Log2(Align A) { return A.ShiftValue; }
208
209/// Returns the alignment that satisfies both alignments.
210/// Same semantic as MinAlign.
211inline Align commonAlignment(Align A, Align B) { return std::min(A, B); }
212
213/// Returns the alignment that satisfies both alignments.
214/// Same semantic as MinAlign.
215inline Align commonAlignment(Align A, uint64_t Offset) {
216 return Align(MinAlign(A.value(), Offset));
217}
218
219/// Returns the alignment that satisfies both alignments.
220/// Same semantic as MinAlign.
221inline MaybeAlign commonAlignment(MaybeAlign A, MaybeAlign B) {
222 return A && B ? commonAlignment(*A, *B) : A ? A : B;
223}
224
225/// Returns the alignment that satisfies both alignments.
226/// Same semantic as MinAlign.
227inline MaybeAlign commonAlignment(MaybeAlign A, uint64_t Offset) {
228 return MaybeAlign(MinAlign((*A).value(), Offset));
229}
230
231/// Returns a representation of the alignment that encodes undefined as 0.
232inline unsigned encode(MaybeAlign A) { return A ? A->ShiftValue + 1 : 0; }
233
234/// Dual operation of the encode function above.
235inline MaybeAlign decodeMaybeAlign(unsigned Value) {
236 if (Value == 0)
237 return MaybeAlign();
238 Align Out;
239 Out.ShiftValue = Value - 1;
240 return Out;
241}
242
243/// Returns a representation of the alignment, the encoded value is positive by
244/// definition.
245inline unsigned encode(Align A) { return encode(MaybeAlign(A)); }
246
247/// Comparisons between Align and scalars. Rhs must be positive.
248inline bool operator==(Align Lhs, uint64_t Rhs) {
249 ALIGN_CHECK_ISPOSITIVE(Rhs);
250 return Lhs.value() == Rhs;
251}
252inline bool operator!=(Align Lhs, uint64_t Rhs) {
253 ALIGN_CHECK_ISPOSITIVE(Rhs);
254 return Lhs.value() != Rhs;
255}
256inline bool operator<=(Align Lhs, uint64_t Rhs) {
257 ALIGN_CHECK_ISPOSITIVE(Rhs);
258 return Lhs.value() <= Rhs;
259}
260inline bool operator>=(Align Lhs, uint64_t Rhs) {
261 ALIGN_CHECK_ISPOSITIVE(Rhs);
262 return Lhs.value() >= Rhs;
263}
264inline bool operator<(Align Lhs, uint64_t Rhs) {
265 ALIGN_CHECK_ISPOSITIVE(Rhs);
266 return Lhs.value() < Rhs;
267}
268inline bool operator>(Align Lhs, uint64_t Rhs) {
269 ALIGN_CHECK_ISPOSITIVE(Rhs);
270 return Lhs.value() > Rhs;
271}
272
273/// Comparisons between MaybeAlign and scalars.
274inline bool operator==(MaybeAlign Lhs, uint64_t Rhs) {
275 return Lhs ? (*Lhs).value() == Rhs : Rhs == 0;
276}
277inline bool operator!=(MaybeAlign Lhs, uint64_t Rhs) {
278 return Lhs ? (*Lhs).value() != Rhs : Rhs != 0;
279}
280
281/// Comparisons operators between Align.
282inline bool operator==(Align Lhs, Align Rhs) {
283 return Lhs.ShiftValue == Rhs.ShiftValue;
284}
285inline bool operator!=(Align Lhs, Align Rhs) {
286 return Lhs.ShiftValue != Rhs.ShiftValue;
287}
288inline bool operator<=(Align Lhs, Align Rhs) {
289 return Lhs.ShiftValue <= Rhs.ShiftValue;
290}
291inline bool operator>=(Align Lhs, Align Rhs) {
292 return Lhs.ShiftValue >= Rhs.ShiftValue;
293}
294inline bool operator<(Align Lhs, Align Rhs) {
295 return Lhs.ShiftValue < Rhs.ShiftValue;
296}
297inline bool operator>(Align Lhs, Align Rhs) {
298 return Lhs.ShiftValue > Rhs.ShiftValue;
299}
300
301// Don't allow relational comparisons with MaybeAlign.
302bool operator<=(Align Lhs, MaybeAlign Rhs) = delete;
303bool operator>=(Align Lhs, MaybeAlign Rhs) = delete;
304bool operator<(Align Lhs, MaybeAlign Rhs) = delete;
305bool operator>(Align Lhs, MaybeAlign Rhs) = delete;
306
307bool operator<=(MaybeAlign Lhs, Align Rhs) = delete;
308bool operator>=(MaybeAlign Lhs, Align Rhs) = delete;
309bool operator<(MaybeAlign Lhs, Align Rhs) = delete;
310bool operator>(MaybeAlign Lhs, Align Rhs) = delete;
311
312bool operator<=(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
313bool operator>=(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
314bool operator<(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
315bool operator>(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
316
317inline Align operator*(Align Lhs, uint64_t Rhs) {
318 assert(Rhs > 0 && "Rhs must be positive")((void)0);
319 return Align(Lhs.value() * Rhs);
320}
321
322inline MaybeAlign operator*(MaybeAlign Lhs, uint64_t Rhs) {
323 assert(Rhs > 0 && "Rhs must be positive")((void)0);
324 return Lhs ? Lhs.getValue() * Rhs : MaybeAlign();
325}
326
327inline Align operator/(Align Lhs, uint64_t Divisor) {
328 assert(llvm::isPowerOf2_64(Divisor) &&((void)0)
329 "Divisor must be positive and a power of 2")((void)0);
330 assert(Lhs != 1 && "Can't halve byte alignment")((void)0);
331 return Align(Lhs.value() / Divisor);
332}
333
334inline MaybeAlign operator/(MaybeAlign Lhs, uint64_t Divisor) {
335 assert(llvm::isPowerOf2_64(Divisor) &&((void)0)
336 "Divisor must be positive and a power of 2")((void)0);
337 return Lhs ? Lhs.getValue() / Divisor : MaybeAlign();
338}
339
340inline Align max(MaybeAlign Lhs, Align Rhs) {
341 return Lhs && *Lhs > Rhs ? *Lhs : Rhs;
342}
343
344inline Align max(Align Lhs, MaybeAlign Rhs) {
345 return Rhs && *Rhs > Lhs ? *Rhs : Lhs;
346}
347
348#ifndef NDEBUG1
349// For usage in LLVM_DEBUG macros.
350inline std::string DebugStr(const Align &A) {
351 return std::to_string(A.value());
352}
353// For usage in LLVM_DEBUG macros.
354inline std::string DebugStr(const MaybeAlign &MA) {
355 if (MA)
356 return std::to_string(MA->value());
357 return "None";
358}
359#endif // NDEBUG
360
361#undef ALIGN_CHECK_ISPOSITIVE
362
363} // namespace llvm
364
365#endif // LLVM_SUPPORT_ALIGNMENT_H_