Bug Summary

File:tools/clang/lib/CodeGen/CGExprConstant.cpp
Warning:line 644, column 42
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGExprConstant.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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn361465/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn361465/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn361465=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-05-24-031927-21217-1 -x c++ /build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp -faddrsig
1//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
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 contains code to emit Constant Expr nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenFunction.h"
14#include "CGCXXABI.h"
15#include "CGObjCRuntime.h"
16#include "CGRecordLayout.h"
17#include "CodeGenModule.h"
18#include "ConstantEmitter.h"
19#include "TargetInfo.h"
20#include "clang/AST/APValue.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/Basic/Builtins.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/GlobalVariable.h"
29using namespace clang;
30using namespace CodeGen;
31
32//===----------------------------------------------------------------------===//
33// ConstStructBuilder
34//===----------------------------------------------------------------------===//
35
36namespace {
37class ConstExprEmitter;
38class ConstStructBuilder {
39 CodeGenModule &CGM;
40 ConstantEmitter &Emitter;
41
42 bool Packed;
43 CharUnits NextFieldOffsetInChars;
44 CharUnits LLVMStructAlignment;
45 SmallVector<llvm::Constant *, 32> Elements;
46public:
47 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
48 ConstExprEmitter *ExprEmitter,
49 llvm::Constant *Base,
50 InitListExpr *Updater,
51 QualType ValTy);
52 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
53 InitListExpr *ILE, QualType StructTy);
54 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
55 const APValue &Value, QualType ValTy);
56
57private:
58 ConstStructBuilder(ConstantEmitter &emitter)
59 : CGM(emitter.CGM), Emitter(emitter), Packed(false),
60 NextFieldOffsetInChars(CharUnits::Zero()),
61 LLVMStructAlignment(CharUnits::One()) { }
62
63 void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
64 llvm::Constant *InitExpr);
65
66 void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
67
68 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
69 llvm::ConstantInt *InitExpr);
70
71 void AppendPadding(CharUnits PadSize);
72
73 void AppendTailPadding(CharUnits RecordSize);
74
75 void ConvertStructToPacked();
76
77 bool Build(InitListExpr *ILE);
78 bool Build(ConstExprEmitter *Emitter, llvm::Constant *Base,
79 InitListExpr *Updater);
80 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
81 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
82 llvm::Constant *Finalize(QualType Ty);
83
84 CharUnits getAlignment(const llvm::Constant *C) const {
85 if (Packed) return CharUnits::One();
86 return CharUnits::fromQuantity(
87 CGM.getDataLayout().getABITypeAlignment(C->getType()));
88 }
89
90 CharUnits getSizeInChars(const llvm::Constant *C) const {
91 return CharUnits::fromQuantity(
92 CGM.getDataLayout().getTypeAllocSize(C->getType()));
93 }
94};
95
96void ConstStructBuilder::
97AppendField(const FieldDecl *Field, uint64_t FieldOffset,
98 llvm::Constant *InitCst) {
99 const ASTContext &Context = CGM.getContext();
100
101 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
102
103 AppendBytes(FieldOffsetInChars, InitCst);
104}
105
106void ConstStructBuilder::
107AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
108
109 assert(NextFieldOffsetInChars <= FieldOffsetInChars((NextFieldOffsetInChars <= FieldOffsetInChars && "Field offset mismatch!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars <= FieldOffsetInChars && \"Field offset mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 110, __PRETTY_FUNCTION__))
110 && "Field offset mismatch!")((NextFieldOffsetInChars <= FieldOffsetInChars && "Field offset mismatch!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars <= FieldOffsetInChars && \"Field offset mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 110, __PRETTY_FUNCTION__))
;
111
112 CharUnits FieldAlignment = getAlignment(InitCst);
113
114 // Round up the field offset to the alignment of the field type.
115 CharUnits AlignedNextFieldOffsetInChars =
116 NextFieldOffsetInChars.alignTo(FieldAlignment);
117
118 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
119 // We need to append padding.
120 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
121
122 assert(NextFieldOffsetInChars == FieldOffsetInChars &&((NextFieldOffsetInChars == FieldOffsetInChars && "Did not add enough padding!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars == FieldOffsetInChars && \"Did not add enough padding!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 123, __PRETTY_FUNCTION__))
123 "Did not add enough padding!")((NextFieldOffsetInChars == FieldOffsetInChars && "Did not add enough padding!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars == FieldOffsetInChars && \"Did not add enough padding!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 123, __PRETTY_FUNCTION__))
;
124
125 AlignedNextFieldOffsetInChars =
126 NextFieldOffsetInChars.alignTo(FieldAlignment);
127 }
128
129 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
130 assert(!Packed && "Alignment is wrong even with a packed struct!")((!Packed && "Alignment is wrong even with a packed struct!"
) ? static_cast<void> (0) : __assert_fail ("!Packed && \"Alignment is wrong even with a packed struct!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 130, __PRETTY_FUNCTION__))
;
131
132 // Convert the struct to a packed struct.
133 ConvertStructToPacked();
134
135 // After we pack the struct, we may need to insert padding.
136 if (NextFieldOffsetInChars < FieldOffsetInChars) {
137 // We need to append padding.
138 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
139
140 assert(NextFieldOffsetInChars == FieldOffsetInChars &&((NextFieldOffsetInChars == FieldOffsetInChars && "Did not add enough padding!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars == FieldOffsetInChars && \"Did not add enough padding!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 141, __PRETTY_FUNCTION__))
141 "Did not add enough padding!")((NextFieldOffsetInChars == FieldOffsetInChars && "Did not add enough padding!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars == FieldOffsetInChars && \"Did not add enough padding!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 141, __PRETTY_FUNCTION__))
;
142 }
143 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
144 }
145
146 // Add the field.
147 Elements.push_back(InitCst);
148 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
149 getSizeInChars(InitCst);
150
151 if (Packed)
152 assert(LLVMStructAlignment == CharUnits::One() &&((LLVMStructAlignment == CharUnits::One() && "Packed struct not byte-aligned!"
) ? static_cast<void> (0) : __assert_fail ("LLVMStructAlignment == CharUnits::One() && \"Packed struct not byte-aligned!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 153, __PRETTY_FUNCTION__))
153 "Packed struct not byte-aligned!")((LLVMStructAlignment == CharUnits::One() && "Packed struct not byte-aligned!"
) ? static_cast<void> (0) : __assert_fail ("LLVMStructAlignment == CharUnits::One() && \"Packed struct not byte-aligned!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 153, __PRETTY_FUNCTION__))
;
154 else
155 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
156}
157
158void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
159 uint64_t FieldOffset,
160 llvm::ConstantInt *CI) {
161 const ASTContext &Context = CGM.getContext();
162 const uint64_t CharWidth = Context.getCharWidth();
163 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
164 if (FieldOffset > NextFieldOffsetInBits) {
165 // We need to add padding.
166 CharUnits PadSize = Context.toCharUnitsFromBits(
167 llvm::alignTo(FieldOffset - NextFieldOffsetInBits,
168 Context.getTargetInfo().getCharAlign()));
169
170 AppendPadding(PadSize);
171 }
172
173 uint64_t FieldSize = Field->getBitWidthValue(Context);
174
175 llvm::APInt FieldValue = CI->getValue();
176
177 // Promote the size of FieldValue if necessary
178 // FIXME: This should never occur, but currently it can because initializer
179 // constants are cast to bool, and because clang is not enforcing bitfield
180 // width limits.
181 if (FieldSize > FieldValue.getBitWidth())
182 FieldValue = FieldValue.zext(FieldSize);
183
184 // Truncate the size of FieldValue to the bit field size.
185 if (FieldSize < FieldValue.getBitWidth())
186 FieldValue = FieldValue.trunc(FieldSize);
187
188 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
189 if (FieldOffset < NextFieldOffsetInBits) {
190 // Either part of the field or the entire field can go into the previous
191 // byte.
192 assert(!Elements.empty() && "Elements can't be empty!")((!Elements.empty() && "Elements can't be empty!") ? static_cast
<void> (0) : __assert_fail ("!Elements.empty() && \"Elements can't be empty!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 192, __PRETTY_FUNCTION__))
;
193
194 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
195
196 bool FitsCompletelyInPreviousByte =
197 BitsInPreviousByte >= FieldValue.getBitWidth();
198
199 llvm::APInt Tmp = FieldValue;
200
201 if (!FitsCompletelyInPreviousByte) {
202 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
203
204 if (CGM.getDataLayout().isBigEndian()) {
205 Tmp.lshrInPlace(NewFieldWidth);
206 Tmp = Tmp.trunc(BitsInPreviousByte);
207
208 // We want the remaining high bits.
209 FieldValue = FieldValue.trunc(NewFieldWidth);
210 } else {
211 Tmp = Tmp.trunc(BitsInPreviousByte);
212
213 // We want the remaining low bits.
214 FieldValue.lshrInPlace(BitsInPreviousByte);
215 FieldValue = FieldValue.trunc(NewFieldWidth);
216 }
217 }
218
219 Tmp = Tmp.zext(CharWidth);
220 if (CGM.getDataLayout().isBigEndian()) {
221 if (FitsCompletelyInPreviousByte)
222 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
223 } else {
224 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
225 }
226
227 // 'or' in the bits that go into the previous byte.
228 llvm::Value *LastElt = Elements.back();
229 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
230 Tmp |= Val->getValue();
231 else {
232 assert(isa<llvm::UndefValue>(LastElt))((isa<llvm::UndefValue>(LastElt)) ? static_cast<void
> (0) : __assert_fail ("isa<llvm::UndefValue>(LastElt)"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 232, __PRETTY_FUNCTION__))
;
233 // If there is an undef field that we're adding to, it can either be a
234 // scalar undef (in which case, we just replace it with our field) or it
235 // is an array. If it is an array, we have to pull one byte off the
236 // array so that the other undef bytes stay around.
237 if (!isa<llvm::IntegerType>(LastElt->getType())) {
238 // The undef padding will be a multibyte array, create a new smaller
239 // padding and then an hole for our i8 to get plopped into.
240 assert(isa<llvm::ArrayType>(LastElt->getType()) &&((isa<llvm::ArrayType>(LastElt->getType()) &&
"Expected array padding of undefs") ? static_cast<void>
(0) : __assert_fail ("isa<llvm::ArrayType>(LastElt->getType()) && \"Expected array padding of undefs\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 241, __PRETTY_FUNCTION__))
241 "Expected array padding of undefs")((isa<llvm::ArrayType>(LastElt->getType()) &&
"Expected array padding of undefs") ? static_cast<void>
(0) : __assert_fail ("isa<llvm::ArrayType>(LastElt->getType()) && \"Expected array padding of undefs\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 241, __PRETTY_FUNCTION__))
;
242 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
243 assert(AT->getElementType()->isIntegerTy(CharWidth) &&((AT->getElementType()->isIntegerTy(CharWidth) &&
AT->getNumElements() != 0 && "Expected non-empty array padding of undefs"
) ? static_cast<void> (0) : __assert_fail ("AT->getElementType()->isIntegerTy(CharWidth) && AT->getNumElements() != 0 && \"Expected non-empty array padding of undefs\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 245, __PRETTY_FUNCTION__))
244 AT->getNumElements() != 0 &&((AT->getElementType()->isIntegerTy(CharWidth) &&
AT->getNumElements() != 0 && "Expected non-empty array padding of undefs"
) ? static_cast<void> (0) : __assert_fail ("AT->getElementType()->isIntegerTy(CharWidth) && AT->getNumElements() != 0 && \"Expected non-empty array padding of undefs\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 245, __PRETTY_FUNCTION__))
245 "Expected non-empty array padding of undefs")((AT->getElementType()->isIntegerTy(CharWidth) &&
AT->getNumElements() != 0 && "Expected non-empty array padding of undefs"
) ? static_cast<void> (0) : __assert_fail ("AT->getElementType()->isIntegerTy(CharWidth) && AT->getNumElements() != 0 && \"Expected non-empty array padding of undefs\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 245, __PRETTY_FUNCTION__))
;
246
247 // Remove the padding array.
248 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
249 Elements.pop_back();
250
251 // Add the padding back in two chunks.
252 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
253 AppendPadding(CharUnits::One());
254 assert(isa<llvm::UndefValue>(Elements.back()) &&((isa<llvm::UndefValue>(Elements.back()) && Elements
.back()->getType()->isIntegerTy(CharWidth) && "Padding addition didn't work right"
) ? static_cast<void> (0) : __assert_fail ("isa<llvm::UndefValue>(Elements.back()) && Elements.back()->getType()->isIntegerTy(CharWidth) && \"Padding addition didn't work right\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 256, __PRETTY_FUNCTION__))
255 Elements.back()->getType()->isIntegerTy(CharWidth) &&((isa<llvm::UndefValue>(Elements.back()) && Elements
.back()->getType()->isIntegerTy(CharWidth) && "Padding addition didn't work right"
) ? static_cast<void> (0) : __assert_fail ("isa<llvm::UndefValue>(Elements.back()) && Elements.back()->getType()->isIntegerTy(CharWidth) && \"Padding addition didn't work right\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 256, __PRETTY_FUNCTION__))
256 "Padding addition didn't work right")((isa<llvm::UndefValue>(Elements.back()) && Elements
.back()->getType()->isIntegerTy(CharWidth) && "Padding addition didn't work right"
) ? static_cast<void> (0) : __assert_fail ("isa<llvm::UndefValue>(Elements.back()) && Elements.back()->getType()->isIntegerTy(CharWidth) && \"Padding addition didn't work right\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 256, __PRETTY_FUNCTION__))
;
257 }
258 }
259
260 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
261
262 if (FitsCompletelyInPreviousByte)
263 return;
264 }
265
266 while (FieldValue.getBitWidth() > CharWidth) {
267 llvm::APInt Tmp;
268
269 if (CGM.getDataLayout().isBigEndian()) {
270 // We want the high bits.
271 Tmp =
272 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
273 } else {
274 // We want the low bits.
275 Tmp = FieldValue.trunc(CharWidth);
276
277 FieldValue.lshrInPlace(CharWidth);
278 }
279
280 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
281 ++NextFieldOffsetInChars;
282
283 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
284 }
285
286 assert(FieldValue.getBitWidth() > 0 &&((FieldValue.getBitWidth() > 0 && "Should have at least one bit left!"
) ? static_cast<void> (0) : __assert_fail ("FieldValue.getBitWidth() > 0 && \"Should have at least one bit left!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 287, __PRETTY_FUNCTION__))
287 "Should have at least one bit left!")((FieldValue.getBitWidth() > 0 && "Should have at least one bit left!"
) ? static_cast<void> (0) : __assert_fail ("FieldValue.getBitWidth() > 0 && \"Should have at least one bit left!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 287, __PRETTY_FUNCTION__))
;
288 assert(FieldValue.getBitWidth() <= CharWidth &&((FieldValue.getBitWidth() <= CharWidth && "Should not have more than a byte left!"
) ? static_cast<void> (0) : __assert_fail ("FieldValue.getBitWidth() <= CharWidth && \"Should not have more than a byte left!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 289, __PRETTY_FUNCTION__))
289 "Should not have more than a byte left!")((FieldValue.getBitWidth() <= CharWidth && "Should not have more than a byte left!"
) ? static_cast<void> (0) : __assert_fail ("FieldValue.getBitWidth() <= CharWidth && \"Should not have more than a byte left!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 289, __PRETTY_FUNCTION__))
;
290
291 if (FieldValue.getBitWidth() < CharWidth) {
292 if (CGM.getDataLayout().isBigEndian()) {
293 unsigned BitWidth = FieldValue.getBitWidth();
294
295 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
296 } else
297 FieldValue = FieldValue.zext(CharWidth);
298 }
299
300 // Append the last element.
301 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
302 FieldValue));
303 ++NextFieldOffsetInChars;
304}
305
306void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
307 if (PadSize.isZero())
308 return;
309
310 llvm::Type *Ty = CGM.Int8Ty;
311 if (PadSize > CharUnits::One())
312 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
313
314 llvm::Constant *C = llvm::UndefValue::get(Ty);
315 Elements.push_back(C);
316 assert(getAlignment(C) == CharUnits::One() &&((getAlignment(C) == CharUnits::One() && "Padding must have 1 byte alignment!"
) ? static_cast<void> (0) : __assert_fail ("getAlignment(C) == CharUnits::One() && \"Padding must have 1 byte alignment!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 317, __PRETTY_FUNCTION__))
317 "Padding must have 1 byte alignment!")((getAlignment(C) == CharUnits::One() && "Padding must have 1 byte alignment!"
) ? static_cast<void> (0) : __assert_fail ("getAlignment(C) == CharUnits::One() && \"Padding must have 1 byte alignment!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 317, __PRETTY_FUNCTION__))
;
318
319 NextFieldOffsetInChars += getSizeInChars(C);
320}
321
322void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
323 assert(NextFieldOffsetInChars <= RecordSize &&((NextFieldOffsetInChars <= RecordSize && "Size mismatch!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars <= RecordSize && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 324, __PRETTY_FUNCTION__))
324 "Size mismatch!")((NextFieldOffsetInChars <= RecordSize && "Size mismatch!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars <= RecordSize && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 324, __PRETTY_FUNCTION__))
;
325
326 AppendPadding(RecordSize - NextFieldOffsetInChars);
327}
328
329void ConstStructBuilder::ConvertStructToPacked() {
330 SmallVector<llvm::Constant *, 16> PackedElements;
331 CharUnits ElementOffsetInChars = CharUnits::Zero();
332
333 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
334 llvm::Constant *C = Elements[i];
335
336 CharUnits ElementAlign = CharUnits::fromQuantity(
337 CGM.getDataLayout().getABITypeAlignment(C->getType()));
338 CharUnits AlignedElementOffsetInChars =
339 ElementOffsetInChars.alignTo(ElementAlign);
340
341 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
342 // We need some padding.
343 CharUnits NumChars =
344 AlignedElementOffsetInChars - ElementOffsetInChars;
345
346 llvm::Type *Ty = CGM.Int8Ty;
347 if (NumChars > CharUnits::One())
348 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
349
350 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
351 PackedElements.push_back(Padding);
352 ElementOffsetInChars += getSizeInChars(Padding);
353 }
354
355 PackedElements.push_back(C);
356 ElementOffsetInChars += getSizeInChars(C);
357 }
358
359 assert(ElementOffsetInChars == NextFieldOffsetInChars &&((ElementOffsetInChars == NextFieldOffsetInChars && "Packing the struct changed its size!"
) ? static_cast<void> (0) : __assert_fail ("ElementOffsetInChars == NextFieldOffsetInChars && \"Packing the struct changed its size!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 360, __PRETTY_FUNCTION__))
360 "Packing the struct changed its size!")((ElementOffsetInChars == NextFieldOffsetInChars && "Packing the struct changed its size!"
) ? static_cast<void> (0) : __assert_fail ("ElementOffsetInChars == NextFieldOffsetInChars && \"Packing the struct changed its size!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 360, __PRETTY_FUNCTION__))
;
361
362 Elements.swap(PackedElements);
363 LLVMStructAlignment = CharUnits::One();
364 Packed = true;
365}
366
367bool ConstStructBuilder::Build(InitListExpr *ILE) {
368 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
369 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
370
371 unsigned FieldNo = 0;
372 unsigned ElementNo = 0;
373
374 // Bail out if we have base classes. We could support these, but they only
375 // arise in C++1z where we will have already constant folded most interesting
376 // cases. FIXME: There are still a few more cases we can handle this way.
377 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
378 if (CXXRD->getNumBases())
379 return false;
380
381 for (RecordDecl::field_iterator Field = RD->field_begin(),
382 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
383 // If this is a union, skip all the fields that aren't being initialized.
384 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
385 continue;
386
387 // Don't emit anonymous bitfields, they just affect layout.
388 if (Field->isUnnamedBitfield())
389 continue;
390
391 // Get the initializer. A struct can include fields without initializers,
392 // we just use explicit null values for them.
393 llvm::Constant *EltInit;
394 if (ElementNo < ILE->getNumInits())
395 EltInit = Emitter.tryEmitPrivateForMemory(ILE->getInit(ElementNo++),
396 Field->getType());
397 else
398 EltInit = Emitter.emitNullForMemory(Field->getType());
399
400 if (!EltInit)
401 return false;
402
403 if (!Field->isBitField()) {
404 // Handle non-bitfield members.
405 AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
406 } else {
407 // Otherwise we have a bitfield.
408 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
409 AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI);
410 } else {
411 // We are trying to initialize a bitfield with a non-trivial constant,
412 // this must require run-time code.
413 return false;
414 }
415 }
416 }
417
418 return true;
419}
420
421namespace {
422struct BaseInfo {
423 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
424 : Decl(Decl), Offset(Offset), Index(Index) {
425 }
426
427 const CXXRecordDecl *Decl;
428 CharUnits Offset;
429 unsigned Index;
430
431 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
432};
433}
434
435bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
436 bool IsPrimaryBase,
437 const CXXRecordDecl *VTableClass,
438 CharUnits Offset) {
439 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
440
441 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
442 // Add a vtable pointer, if we need one and it hasn't already been added.
443 if (CD->isDynamicClass() && !IsPrimaryBase) {
444 llvm::Constant *VTableAddressPoint =
445 CGM.getCXXABI().getVTableAddressPointForConstExpr(
446 BaseSubobject(CD, Offset), VTableClass);
447 AppendBytes(Offset, VTableAddressPoint);
448 }
449
450 // Accumulate and sort bases, in order to visit them in address order, which
451 // may not be the same as declaration order.
452 SmallVector<BaseInfo, 8> Bases;
453 Bases.reserve(CD->getNumBases());
454 unsigned BaseNo = 0;
455 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
456 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
457 assert(!Base->isVirtual() && "should not have virtual bases here")((!Base->isVirtual() && "should not have virtual bases here"
) ? static_cast<void> (0) : __assert_fail ("!Base->isVirtual() && \"should not have virtual bases here\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 457, __PRETTY_FUNCTION__))
;
458 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
459 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
460 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
461 }
462 llvm::stable_sort(Bases);
463
464 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
465 BaseInfo &Base = Bases[I];
466
467 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
468 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
469 VTableClass, Offset + Base.Offset);
470 }
471 }
472
473 unsigned FieldNo = 0;
474 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
475
476 for (RecordDecl::field_iterator Field = RD->field_begin(),
477 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
478 // If this is a union, skip all the fields that aren't being initialized.
479 if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
480 continue;
481
482 // Don't emit anonymous bitfields, they just affect layout.
483 if (Field->isUnnamedBitfield())
484 continue;
485
486 // Emit the value of the initializer.
487 const APValue &FieldValue =
488 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
489 llvm::Constant *EltInit =
490 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
491 if (!EltInit)
492 return false;
493
494 if (!Field->isBitField()) {
495 // Handle non-bitfield members.
496 AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
497 } else {
498 // Otherwise we have a bitfield.
499 AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
500 cast<llvm::ConstantInt>(EltInit));
501 }
502 }
503
504 return true;
505}
506
507llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
508 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
509 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
510
511 CharUnits LayoutSizeInChars = Layout.getSize();
512
513 if (NextFieldOffsetInChars > LayoutSizeInChars) {
514 // If the struct is bigger than the size of the record type,
515 // we must have a flexible array member at the end.
516 assert(RD->hasFlexibleArrayMember() &&((RD->hasFlexibleArrayMember() && "Must have flexible array member if struct is bigger than type!"
) ? static_cast<void> (0) : __assert_fail ("RD->hasFlexibleArrayMember() && \"Must have flexible array member if struct is bigger than type!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 517, __PRETTY_FUNCTION__))
517 "Must have flexible array member if struct is bigger than type!")((RD->hasFlexibleArrayMember() && "Must have flexible array member if struct is bigger than type!"
) ? static_cast<void> (0) : __assert_fail ("RD->hasFlexibleArrayMember() && \"Must have flexible array member if struct is bigger than type!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 517, __PRETTY_FUNCTION__))
;
518
519 // No tail padding is necessary.
520 } else {
521 // Append tail padding if necessary.
522 CharUnits LLVMSizeInChars =
523 NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
524
525 if (LLVMSizeInChars != LayoutSizeInChars)
526 AppendTailPadding(LayoutSizeInChars);
527
528 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
529
530 // Check if we need to convert the struct to a packed struct.
531 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
532 LLVMSizeInChars > LayoutSizeInChars) {
533 assert(!Packed && "Size mismatch!")((!Packed && "Size mismatch!") ? static_cast<void>
(0) : __assert_fail ("!Packed && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 533, __PRETTY_FUNCTION__))
;
534
535 ConvertStructToPacked();
536 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&((NextFieldOffsetInChars <= LayoutSizeInChars && "Converting to packed did not help!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars <= LayoutSizeInChars && \"Converting to packed did not help!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 537, __PRETTY_FUNCTION__))
537 "Converting to packed did not help!")((NextFieldOffsetInChars <= LayoutSizeInChars && "Converting to packed did not help!"
) ? static_cast<void> (0) : __assert_fail ("NextFieldOffsetInChars <= LayoutSizeInChars && \"Converting to packed did not help!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 537, __PRETTY_FUNCTION__))
;
538 }
539
540 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
541
542 assert(LayoutSizeInChars == LLVMSizeInChars &&((LayoutSizeInChars == LLVMSizeInChars && "Tail padding mismatch!"
) ? static_cast<void> (0) : __assert_fail ("LayoutSizeInChars == LLVMSizeInChars && \"Tail padding mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 543, __PRETTY_FUNCTION__))
543 "Tail padding mismatch!")((LayoutSizeInChars == LLVMSizeInChars && "Tail padding mismatch!"
) ? static_cast<void> (0) : __assert_fail ("LayoutSizeInChars == LLVMSizeInChars && \"Tail padding mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 543, __PRETTY_FUNCTION__))
;
544 }
545
546 // Pick the type to use. If the type is layout identical to the ConvertType
547 // type then use it, otherwise use whatever the builder produced for us.
548 llvm::StructType *STy =
549 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
550 Elements, Packed);
551 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
552 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
553 if (ValSTy->isLayoutIdentical(STy))
554 STy = ValSTy;
555 }
556
557 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
558
559 assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) ==((NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars
(Result) && "Size mismatch!") ? static_cast<void>
(0) : __assert_fail ("NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars(Result) && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 561, __PRETTY_FUNCTION__))
560 getSizeInChars(Result) &&((NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars
(Result) && "Size mismatch!") ? static_cast<void>
(0) : __assert_fail ("NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars(Result) && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 561, __PRETTY_FUNCTION__))
561 "Size mismatch!")((NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars
(Result) && "Size mismatch!") ? static_cast<void>
(0) : __assert_fail ("NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars(Result) && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 561, __PRETTY_FUNCTION__))
;
562
563 return Result;
564}
565
566llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
567 ConstExprEmitter *ExprEmitter,
568 llvm::Constant *Base,
569 InitListExpr *Updater,
570 QualType ValTy) {
571 ConstStructBuilder Builder(Emitter);
572 if (!Builder.Build(ExprEmitter, Base, Updater))
573 return nullptr;
574 return Builder.Finalize(ValTy);
575}
576
577llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
578 InitListExpr *ILE,
579 QualType ValTy) {
580 ConstStructBuilder Builder(Emitter);
581
582 if (!Builder.Build(ILE))
583 return nullptr;
584
585 return Builder.Finalize(ValTy);
586}
587
588llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
589 const APValue &Val,
590 QualType ValTy) {
591 ConstStructBuilder Builder(Emitter);
592
593 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
594 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
595 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
596 return nullptr;
597
598 return Builder.Finalize(ValTy);
599}
600
601
602//===----------------------------------------------------------------------===//
603// ConstExprEmitter
604//===----------------------------------------------------------------------===//
605
606static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
607 CodeGenFunction *CGF,
608 const CompoundLiteralExpr *E) {
609 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
610 if (llvm::GlobalVariable *Addr =
611 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
612 return ConstantAddress(Addr, Align);
613
614 LangAS addressSpace = E->getType().getAddressSpace();
615
616 ConstantEmitter emitter(CGM, CGF);
617 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
618 addressSpace, E->getType());
619 if (!C) {
620 assert(!E->isFileScope() &&((!E->isFileScope() && "file-scope compound literal did not have constant initializer!"
) ? static_cast<void> (0) : __assert_fail ("!E->isFileScope() && \"file-scope compound literal did not have constant initializer!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 621, __PRETTY_FUNCTION__))
621 "file-scope compound literal did not have constant initializer!")((!E->isFileScope() && "file-scope compound literal did not have constant initializer!"
) ? static_cast<void> (0) : __assert_fail ("!E->isFileScope() && \"file-scope compound literal did not have constant initializer!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 621, __PRETTY_FUNCTION__))
;
622 return ConstantAddress::invalid();
623 }
624
625 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
626 CGM.isTypeConstant(E->getType(), true),
627 llvm::GlobalValue::InternalLinkage,
628 C, ".compoundliteral", nullptr,
629 llvm::GlobalVariable::NotThreadLocal,
630 CGM.getContext().getTargetAddressSpace(addressSpace));
631 emitter.finalize(GV);
632 GV->setAlignment(Align.getQuantity());
633 CGM.setAddrOfConstantCompoundLiteral(E, GV);
634 return ConstantAddress(GV, Align);
635}
636
637static llvm::Constant *
638EmitArrayConstant(CodeGenModule &CGM, const ConstantArrayType *DestType,
639 llvm::Type *CommonElementType, unsigned ArrayBound,
640 SmallVectorImpl<llvm::Constant *> &Elements,
641 llvm::Constant *Filler) {
642 // Figure out how long the initial prefix of non-zero elements is.
643 unsigned NonzeroLength = ArrayBound;
644 if (Elements.size() < NonzeroLength && Filler->isNullValue())
13
Assuming the condition is true
14
Called C++ object pointer is null
645 NonzeroLength = Elements.size();
646 if (NonzeroLength == Elements.size()) {
647 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
648 --NonzeroLength;
649 }
650
651 if (NonzeroLength == 0) {
652 return llvm::ConstantAggregateZero::get(
653 CGM.getTypes().ConvertType(QualType(DestType, 0)));
654 }
655
656 // Add a zeroinitializer array filler if we have lots of trailing zeroes.
657 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
658 if (TrailingZeroes >= 8) {
659 assert(Elements.size() >= NonzeroLength &&((Elements.size() >= NonzeroLength && "missing initializer for non-zero element"
) ? static_cast<void> (0) : __assert_fail ("Elements.size() >= NonzeroLength && \"missing initializer for non-zero element\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 660, __PRETTY_FUNCTION__))
660 "missing initializer for non-zero element")((Elements.size() >= NonzeroLength && "missing initializer for non-zero element"
) ? static_cast<void> (0) : __assert_fail ("Elements.size() >= NonzeroLength && \"missing initializer for non-zero element\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 660, __PRETTY_FUNCTION__))
;
661
662 // If all the elements had the same type up to the trailing zeroes, emit a
663 // struct of two arrays (the nonzero data and the zeroinitializer).
664 if (CommonElementType && NonzeroLength >= 8) {
665 llvm::Constant *Initial = llvm::ConstantArray::get(
666 llvm::ArrayType::get(CommonElementType, NonzeroLength),
667 makeArrayRef(Elements).take_front(NonzeroLength));
668 Elements.resize(2);
669 Elements[0] = Initial;
670 } else {
671 Elements.resize(NonzeroLength + 1);
672 }
673
674 auto *FillerType =
675 CommonElementType
676 ? CommonElementType
677 : CGM.getTypes().ConvertType(DestType->getElementType());
678 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
679 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
680 CommonElementType = nullptr;
681 } else if (Elements.size() != ArrayBound) {
682 // Otherwise pad to the right size with the filler if necessary.
683 Elements.resize(ArrayBound, Filler);
684 if (Filler->getType() != CommonElementType)
685 CommonElementType = nullptr;
686 }
687
688 // If all elements have the same type, just emit an array constant.
689 if (CommonElementType)
690 return llvm::ConstantArray::get(
691 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
692
693 // We have mixed types. Use a packed struct.
694 llvm::SmallVector<llvm::Type *, 16> Types;
695 Types.reserve(Elements.size());
696 for (llvm::Constant *Elt : Elements)
697 Types.push_back(Elt->getType());
698 llvm::StructType *SType =
699 llvm::StructType::get(CGM.getLLVMContext(), Types, true);
700 return llvm::ConstantStruct::get(SType, Elements);
701}
702
703// This class only needs to handle arrays, structs and unions. Outside C++11
704// mode, we don't currently constant fold those types. All other types are
705// handled by constant folding.
706//
707// Constant folding is currently missing support for a few features supported
708// here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
709class ConstExprEmitter :
710 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
711 CodeGenModule &CGM;
712 ConstantEmitter &Emitter;
713 llvm::LLVMContext &VMContext;
714public:
715 ConstExprEmitter(ConstantEmitter &emitter)
716 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
717 }
718
719 //===--------------------------------------------------------------------===//
720 // Visitor Methods
721 //===--------------------------------------------------------------------===//
722
723 llvm::Constant *VisitStmt(Stmt *S, QualType T) {
724 return nullptr;
725 }
726
727 llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
728 return Visit(CE->getSubExpr(), T);
729 }
730
731 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
732 return Visit(PE->getSubExpr(), T);
733 }
734
735 llvm::Constant *
736 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
737 QualType T) {
738 return Visit(PE->getReplacement(), T);
739 }
740
741 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
742 QualType T) {
743 return Visit(GE->getResultExpr(), T);
744 }
745
746 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
747 return Visit(CE->getChosenSubExpr(), T);
748 }
749
750 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
751 return Visit(E->getInitializer(), T);
752 }
753
754 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
755 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
756 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
757 Expr *subExpr = E->getSubExpr();
758
759 switch (E->getCastKind()) {
760 case CK_ToUnion: {
761 // GCC cast to union extension
762 assert(E->getType()->isUnionType() &&((E->getType()->isUnionType() && "Destination type is not union type!"
) ? static_cast<void> (0) : __assert_fail ("E->getType()->isUnionType() && \"Destination type is not union type!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 763, __PRETTY_FUNCTION__))
763 "Destination type is not union type!")((E->getType()->isUnionType() && "Destination type is not union type!"
) ? static_cast<void> (0) : __assert_fail ("E->getType()->isUnionType() && \"Destination type is not union type!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 763, __PRETTY_FUNCTION__))
;
764
765 auto field = E->getTargetUnionField();
766
767 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
768 if (!C) return nullptr;
769
770 auto destTy = ConvertType(destType);
771 if (C->getType() == destTy) return C;
772
773 // Build a struct with the union sub-element as the first member,
774 // and padded to the appropriate size.
775 SmallVector<llvm::Constant*, 2> Elts;
776 SmallVector<llvm::Type*, 2> Types;
777 Elts.push_back(C);
778 Types.push_back(C->getType());
779 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
780 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
781
782 assert(CurSize <= TotalSize && "Union size mismatch!")((CurSize <= TotalSize && "Union size mismatch!") ?
static_cast<void> (0) : __assert_fail ("CurSize <= TotalSize && \"Union size mismatch!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 782, __PRETTY_FUNCTION__))
;
783 if (unsigned NumPadBytes = TotalSize - CurSize) {
784 llvm::Type *Ty = CGM.Int8Ty;
785 if (NumPadBytes > 1)
786 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
787
788 Elts.push_back(llvm::UndefValue::get(Ty));
789 Types.push_back(Ty);
790 }
791
792 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
793 return llvm::ConstantStruct::get(STy, Elts);
794 }
795
796 case CK_AddressSpaceConversion: {
797 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
798 if (!C) return nullptr;
799 LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
800 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
801 llvm::Type *destTy = ConvertType(E->getType());
802 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
803 destAS, destTy);
804 }
805
806 case CK_LValueToRValue:
807 case CK_AtomicToNonAtomic:
808 case CK_NonAtomicToAtomic:
809 case CK_NoOp:
810 case CK_ConstructorConversion:
811 return Visit(subExpr, destType);
812
813 case CK_IntToOCLSampler:
814 llvm_unreachable("global sampler variables are not generated")::llvm::llvm_unreachable_internal("global sampler variables are not generated"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 814)
;
815
816 case CK_Dependent: llvm_unreachable("saw dependent cast!")::llvm::llvm_unreachable_internal("saw dependent cast!", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 816)
;
817
818 case CK_BuiltinFnToFnPtr:
819 llvm_unreachable("builtin functions are handled elsewhere")::llvm::llvm_unreachable_internal("builtin functions are handled elsewhere"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 819)
;
820
821 case CK_ReinterpretMemberPointer:
822 case CK_DerivedToBaseMemberPointer:
823 case CK_BaseToDerivedMemberPointer: {
824 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
825 if (!C) return nullptr;
826 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
827 }
828
829 // These will never be supported.
830 case CK_ObjCObjectLValueCast:
831 case CK_ARCProduceObject:
832 case CK_ARCConsumeObject:
833 case CK_ARCReclaimReturnedObject:
834 case CK_ARCExtendBlockObject:
835 case CK_CopyAndAutoreleaseBlockObject:
836 return nullptr;
837
838 // These don't need to be handled here because Evaluate knows how to
839 // evaluate them in the cases where they can be folded.
840 case CK_BitCast:
841 case CK_ToVoid:
842 case CK_Dynamic:
843 case CK_LValueBitCast:
844 case CK_NullToMemberPointer:
845 case CK_UserDefinedConversion:
846 case CK_CPointerToObjCPointerCast:
847 case CK_BlockPointerToObjCPointerCast:
848 case CK_AnyPointerToBlockPointerCast:
849 case CK_ArrayToPointerDecay:
850 case CK_FunctionToPointerDecay:
851 case CK_BaseToDerived:
852 case CK_DerivedToBase:
853 case CK_UncheckedDerivedToBase:
854 case CK_MemberPointerToBoolean:
855 case CK_VectorSplat:
856 case CK_FloatingRealToComplex:
857 case CK_FloatingComplexToReal:
858 case CK_FloatingComplexToBoolean:
859 case CK_FloatingComplexCast:
860 case CK_FloatingComplexToIntegralComplex:
861 case CK_IntegralRealToComplex:
862 case CK_IntegralComplexToReal:
863 case CK_IntegralComplexToBoolean:
864 case CK_IntegralComplexCast:
865 case CK_IntegralComplexToFloatingComplex:
866 case CK_PointerToIntegral:
867 case CK_PointerToBoolean:
868 case CK_NullToPointer:
869 case CK_IntegralCast:
870 case CK_BooleanToSignedIntegral:
871 case CK_IntegralToPointer:
872 case CK_IntegralToBoolean:
873 case CK_IntegralToFloating:
874 case CK_FloatingToIntegral:
875 case CK_FloatingToBoolean:
876 case CK_FloatingCast:
877 case CK_FixedPointCast:
878 case CK_FixedPointToBoolean:
879 case CK_FixedPointToIntegral:
880 case CK_IntegralToFixedPoint:
881 case CK_ZeroToOCLOpaqueType:
882 return nullptr;
883 }
884 llvm_unreachable("Invalid CastKind")::llvm::llvm_unreachable_internal("Invalid CastKind", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 884)
;
885 }
886
887 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
888 // No need for a DefaultInitExprScope: we don't handle 'this' in a
889 // constant expression.
890 return Visit(DIE->getExpr(), T);
891 }
892
893 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
894 if (!E->cleanupsHaveSideEffects())
895 return Visit(E->getSubExpr(), T);
896 return nullptr;
897 }
898
899 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
900 QualType T) {
901 return Visit(E->GetTemporaryExpr(), T);
902 }
903
904 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
905 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
906 assert(CAT && "can't emit array init for non-constant-bound array")((CAT && "can't emit array init for non-constant-bound array"
) ? static_cast<void> (0) : __assert_fail ("CAT && \"can't emit array init for non-constant-bound array\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 906, __PRETTY_FUNCTION__))
;
5
'?' condition is true
907 unsigned NumInitElements = ILE->getNumInits();
908 unsigned NumElements = CAT->getSize().getZExtValue();
909
910 // Initialising an array requires us to automatically
911 // initialise any elements that have not been initialised explicitly
912 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
913
914 QualType EltType = CAT->getElementType();
915
916 // Initialize remaining array elements.
917 llvm::Constant *fillC = nullptr;
6
'fillC' initialized to a null pointer value
918 if (Expr *filler = ILE->getArrayFiller()) {
7
Assuming 'filler' is null
8
Taking false branch
919 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
920 if (!fillC)
921 return nullptr;
922 }
923
924 // Copy initializer elements.
925 SmallVector<llvm::Constant*, 16> Elts;
926 if (fillC && fillC->isNullValue())
927 Elts.reserve(NumInitableElts + 1);
928 else
929 Elts.reserve(NumElements);
930
931 llvm::Type *CommonElementType = nullptr;
932 for (unsigned i = 0; i < NumInitableElts; ++i) {
9
Assuming 'i' is >= 'NumInitableElts'
10
Loop condition is false. Execution continues on line 944
933 Expr *Init = ILE->getInit(i);
934 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
935 if (!C)
936 return nullptr;
937 if (i == 0)
938 CommonElementType = C->getType();
939 else if (C->getType() != CommonElementType)
940 CommonElementType = nullptr;
941 Elts.push_back(C);
942 }
943
944 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
12
Calling 'EmitArrayConstant'
945 fillC);
11
Passing null pointer value via 6th parameter 'Filler'
946 }
947
948 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
949 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
950 }
951
952 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
953 QualType T) {
954 return CGM.EmitNullConstant(T);
955 }
956
957 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
958 if (ILE->isTransparent())
1
Assuming the condition is false
2
Taking false branch
959 return Visit(ILE->getInit(0), T);
960
961 if (ILE->getType()->isArrayType())
3
Taking true branch
962 return EmitArrayInitialization(ILE, T);
4
Calling 'ConstExprEmitter::EmitArrayInitialization'
963
964 if (ILE->getType()->isRecordType())
965 return EmitRecordInitialization(ILE, T);
966
967 return nullptr;
968 }
969
970 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
971 InitListExpr *Updater,
972 QualType destType) {
973 if (auto destAT = CGM.getContext().getAsArrayType(destType)) {
974 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
975 llvm::Type *ElemType = AType->getElementType();
976
977 unsigned NumInitElements = Updater->getNumInits();
978 unsigned NumElements = AType->getNumElements();
979
980 std::vector<llvm::Constant *> Elts;
981 Elts.reserve(NumElements);
982
983 QualType destElemType = destAT->getElementType();
984
985 if (auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
986 for (unsigned i = 0; i != NumElements; ++i)
987 Elts.push_back(DataArray->getElementAsConstant(i));
988 else if (auto Array = dyn_cast<llvm::ConstantArray>(Base))
989 for (unsigned i = 0; i != NumElements; ++i)
990 Elts.push_back(Array->getOperand(i));
991 else
992 return nullptr; // FIXME: other array types not implemented
993
994 llvm::Constant *fillC = nullptr;
995 if (Expr *filler = Updater->getArrayFiller())
996 if (!isa<NoInitExpr>(filler))
997 fillC = Emitter.tryEmitAbstractForMemory(filler, destElemType);
998 bool RewriteType = (fillC && fillC->getType() != ElemType);
999
1000 for (unsigned i = 0; i != NumElements; ++i) {
1001 Expr *Init = nullptr;
1002 if (i < NumInitElements)
1003 Init = Updater->getInit(i);
1004
1005 if (!Init && fillC)
1006 Elts[i] = fillC;
1007 else if (!Init || isa<NoInitExpr>(Init))
1008 ; // Do nothing.
1009 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1010 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
1011 else
1012 Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType);
1013
1014 if (!Elts[i])
1015 return nullptr;
1016 RewriteType |= (Elts[i]->getType() != ElemType);
1017 }
1018
1019 if (RewriteType) {
1020 std::vector<llvm::Type *> Types;
1021 Types.reserve(NumElements);
1022 for (unsigned i = 0; i != NumElements; ++i)
1023 Types.push_back(Elts[i]->getType());
1024 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
1025 Types, true);
1026 return llvm::ConstantStruct::get(SType, Elts);
1027 }
1028
1029 return llvm::ConstantArray::get(AType, Elts);
1030 }
1031
1032 if (destType->isRecordType())
1033 return ConstStructBuilder::BuildStruct(Emitter, this, Base, Updater,
1034 destType);
1035
1036 return nullptr;
1037 }
1038
1039 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1040 QualType destType) {
1041 auto C = Visit(E->getBase(), destType);
1042 if (!C) return nullptr;
1043 return EmitDesignatedInitUpdater(C, E->getUpdater(), destType);
1044 }
1045
1046 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
1047 if (!E->getConstructor()->isTrivial())
1048 return nullptr;
1049
1050 // FIXME: We should not have to call getBaseElementType here.
1051 const RecordType *RT =
1052 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1053 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1054
1055 // If the class doesn't have a trivial destructor, we can't emit it as a
1056 // constant expr.
1057 if (!RD->hasTrivialDestructor())
1058 return nullptr;
1059
1060 // Only copy and default constructors can be trivial.
1061
1062
1063 if (E->getNumArgs()) {
1064 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument")((E->getNumArgs() == 1 && "trivial ctor with > 1 argument"
) ? static_cast<void> (0) : __assert_fail ("E->getNumArgs() == 1 && \"trivial ctor with > 1 argument\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1064, __PRETTY_FUNCTION__))
;
1065 assert(E->getConstructor()->isCopyOrMoveConstructor() &&((E->getConstructor()->isCopyOrMoveConstructor() &&
"trivial ctor has argument but isn't a copy/move ctor") ? static_cast
<void> (0) : __assert_fail ("E->getConstructor()->isCopyOrMoveConstructor() && \"trivial ctor has argument but isn't a copy/move ctor\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1066, __PRETTY_FUNCTION__))
1066 "trivial ctor has argument but isn't a copy/move ctor")((E->getConstructor()->isCopyOrMoveConstructor() &&
"trivial ctor has argument but isn't a copy/move ctor") ? static_cast
<void> (0) : __assert_fail ("E->getConstructor()->isCopyOrMoveConstructor() && \"trivial ctor has argument but isn't a copy/move ctor\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1066, __PRETTY_FUNCTION__))
;
1067
1068 Expr *Arg = E->getArg(0);
1069 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&((CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType
()) && "argument to copy ctor is of wrong type") ? static_cast
<void> (0) : __assert_fail ("CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) && \"argument to copy ctor is of wrong type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1070, __PRETTY_FUNCTION__))
1070 "argument to copy ctor is of wrong type")((CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType
()) && "argument to copy ctor is of wrong type") ? static_cast
<void> (0) : __assert_fail ("CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) && \"argument to copy ctor is of wrong type\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1070, __PRETTY_FUNCTION__))
;
1071
1072 return Visit(Arg, Ty);
1073 }
1074
1075 return CGM.EmitNullConstant(Ty);
1076 }
1077
1078 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
1079 // This is a string literal initializing an array in an initializer.
1080 return CGM.GetConstantArrayFromStringLiteral(E);
1081 }
1082
1083 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
1084 // This must be an @encode initializing an array in a static initializer.
1085 // Don't emit it as the address of the string, emit the string data itself
1086 // as an inline array.
1087 std::string Str;
1088 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1089 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1090
1091 // Resize the string to the right size, adding zeros at the end, or
1092 // truncating as needed.
1093 Str.resize(CAT->getSize().getZExtValue(), '\0');
1094 return llvm::ConstantDataArray::getString(VMContext, Str, false);
1095 }
1096
1097 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1098 return Visit(E->getSubExpr(), T);
1099 }
1100
1101 // Utility methods
1102 llvm::Type *ConvertType(QualType T) {
1103 return CGM.getTypes().ConvertType(T);
1104 }
1105};
1106
1107} // end anonymous namespace.
1108
1109bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
1110 llvm::Constant *Base,
1111 InitListExpr *Updater) {
1112 assert(Base && "base expression should not be empty")((Base && "base expression should not be empty") ? static_cast
<void> (0) : __assert_fail ("Base && \"base expression should not be empty\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1112, __PRETTY_FUNCTION__))
;
1113
1114 QualType ExprType = Updater->getType();
1115 RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
1116 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1117 const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
1118 cast<llvm::StructType>(Base->getType()));
1119 unsigned FieldNo = -1;
1120 unsigned ElementNo = 0;
1121
1122 // Bail out if we have base classes. We could support these, but they only
1123 // arise in C++1z where we will have already constant folded most interesting
1124 // cases. FIXME: There are still a few more cases we can handle this way.
1125 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1126 if (CXXRD->getNumBases())
1127 return false;
1128
1129 for (FieldDecl *Field : RD->fields()) {
1130 ++FieldNo;
1131
1132 if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
1133 continue;
1134
1135 // Skip anonymous bitfields.
1136 if (Field->isUnnamedBitfield())
1137 continue;
1138
1139 llvm::Constant *EltInit = Base->getAggregateElement(ElementNo);
1140
1141 // Bail out if the type of the ConstantStruct does not have the same layout
1142 // as the type of the InitListExpr.
1143 if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
1144 Layout.getFieldOffset(ElementNo) !=
1145 BaseLayout->getElementOffsetInBits(ElementNo))
1146 return false;
1147
1148 // Get the initializer. If we encounter an empty field or a NoInitExpr,
1149 // we use values from the base expression.
1150 Expr *Init = nullptr;
1151 if (ElementNo < Updater->getNumInits())
1152 Init = Updater->getInit(ElementNo);
1153
1154 if (!Init || isa<NoInitExpr>(Init))
1155 ; // Do nothing.
1156 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1157 EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1158 Field->getType());
1159 else
1160 EltInit = Emitter.tryEmitPrivateForMemory(Init, Field->getType());
1161
1162 ++ElementNo;
1163
1164 if (!EltInit)
1165 return false;
1166
1167 if (!Field->isBitField())
1168 AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
1169 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1170 AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
1171 else
1172 // Initializing a bitfield with a non-trivial constant?
1173 return false;
1174 }
1175
1176 return true;
1177}
1178
1179llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1180 AbstractState saved) {
1181 Abstract = saved.OldValue;
1182
1183 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&((saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
"created a placeholder while doing an abstract emission?") ?
static_cast<void> (0) : __assert_fail ("saved.OldPlaceholdersSize == PlaceholderAddresses.size() && \"created a placeholder while doing an abstract emission?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1184, __PRETTY_FUNCTION__))
1184 "created a placeholder while doing an abstract emission?")((saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
"created a placeholder while doing an abstract emission?") ?
static_cast<void> (0) : __assert_fail ("saved.OldPlaceholdersSize == PlaceholderAddresses.size() && \"created a placeholder while doing an abstract emission?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1184, __PRETTY_FUNCTION__))
;
1185
1186 // No validation necessary for now.
1187 // No cleanup to do for now.
1188 return C;
1189}
1190
1191llvm::Constant *
1192ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1193 auto state = pushAbstract();
1194 auto C = tryEmitPrivateForVarInit(D);
1195 return validateAndPopAbstract(C, state);
1196}
1197
1198llvm::Constant *
1199ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1200 auto state = pushAbstract();
1201 auto C = tryEmitPrivate(E, destType);
1202 return validateAndPopAbstract(C, state);
1203}
1204
1205llvm::Constant *
1206ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1207 auto state = pushAbstract();
1208 auto C = tryEmitPrivate(value, destType);
1209 return validateAndPopAbstract(C, state);
1210}
1211
1212llvm::Constant *
1213ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1214 auto state = pushAbstract();
1215 auto C = tryEmitPrivate(E, destType);
1216 C = validateAndPopAbstract(C, state);
1217 if (!C) {
1218 CGM.Error(E->getExprLoc(),
1219 "internal error: could not emit constant value \"abstractly\"");
1220 C = CGM.EmitNullConstant(destType);
1221 }
1222 return C;
1223}
1224
1225llvm::Constant *
1226ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1227 QualType destType) {
1228 auto state = pushAbstract();
1229 auto C = tryEmitPrivate(value, destType);
1230 C = validateAndPopAbstract(C, state);
1231 if (!C) {
1232 CGM.Error(loc,
1233 "internal error: could not emit constant value \"abstractly\"");
1234 C = CGM.EmitNullConstant(destType);
1235 }
1236 return C;
1237}
1238
1239llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1240 initializeNonAbstract(D.getType().getAddressSpace());
1241 return markIfFailed(tryEmitPrivateForVarInit(D));
1242}
1243
1244llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1245 LangAS destAddrSpace,
1246 QualType destType) {
1247 initializeNonAbstract(destAddrSpace);
1248 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1249}
1250
1251llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1252 LangAS destAddrSpace,
1253 QualType destType) {
1254 initializeNonAbstract(destAddrSpace);
1255 auto C = tryEmitPrivateForMemory(value, destType);
1256 assert(C && "couldn't emit constant value non-abstractly?")((C && "couldn't emit constant value non-abstractly?"
) ? static_cast<void> (0) : __assert_fail ("C && \"couldn't emit constant value non-abstractly?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1256, __PRETTY_FUNCTION__))
;
1257 return C;
1258}
1259
1260llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1261 assert(!Abstract && "cannot get current address for abstract constant")((!Abstract && "cannot get current address for abstract constant"
) ? static_cast<void> (0) : __assert_fail ("!Abstract && \"cannot get current address for abstract constant\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1261, __PRETTY_FUNCTION__))
;
1262
1263
1264
1265 // Make an obviously ill-formed global that should blow up compilation
1266 // if it survives.
1267 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1268 llvm::GlobalValue::PrivateLinkage,
1269 /*init*/ nullptr,
1270 /*name*/ "",
1271 /*before*/ nullptr,
1272 llvm::GlobalVariable::NotThreadLocal,
1273 CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1274
1275 PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1276
1277 return global;
1278}
1279
1280void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1281 llvm::GlobalValue *placeholder) {
1282 assert(!PlaceholderAddresses.empty())((!PlaceholderAddresses.empty()) ? static_cast<void> (0
) : __assert_fail ("!PlaceholderAddresses.empty()", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1282, __PRETTY_FUNCTION__))
;
1283 assert(PlaceholderAddresses.back().first == nullptr)((PlaceholderAddresses.back().first == nullptr) ? static_cast
<void> (0) : __assert_fail ("PlaceholderAddresses.back().first == nullptr"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1283, __PRETTY_FUNCTION__))
;
1284 assert(PlaceholderAddresses.back().second == placeholder)((PlaceholderAddresses.back().second == placeholder) ? static_cast
<void> (0) : __assert_fail ("PlaceholderAddresses.back().second == placeholder"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1284, __PRETTY_FUNCTION__))
;
1285 PlaceholderAddresses.back().first = signal;
1286}
1287
1288namespace {
1289 struct ReplacePlaceholders {
1290 CodeGenModule &CGM;
1291
1292 /// The base address of the global.
1293 llvm::Constant *Base;
1294 llvm::Type *BaseValueTy = nullptr;
1295
1296 /// The placeholder addresses that were registered during emission.
1297 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1298
1299 /// The locations of the placeholder signals.
1300 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1301
1302 /// The current index stack. We use a simple unsigned stack because
1303 /// we assume that placeholders will be relatively sparse in the
1304 /// initializer, but we cache the index values we find just in case.
1305 llvm::SmallVector<unsigned, 8> Indices;
1306 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1307
1308 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1309 ArrayRef<std::pair<llvm::Constant*,
1310 llvm::GlobalVariable*>> addresses)
1311 : CGM(CGM), Base(base),
1312 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1313 }
1314
1315 void replaceInInitializer(llvm::Constant *init) {
1316 // Remember the type of the top-most initializer.
1317 BaseValueTy = init->getType();
1318
1319 // Initialize the stack.
1320 Indices.push_back(0);
1321 IndexValues.push_back(nullptr);
1322
1323 // Recurse into the initializer.
1324 findLocations(init);
1325
1326 // Check invariants.
1327 assert(IndexValues.size() == Indices.size() && "mismatch")((IndexValues.size() == Indices.size() && "mismatch")
? static_cast<void> (0) : __assert_fail ("IndexValues.size() == Indices.size() && \"mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1327, __PRETTY_FUNCTION__))
;
1328 assert(Indices.size() == 1 && "didn't pop all indices")((Indices.size() == 1 && "didn't pop all indices") ? static_cast
<void> (0) : __assert_fail ("Indices.size() == 1 && \"didn't pop all indices\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1328, __PRETTY_FUNCTION__))
;
1329
1330 // Do the replacement; this basically invalidates 'init'.
1331 assert(Locations.size() == PlaceholderAddresses.size() &&((Locations.size() == PlaceholderAddresses.size() && "missed a placeholder?"
) ? static_cast<void> (0) : __assert_fail ("Locations.size() == PlaceholderAddresses.size() && \"missed a placeholder?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1332, __PRETTY_FUNCTION__))
1332 "missed a placeholder?")((Locations.size() == PlaceholderAddresses.size() && "missed a placeholder?"
) ? static_cast<void> (0) : __assert_fail ("Locations.size() == PlaceholderAddresses.size() && \"missed a placeholder?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1332, __PRETTY_FUNCTION__))
;
1333
1334 // We're iterating over a hashtable, so this would be a source of
1335 // non-determinism in compiler output *except* that we're just
1336 // messing around with llvm::Constant structures, which never itself
1337 // does anything that should be visible in compiler output.
1338 for (auto &entry : Locations) {
1339 assert(entry.first->getParent() == nullptr && "not a placeholder!")((entry.first->getParent() == nullptr && "not a placeholder!"
) ? static_cast<void> (0) : __assert_fail ("entry.first->getParent() == nullptr && \"not a placeholder!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1339, __PRETTY_FUNCTION__))
;
1340 entry.first->replaceAllUsesWith(entry.second);
1341 entry.first->eraseFromParent();
1342 }
1343 }
1344
1345 private:
1346 void findLocations(llvm::Constant *init) {
1347 // Recurse into aggregates.
1348 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1349 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1350 Indices.push_back(i);
1351 IndexValues.push_back(nullptr);
1352
1353 findLocations(agg->getOperand(i));
1354
1355 IndexValues.pop_back();
1356 Indices.pop_back();
1357 }
1358 return;
1359 }
1360
1361 // Otherwise, check for registered constants.
1362 while (true) {
1363 auto it = PlaceholderAddresses.find(init);
1364 if (it != PlaceholderAddresses.end()) {
1365 setLocation(it->second);
1366 break;
1367 }
1368
1369 // Look through bitcasts or other expressions.
1370 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1371 init = expr->getOperand(0);
1372 } else {
1373 break;
1374 }
1375 }
1376 }
1377
1378 void setLocation(llvm::GlobalVariable *placeholder) {
1379 assert(Locations.find(placeholder) == Locations.end() &&((Locations.find(placeholder) == Locations.end() && "already found location for placeholder!"
) ? static_cast<void> (0) : __assert_fail ("Locations.find(placeholder) == Locations.end() && \"already found location for placeholder!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1380, __PRETTY_FUNCTION__))
1380 "already found location for placeholder!")((Locations.find(placeholder) == Locations.end() && "already found location for placeholder!"
) ? static_cast<void> (0) : __assert_fail ("Locations.find(placeholder) == Locations.end() && \"already found location for placeholder!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1380, __PRETTY_FUNCTION__))
;
1381
1382 // Lazily fill in IndexValues with the values from Indices.
1383 // We do this in reverse because we should always have a strict
1384 // prefix of indices from the start.
1385 assert(Indices.size() == IndexValues.size())((Indices.size() == IndexValues.size()) ? static_cast<void
> (0) : __assert_fail ("Indices.size() == IndexValues.size()"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1385, __PRETTY_FUNCTION__))
;
1386 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1387 if (IndexValues[i]) {
1388#ifndef NDEBUG
1389 for (size_t j = 0; j != i + 1; ++j) {
1390 assert(IndexValues[j] &&((IndexValues[j] && isa<llvm::ConstantInt>(IndexValues
[j]) && cast<llvm::ConstantInt>(IndexValues[j])
->getZExtValue() == Indices[j]) ? static_cast<void> (
0) : __assert_fail ("IndexValues[j] && isa<llvm::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() == Indices[j]"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1393, __PRETTY_FUNCTION__))
1391 isa<llvm::ConstantInt>(IndexValues[j]) &&((IndexValues[j] && isa<llvm::ConstantInt>(IndexValues
[j]) && cast<llvm::ConstantInt>(IndexValues[j])
->getZExtValue() == Indices[j]) ? static_cast<void> (
0) : __assert_fail ("IndexValues[j] && isa<llvm::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() == Indices[j]"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1393, __PRETTY_FUNCTION__))
1392 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()((IndexValues[j] && isa<llvm::ConstantInt>(IndexValues
[j]) && cast<llvm::ConstantInt>(IndexValues[j])
->getZExtValue() == Indices[j]) ? static_cast<void> (
0) : __assert_fail ("IndexValues[j] && isa<llvm::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() == Indices[j]"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1393, __PRETTY_FUNCTION__))
1393 == Indices[j])((IndexValues[j] && isa<llvm::ConstantInt>(IndexValues
[j]) && cast<llvm::ConstantInt>(IndexValues[j])
->getZExtValue() == Indices[j]) ? static_cast<void> (
0) : __assert_fail ("IndexValues[j] && isa<llvm::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() == Indices[j]"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1393, __PRETTY_FUNCTION__))
;
1394 }
1395#endif
1396 break;
1397 }
1398
1399 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1400 }
1401
1402 // Form a GEP and then bitcast to the placeholder type so that the
1403 // replacement will succeed.
1404 llvm::Constant *location =
1405 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1406 Base, IndexValues);
1407 location = llvm::ConstantExpr::getBitCast(location,
1408 placeholder->getType());
1409
1410 Locations.insert({placeholder, location});
1411 }
1412 };
1413}
1414
1415void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1416 assert(InitializedNonAbstract &&((InitializedNonAbstract && "finalizing emitter that was used for abstract emission?"
) ? static_cast<void> (0) : __assert_fail ("InitializedNonAbstract && \"finalizing emitter that was used for abstract emission?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1417, __PRETTY_FUNCTION__))
1417 "finalizing emitter that was used for abstract emission?")((InitializedNonAbstract && "finalizing emitter that was used for abstract emission?"
) ? static_cast<void> (0) : __assert_fail ("InitializedNonAbstract && \"finalizing emitter that was used for abstract emission?\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1417, __PRETTY_FUNCTION__))
;
1418 assert(!Finalized && "finalizing emitter multiple times")((!Finalized && "finalizing emitter multiple times") ?
static_cast<void> (0) : __assert_fail ("!Finalized && \"finalizing emitter multiple times\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1418, __PRETTY_FUNCTION__))
;
1419 assert(global->getInitializer())((global->getInitializer()) ? static_cast<void> (0) :
__assert_fail ("global->getInitializer()", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1419, __PRETTY_FUNCTION__))
;
1420
1421 // Note that we might also be Failed.
1422 Finalized = true;
1423
1424 if (!PlaceholderAddresses.empty()) {
1425 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1426 .replaceInInitializer(global->getInitializer());
1427 PlaceholderAddresses.clear(); // satisfy
1428 }
1429}
1430
1431ConstantEmitter::~ConstantEmitter() {
1432 assert((!InitializedNonAbstract || Finalized || Failed) &&(((!InitializedNonAbstract || Finalized || Failed) &&
"not finalized after being initialized for non-abstract emission"
) ? static_cast<void> (0) : __assert_fail ("(!InitializedNonAbstract || Finalized || Failed) && \"not finalized after being initialized for non-abstract emission\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1433, __PRETTY_FUNCTION__))
1433 "not finalized after being initialized for non-abstract emission")(((!InitializedNonAbstract || Finalized || Failed) &&
"not finalized after being initialized for non-abstract emission"
) ? static_cast<void> (0) : __assert_fail ("(!InitializedNonAbstract || Finalized || Failed) && \"not finalized after being initialized for non-abstract emission\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1433, __PRETTY_FUNCTION__))
;
1434 assert(PlaceholderAddresses.empty() && "unhandled placeholders")((PlaceholderAddresses.empty() && "unhandled placeholders"
) ? static_cast<void> (0) : __assert_fail ("PlaceholderAddresses.empty() && \"unhandled placeholders\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1434, __PRETTY_FUNCTION__))
;
1435}
1436
1437static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1438 if (auto AT = type->getAs<AtomicType>()) {
1439 return CGM.getContext().getQualifiedType(AT->getValueType(),
1440 type.getQualifiers());
1441 }
1442 return type;
1443}
1444
1445llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1446 // Make a quick check if variable can be default NULL initialized
1447 // and avoid going through rest of code which may do, for c++11,
1448 // initialization of memory to all NULLs.
1449 if (!D.hasLocalStorage()) {
1450 QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1451 if (Ty->isRecordType())
1452 if (const CXXConstructExpr *E =
1453 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1454 const CXXConstructorDecl *CD = E->getConstructor();
1455 if (CD->isTrivial() && CD->isDefaultConstructor())
1456 return CGM.EmitNullConstant(D.getType());
1457 }
1458 InConstantContext = true;
1459 }
1460
1461 QualType destType = D.getType();
1462
1463 // Try to emit the initializer. Note that this can allow some things that
1464 // are not allowed by tryEmitPrivateForMemory alone.
1465 if (auto value = D.evaluateValue()) {
1466 return tryEmitPrivateForMemory(*value, destType);
1467 }
1468
1469 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1470 // reference is a constant expression, and the reference binds to a temporary,
1471 // then constant initialization is performed. ConstExprEmitter will
1472 // incorrectly emit a prvalue constant in this case, and the calling code
1473 // interprets that as the (pointer) value of the reference, rather than the
1474 // desired value of the referee.
1475 if (destType->isReferenceType())
1476 return nullptr;
1477
1478 const Expr *E = D.getInit();
1479 assert(E && "No initializer to emit")((E && "No initializer to emit") ? static_cast<void
> (0) : __assert_fail ("E && \"No initializer to emit\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1479, __PRETTY_FUNCTION__))
;
1480
1481 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1482 auto C =
1483 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1484 return (C ? emitForMemory(C, destType) : nullptr);
1485}
1486
1487llvm::Constant *
1488ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1489 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1490 auto C = tryEmitAbstract(E, nonMemoryDestType);
1491 return (C ? emitForMemory(C, destType) : nullptr);
1492}
1493
1494llvm::Constant *
1495ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1496 QualType destType) {
1497 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1498 auto C = tryEmitAbstract(value, nonMemoryDestType);
1499 return (C ? emitForMemory(C, destType) : nullptr);
1500}
1501
1502llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1503 QualType destType) {
1504 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1505 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1506 return (C ? emitForMemory(C, destType) : nullptr);
1507}
1508
1509llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1510 QualType destType) {
1511 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1512 auto C = tryEmitPrivate(value, nonMemoryDestType);
1513 return (C ? emitForMemory(C, destType) : nullptr);
1514}
1515
1516llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1517 llvm::Constant *C,
1518 QualType destType) {
1519 // For an _Atomic-qualified constant, we may need to add tail padding.
1520 if (auto AT = destType->getAs<AtomicType>()) {
1521 QualType destValueType = AT->getValueType();
1522 C = emitForMemory(CGM, C, destValueType);
1523
1524 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1525 uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1526 if (innerSize == outerSize)
1527 return C;
1528
1529 assert(innerSize < outerSize && "emitted over-large constant for atomic")((innerSize < outerSize && "emitted over-large constant for atomic"
) ? static_cast<void> (0) : __assert_fail ("innerSize < outerSize && \"emitted over-large constant for atomic\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1529, __PRETTY_FUNCTION__))
;
1530 llvm::Constant *elts[] = {
1531 C,
1532 llvm::ConstantAggregateZero::get(
1533 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1534 };
1535 return llvm::ConstantStruct::getAnon(elts);
1536 }
1537
1538 // Zero-extend bool.
1539 if (C->getType()->isIntegerTy(1)) {
1540 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1541 return llvm::ConstantExpr::getZExt(C, boolTy);
1542 }
1543
1544 return C;
1545}
1546
1547llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1548 QualType destType) {
1549 Expr::EvalResult Result;
1550
1551 bool Success = false;
1552
1553 if (destType->isReferenceType())
1554 Success = E->EvaluateAsLValue(Result, CGM.getContext());
1555 else
1556 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
1557
1558 llvm::Constant *C;
1559 if (Success && !Result.HasSideEffects)
1560 C = tryEmitPrivate(Result.Val, destType);
1561 else
1562 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1563
1564 return C;
1565}
1566
1567llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1568 return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1569}
1570
1571namespace {
1572/// A struct which can be used to peephole certain kinds of finalization
1573/// that normally happen during l-value emission.
1574struct ConstantLValue {
1575 llvm::Constant *Value;
1576 bool HasOffsetApplied;
1577
1578 /*implicit*/ ConstantLValue(llvm::Constant *value,
1579 bool hasOffsetApplied = false)
1580 : Value(value), HasOffsetApplied(false) {}
1581
1582 /*implicit*/ ConstantLValue(ConstantAddress address)
1583 : ConstantLValue(address.getPointer()) {}
1584};
1585
1586/// A helper class for emitting constant l-values.
1587class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1588 ConstantLValue> {
1589 CodeGenModule &CGM;
1590 ConstantEmitter &Emitter;
1591 const APValue &Value;
1592 QualType DestType;
1593
1594 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1595 friend StmtVisitorBase;
1596
1597public:
1598 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1599 QualType destType)
1600 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1601
1602 llvm::Constant *tryEmit();
1603
1604private:
1605 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1606 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1607
1608 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1609 ConstantLValue VisitConstantExpr(const ConstantExpr *E);
1610 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1611 ConstantLValue VisitStringLiteral(const StringLiteral *E);
1612 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
1613 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1614 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1615 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1616 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1617 ConstantLValue VisitCallExpr(const CallExpr *E);
1618 ConstantLValue VisitBlockExpr(const BlockExpr *E);
1619 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1620 ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1621 ConstantLValue VisitMaterializeTemporaryExpr(
1622 const MaterializeTemporaryExpr *E);
1623
1624 bool hasNonZeroOffset() const {
1625 return !Value.getLValueOffset().isZero();
1626 }
1627
1628 /// Return the value offset.
1629 llvm::Constant *getOffset() {
1630 return llvm::ConstantInt::get(CGM.Int64Ty,
1631 Value.getLValueOffset().getQuantity());
1632 }
1633
1634 /// Apply the value offset to the given constant.
1635 llvm::Constant *applyOffset(llvm::Constant *C) {
1636 if (!hasNonZeroOffset())
1637 return C;
1638
1639 llvm::Type *origPtrTy = C->getType();
1640 unsigned AS = origPtrTy->getPointerAddressSpace();
1641 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1642 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1643 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1644 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1645 return C;
1646 }
1647};
1648
1649}
1650
1651llvm::Constant *ConstantLValueEmitter::tryEmit() {
1652 const APValue::LValueBase &base = Value.getLValueBase();
1653
1654 // The destination type should be a pointer or reference
1655 // type, but it might also be a cast thereof.
1656 //
1657 // FIXME: the chain of casts required should be reflected in the APValue.
1658 // We need this in order to correctly handle things like a ptrtoint of a
1659 // non-zero null pointer and addrspace casts that aren't trivially
1660 // represented in LLVM IR.
1661 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1662 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy))((isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType
>(destTy)) ? static_cast<void> (0) : __assert_fail (
"isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy)"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1662, __PRETTY_FUNCTION__))
;
1663
1664 // If there's no base at all, this is a null or absolute pointer,
1665 // possibly cast back to an integer type.
1666 if (!base) {
1667 return tryEmitAbsolute(destTy);
1668 }
1669
1670 // Otherwise, try to emit the base.
1671 ConstantLValue result = tryEmitBase(base);
1672
1673 // If that failed, we're done.
1674 llvm::Constant *value = result.Value;
1675 if (!value) return nullptr;
1676
1677 // Apply the offset if necessary and not already done.
1678 if (!result.HasOffsetApplied) {
1679 value = applyOffset(value);
1680 }
1681
1682 // Convert to the appropriate type; this could be an lvalue for
1683 // an integer. FIXME: performAddrSpaceCast
1684 if (isa<llvm::PointerType>(destTy))
1685 return llvm::ConstantExpr::getPointerCast(value, destTy);
1686
1687 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1688}
1689
1690/// Try to emit an absolute l-value, such as a null pointer or an integer
1691/// bitcast to pointer type.
1692llvm::Constant *
1693ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1694 // If we're producing a pointer, this is easy.
1695 auto destPtrTy = cast<llvm::PointerType>(destTy);
1696 if (Value.isNullPointer()) {
1697 // FIXME: integer offsets from non-zero null pointers.
1698 return CGM.getNullPointer(destPtrTy, DestType);
1699 }
1700
1701 // Convert the integer to a pointer-sized integer before converting it
1702 // to a pointer.
1703 // FIXME: signedness depends on the original integer type.
1704 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1705 llvm::Constant *C;
1706 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1707 /*isSigned*/ false);
1708 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1709 return C;
1710}
1711
1712ConstantLValue
1713ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1714 // Handle values.
1715 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1716 if (D->hasAttr<WeakRefAttr>())
1717 return CGM.GetWeakRefReference(D).getPointer();
1718
1719 if (auto FD = dyn_cast<FunctionDecl>(D))
1720 return CGM.GetAddrOfFunction(FD);
1721
1722 if (auto VD = dyn_cast<VarDecl>(D)) {
1723 // We can never refer to a variable with local storage.
1724 if (!VD->hasLocalStorage()) {
1725 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1726 return CGM.GetAddrOfGlobalVar(VD);
1727
1728 if (VD->isLocalVarDecl()) {
1729 return CGM.getOrCreateStaticVarDecl(
1730 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1731 }
1732 }
1733 }
1734
1735 return nullptr;
1736 }
1737
1738 // Handle typeid(T).
1739 if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
1740 llvm::Type *StdTypeInfoPtrTy =
1741 CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
1742 llvm::Constant *TypeInfo =
1743 CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
1744 if (TypeInfo->getType() != StdTypeInfoPtrTy)
1745 TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1746 return TypeInfo;
1747 }
1748
1749 // Otherwise, it must be an expression.
1750 return Visit(base.get<const Expr*>());
1751}
1752
1753ConstantLValue
1754ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1755 return Visit(E->getSubExpr());
1756}
1757
1758ConstantLValue
1759ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1760 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1761}
1762
1763ConstantLValue
1764ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1765 return CGM.GetAddrOfConstantStringFromLiteral(E);
1766}
1767
1768ConstantLValue
1769ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1770 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1771}
1772
1773static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1774 QualType T,
1775 CodeGenModule &CGM) {
1776 auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1777 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1778}
1779
1780ConstantLValue
1781ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1782 return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1783}
1784
1785ConstantLValue
1786ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1787 assert(E->isExpressibleAsConstantInitializer() &&((E->isExpressibleAsConstantInitializer() && "this boxed expression can't be emitted as a compile-time constant"
) ? static_cast<void> (0) : __assert_fail ("E->isExpressibleAsConstantInitializer() && \"this boxed expression can't be emitted as a compile-time constant\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1788, __PRETTY_FUNCTION__))
1788 "this boxed expression can't be emitted as a compile-time constant")((E->isExpressibleAsConstantInitializer() && "this boxed expression can't be emitted as a compile-time constant"
) ? static_cast<void> (0) : __assert_fail ("E->isExpressibleAsConstantInitializer() && \"this boxed expression can't be emitted as a compile-time constant\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1788, __PRETTY_FUNCTION__))
;
1789 auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1790 return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
1791}
1792
1793ConstantLValue
1794ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1795 return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
1796}
1797
1798ConstantLValue
1799ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1800 assert(Emitter.CGF && "Invalid address of label expression outside function")((Emitter.CGF && "Invalid address of label expression outside function"
) ? static_cast<void> (0) : __assert_fail ("Emitter.CGF && \"Invalid address of label expression outside function\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1800, __PRETTY_FUNCTION__))
;
1801 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1802 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1803 CGM.getTypes().ConvertType(E->getType()));
1804 return Ptr;
1805}
1806
1807ConstantLValue
1808ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1809 unsigned builtin = E->getBuiltinCallee();
1810 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1811 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1812 return nullptr;
1813
1814 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1815 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1816 return CGM.getObjCRuntime().GenerateConstantString(literal);
1817 } else {
1818 // FIXME: need to deal with UCN conversion issues.
1819 return CGM.GetAddrOfConstantCFString(literal);
1820 }
1821}
1822
1823ConstantLValue
1824ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1825 StringRef functionName;
1826 if (auto CGF = Emitter.CGF)
1827 functionName = CGF->CurFn->getName();
1828 else
1829 functionName = "global";
1830
1831 return CGM.GetAddrOfGlobalBlock(E, functionName);
1832}
1833
1834ConstantLValue
1835ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1836 QualType T;
1837 if (E->isTypeOperand())
1838 T = E->getTypeOperand(CGM.getContext());
1839 else
1840 T = E->getExprOperand()->getType();
1841 return CGM.GetAddrOfRTTIDescriptor(T);
1842}
1843
1844ConstantLValue
1845ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1846 return CGM.GetAddrOfUuidDescriptor(E);
1847}
1848
1849ConstantLValue
1850ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1851 const MaterializeTemporaryExpr *E) {
1852 assert(E->getStorageDuration() == SD_Static)((E->getStorageDuration() == SD_Static) ? static_cast<void
> (0) : __assert_fail ("E->getStorageDuration() == SD_Static"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1852, __PRETTY_FUNCTION__))
;
1853 SmallVector<const Expr *, 2> CommaLHSs;
1854 SmallVector<SubobjectAdjustment, 2> Adjustments;
1855 const Expr *Inner = E->GetTemporaryExpr()
1856 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1857 return CGM.GetAddrOfGlobalTemporary(E, Inner);
1858}
1859
1860llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
1861 QualType DestType) {
1862 switch (Value.getKind()) {
1863 case APValue::None:
1864 case APValue::Indeterminate:
1865 // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
1866 return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
1867 case APValue::LValue:
1868 return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
1869 case APValue::Int:
1870 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
1871 case APValue::FixedPoint:
1872 return llvm::ConstantInt::get(CGM.getLLVMContext(),
1873 Value.getFixedPoint().getValue());
1874 case APValue::ComplexInt: {
1875 llvm::Constant *Complex[2];
1876
1877 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1878 Value.getComplexIntReal());
1879 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1880 Value.getComplexIntImag());
1881
1882 // FIXME: the target may want to specify that this is packed.
1883 llvm::StructType *STy =
1884 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1885 return llvm::ConstantStruct::get(STy, Complex);
1886 }
1887 case APValue::Float: {
1888 const llvm::APFloat &Init = Value.getFloat();
1889 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
1890 !CGM.getContext().getLangOpts().NativeHalfType &&
1891 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1892 return llvm::ConstantInt::get(CGM.getLLVMContext(),
1893 Init.bitcastToAPInt());
1894 else
1895 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
1896 }
1897 case APValue::ComplexFloat: {
1898 llvm::Constant *Complex[2];
1899
1900 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1901 Value.getComplexFloatReal());
1902 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1903 Value.getComplexFloatImag());
1904
1905 // FIXME: the target may want to specify that this is packed.
1906 llvm::StructType *STy =
1907 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1908 return llvm::ConstantStruct::get(STy, Complex);
1909 }
1910 case APValue::Vector: {
1911 unsigned NumElts = Value.getVectorLength();
1912 SmallVector<llvm::Constant *, 4> Inits(NumElts);
1913
1914 for (unsigned I = 0; I != NumElts; ++I) {
1915 const APValue &Elt = Value.getVectorElt(I);
1916 if (Elt.isInt())
1917 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
1918 else if (Elt.isFloat())
1919 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
1920 else
1921 llvm_unreachable("unsupported vector element type")::llvm::llvm_unreachable_internal("unsupported vector element type"
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1921)
;
1922 }
1923 return llvm::ConstantVector::get(Inits);
1924 }
1925 case APValue::AddrLabelDiff: {
1926 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1927 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1928 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
1929 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
1930 if (!LHS || !RHS) return nullptr;
1931
1932 // Compute difference
1933 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
1934 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
1935 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
1936 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1937
1938 // LLVM is a bit sensitive about the exact format of the
1939 // address-of-label difference; make sure to truncate after
1940 // the subtraction.
1941 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1942 }
1943 case APValue::Struct:
1944 case APValue::Union:
1945 return ConstStructBuilder::BuildStruct(*this, Value, DestType);
1946 case APValue::Array: {
1947 const ConstantArrayType *CAT =
1948 CGM.getContext().getAsConstantArrayType(DestType);
1949 unsigned NumElements = Value.getArraySize();
1950 unsigned NumInitElts = Value.getArrayInitializedElts();
1951
1952 // Emit array filler, if there is one.
1953 llvm::Constant *Filler = nullptr;
1954 if (Value.hasArrayFiller()) {
1955 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
1956 CAT->getElementType());
1957 if (!Filler)
1958 return nullptr;
1959 }
1960
1961 // Emit initializer elements.
1962 SmallVector<llvm::Constant*, 16> Elts;
1963 if (Filler && Filler->isNullValue())
1964 Elts.reserve(NumInitElts + 1);
1965 else
1966 Elts.reserve(NumElements);
1967
1968 llvm::Type *CommonElementType = nullptr;
1969 for (unsigned I = 0; I < NumInitElts; ++I) {
1970 llvm::Constant *C = tryEmitPrivateForMemory(
1971 Value.getArrayInitializedElt(I), CAT->getElementType());
1972 if (!C) return nullptr;
1973
1974 if (I == 0)
1975 CommonElementType = C->getType();
1976 else if (C->getType() != CommonElementType)
1977 CommonElementType = nullptr;
1978 Elts.push_back(C);
1979 }
1980
1981 // This means that the array type is probably "IncompleteType" or some
1982 // type that is not ConstantArray.
1983 if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
1984 const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
1985 CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
1986 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
1987 NumElements);
1988 return llvm::ConstantAggregateZero::get(AType);
1989 }
1990
1991 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
1992 Filler);
1993 }
1994 case APValue::MemberPointer:
1995 return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
1996 }
1997 llvm_unreachable("Unknown APValue kind")::llvm::llvm_unreachable_internal("Unknown APValue kind", "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1997)
;
1998}
1999
2000llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2001 const CompoundLiteralExpr *E) {
2002 return EmittedCompoundLiterals.lookup(E);
2003}
2004
2005void CodeGenModule::setAddrOfConstantCompoundLiteral(
2006 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2007 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2008 (void)Ok;
2009 assert(Ok && "CLE has already been emitted!")((Ok && "CLE has already been emitted!") ? static_cast
<void> (0) : __assert_fail ("Ok && \"CLE has already been emitted!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 2009, __PRETTY_FUNCTION__))
;
2010}
2011
2012ConstantAddress
2013CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2014 assert(E->isFileScope() && "not a file-scope compound literal expr")((E->isFileScope() && "not a file-scope compound literal expr"
) ? static_cast<void> (0) : __assert_fail ("E->isFileScope() && \"not a file-scope compound literal expr\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 2014, __PRETTY_FUNCTION__))
;
2015 return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
2016}
2017
2018llvm::Constant *
2019CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2020 // Member pointer constants always have a very particular form.
2021 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2022 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2023
2024 // A member function pointer.
2025 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2026 return getCXXABI().EmitMemberFunctionPointer(method);
2027
2028 // Otherwise, a member data pointer.
2029 uint64_t fieldOffset = getContext().getFieldOffset(decl);
2030 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2031 return getCXXABI().EmitMemberDataPointer(type, chars);
2032}
2033
2034static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2035 llvm::Type *baseType,
2036 const CXXRecordDecl *base);
2037
2038static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2039 const RecordDecl *record,
2040 bool asCompleteObject) {
2041 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
2042 llvm::StructType *structure =
2043 (asCompleteObject ? layout.getLLVMType()
2044 : layout.getBaseSubobjectLLVMType());
2045
2046 unsigned numElements = structure->getNumElements();
2047 std::vector<llvm::Constant *> elements(numElements);
2048
2049 auto CXXR = dyn_cast<CXXRecordDecl>(record);
2050 // Fill in all the bases.
2051 if (CXXR) {
2052 for (const auto &I : CXXR->bases()) {
2053 if (I.isVirtual()) {
2054 // Ignore virtual bases; if we're laying out for a complete
2055 // object, we'll lay these out later.
2056 continue;
2057 }
2058
2059 const CXXRecordDecl *base =
2060 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2061
2062 // Ignore empty bases.
2063 if (base->isEmpty() ||
2064 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2065 .isZero())
2066 continue;
2067
2068 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2069 llvm::Type *baseType = structure->getElementType(fieldIndex);
2070 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2071 }
2072 }
2073
2074 // Fill in all the fields.
2075 for (const auto *Field : record->fields()) {
2076 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2077 // will fill in later.)
2078 if (!Field->isBitField()) {
2079 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2080 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2081 }
2082
2083 // For unions, stop after the first named field.
2084 if (record->isUnion()) {
2085 if (Field->getIdentifier())
2086 break;
2087 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2088 if (FieldRD->findFirstNamedDataMember())
2089 break;
2090 }
2091 }
2092
2093 // Fill in the virtual bases, if we're working with the complete object.
2094 if (CXXR && asCompleteObject) {
2095 for (const auto &I : CXXR->vbases()) {
2096 const CXXRecordDecl *base =
2097 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2098
2099 // Ignore empty bases.
2100 if (base->isEmpty())
2101 continue;
2102
2103 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2104
2105 // We might have already laid this field out.
2106 if (elements[fieldIndex]) continue;
2107
2108 llvm::Type *baseType = structure->getElementType(fieldIndex);
2109 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2110 }
2111 }
2112
2113 // Now go through all other fields and zero them out.
2114 for (unsigned i = 0; i != numElements; ++i) {
2115 if (!elements[i])
2116 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2117 }
2118
2119 return llvm::ConstantStruct::get(structure, elements);
2120}
2121
2122/// Emit the null constant for a base subobject.
2123static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2124 llvm::Type *baseType,
2125 const CXXRecordDecl *base) {
2126 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2127
2128 // Just zero out bases that don't have any pointer to data members.
2129 if (baseLayout.isZeroInitializableAsBase())
2130 return llvm::Constant::getNullValue(baseType);
2131
2132 // Otherwise, we can just use its null constant.
2133 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2134}
2135
2136llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2137 QualType T) {
2138 return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2139}
2140
2141llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2142 if (T->getAs<PointerType>())
2143 return getNullPointer(
2144 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2145
2146 if (getTypes().isZeroInitializable(T))
2147 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2148
2149 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2150 llvm::ArrayType *ATy =
2151 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2152
2153 QualType ElementTy = CAT->getElementType();
2154
2155 llvm::Constant *Element =
2156 ConstantEmitter::emitNullForMemory(*this, ElementTy);
2157 unsigned NumElements = CAT->getSize().getZExtValue();
2158 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2159 return llvm::ConstantArray::get(ATy, Array);
2160 }
2161
2162 if (const RecordType *RT = T->getAs<RecordType>())
2163 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2164
2165 assert(T->isMemberDataPointerType() &&((T->isMemberDataPointerType() && "Should only see pointers to data members here!"
) ? static_cast<void> (0) : __assert_fail ("T->isMemberDataPointerType() && \"Should only see pointers to data members here!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 2166, __PRETTY_FUNCTION__))
2166 "Should only see pointers to data members here!")((T->isMemberDataPointerType() && "Should only see pointers to data members here!"
) ? static_cast<void> (0) : __assert_fail ("T->isMemberDataPointerType() && \"Should only see pointers to data members here!\""
, "/build/llvm-toolchain-snapshot-9~svn361465/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 2166, __PRETTY_FUNCTION__))
;
2167
2168 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2169}
2170
2171llvm::Constant *
2172CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2173 return ::EmitNullConstant(*this, Record, false);
2174}