Bug Summary

File:clang/lib/AST/Expr.cpp
Warning:line 315, column 5
Storage provided to placement new is only 0 bytes, whereas the allocated type requires 72 bytes

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Expr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/AST -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/AST/Expr.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/AST/Expr.cpp

1//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr class and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Expr.h"
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/ComputeDependence.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/DependenceFlags.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/IgnoreExpr.h"
25#include "clang/AST/Mangle.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/CharInfo.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/Lexer.h"
33#include "clang/Lex/LiteralSupport.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/Format.h"
36#include "llvm/Support/raw_ostream.h"
37#include <algorithm>
38#include <cstring>
39using namespace clang;
40
41const Expr *Expr::getBestDynamicClassTypeExpr() const {
42 const Expr *E = this;
43 while (true) {
44 E = E->IgnoreParenBaseCasts();
45
46 // Follow the RHS of a comma operator.
47 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
48 if (BO->getOpcode() == BO_Comma) {
49 E = BO->getRHS();
50 continue;
51 }
52 }
53
54 // Step into initializer for materialized temporaries.
55 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
56 E = MTE->getSubExpr();
57 continue;
58 }
59
60 break;
61 }
62
63 return E;
64}
65
66const CXXRecordDecl *Expr::getBestDynamicClassType() const {
67 const Expr *E = getBestDynamicClassTypeExpr();
68 QualType DerivedType = E->getType();
69 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
70 DerivedType = PTy->getPointeeType();
71
72 if (DerivedType->isDependentType())
73 return nullptr;
74
75 const RecordType *Ty = DerivedType->castAs<RecordType>();
76 Decl *D = Ty->getDecl();
77 return cast<CXXRecordDecl>(D);
78}
79
80const Expr *Expr::skipRValueSubobjectAdjustments(
81 SmallVectorImpl<const Expr *> &CommaLHSs,
82 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
83 const Expr *E = this;
84 while (true) {
85 E = E->IgnoreParens();
86
87 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
88 if ((CE->getCastKind() == CK_DerivedToBase ||
89 CE->getCastKind() == CK_UncheckedDerivedToBase) &&
90 E->getType()->isRecordType()) {
91 E = CE->getSubExpr();
92 auto *Derived =
93 cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
94 Adjustments.push_back(SubobjectAdjustment(CE, Derived));
95 continue;
96 }
97
98 if (CE->getCastKind() == CK_NoOp) {
99 E = CE->getSubExpr();
100 continue;
101 }
102 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
103 if (!ME->isArrow()) {
104 assert(ME->getBase()->getType()->isRecordType())(static_cast<void> (0));
105 if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
106 if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
107 E = ME->getBase();
108 Adjustments.push_back(SubobjectAdjustment(Field));
109 continue;
110 }
111 }
112 }
113 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
114 if (BO->getOpcode() == BO_PtrMemD) {
115 assert(BO->getRHS()->isPRValue())(static_cast<void> (0));
116 E = BO->getLHS();
117 const MemberPointerType *MPT =
118 BO->getRHS()->getType()->getAs<MemberPointerType>();
119 Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
120 continue;
121 }
122 if (BO->getOpcode() == BO_Comma) {
123 CommaLHSs.push_back(BO->getLHS());
124 E = BO->getRHS();
125 continue;
126 }
127 }
128
129 // Nothing changed.
130 break;
131 }
132 return E;
133}
134
135bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
136 const Expr *E = IgnoreParens();
137
138 // If this value has _Bool type, it is obvious 0/1.
139 if (E->getType()->isBooleanType()) return true;
140 // If this is a non-scalar-integer type, we don't care enough to try.
141 if (!E->getType()->isIntegralOrEnumerationType()) return false;
142
143 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
144 switch (UO->getOpcode()) {
145 case UO_Plus:
146 return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
147 case UO_LNot:
148 return true;
149 default:
150 return false;
151 }
152 }
153
154 // Only look through implicit casts. If the user writes
155 // '(int) (a && b)' treat it as an arbitrary int.
156 // FIXME: Should we look through any cast expression in !Semantic mode?
157 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
158 return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
159
160 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
161 switch (BO->getOpcode()) {
162 default: return false;
163 case BO_LT: // Relational operators.
164 case BO_GT:
165 case BO_LE:
166 case BO_GE:
167 case BO_EQ: // Equality operators.
168 case BO_NE:
169 case BO_LAnd: // AND operator.
170 case BO_LOr: // Logical OR operator.
171 return true;
172
173 case BO_And: // Bitwise AND operator.
174 case BO_Xor: // Bitwise XOR operator.
175 case BO_Or: // Bitwise OR operator.
176 // Handle things like (x==2)|(y==12).
177 return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
178 BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
179
180 case BO_Comma:
181 case BO_Assign:
182 return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
183 }
184 }
185
186 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
187 return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
188 CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
189
190 if (isa<ObjCBoolLiteralExpr>(E))
191 return true;
192
193 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
194 return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
195
196 if (const FieldDecl *FD = E->getSourceBitField())
197 if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
198 !FD->getBitWidth()->isValueDependent() &&
199 FD->getBitWidthValue(FD->getASTContext()) == 1)
200 return true;
201
202 return false;
203}
204
205// Amusing macro metaprogramming hack: check whether a class provides
206// a more specific implementation of getExprLoc().
207//
208// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
209namespace {
210 /// This implementation is used when a class provides a custom
211 /// implementation of getExprLoc.
212 template <class E, class T>
213 SourceLocation getExprLocImpl(const Expr *expr,
214 SourceLocation (T::*v)() const) {
215 return static_cast<const E*>(expr)->getExprLoc();
216 }
217
218 /// This implementation is used when a class doesn't provide
219 /// a custom implementation of getExprLoc. Overload resolution
220 /// should pick it over the implementation above because it's
221 /// more specialized according to function template partial ordering.
222 template <class E>
223 SourceLocation getExprLocImpl(const Expr *expr,
224 SourceLocation (Expr::*v)() const) {
225 return static_cast<const E *>(expr)->getBeginLoc();
226 }
227}
228
229SourceLocation Expr::getExprLoc() const {
230 switch (getStmtClass()) {
231 case Stmt::NoStmtClass: llvm_unreachable("statement without class")__builtin_unreachable();
232#define ABSTRACT_STMT(type)
233#define STMT(type, base) \
234 case Stmt::type##Class: break;
235#define EXPR(type, base) \
236 case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
237#include "clang/AST/StmtNodes.inc"
238 }
239 llvm_unreachable("unknown expression kind")__builtin_unreachable();
240}
241
242//===----------------------------------------------------------------------===//
243// Primary Expressions.
244//===----------------------------------------------------------------------===//
245
246static void AssertResultStorageKind(ConstantExpr::ResultStorageKind Kind) {
247 assert((Kind == ConstantExpr::RSK_APValue ||(static_cast<void> (0))
248 Kind == ConstantExpr::RSK_Int64 || Kind == ConstantExpr::RSK_None) &&(static_cast<void> (0))
249 "Invalid StorageKind Value")(static_cast<void> (0));
250 (void)Kind;
251}
252
253ConstantExpr::ResultStorageKind
254ConstantExpr::getStorageKind(const APValue &Value) {
255 switch (Value.getKind()) {
256 case APValue::None:
257 case APValue::Indeterminate:
258 return ConstantExpr::RSK_None;
259 case APValue::Int:
260 if (!Value.getInt().needsCleanup())
261 return ConstantExpr::RSK_Int64;
262 LLVM_FALLTHROUGH[[gnu::fallthrough]];
263 default:
264 return ConstantExpr::RSK_APValue;
265 }
266}
267
268ConstantExpr::ResultStorageKind
269ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
270 if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
271 return ConstantExpr::RSK_Int64;
272 return ConstantExpr::RSK_APValue;
273}
274
275ConstantExpr::ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
276 bool IsImmediateInvocation)
277 : FullExpr(ConstantExprClass, SubExpr) {
278 ConstantExprBits.ResultKind = StorageKind;
279 ConstantExprBits.APValueKind = APValue::None;
280 ConstantExprBits.IsUnsigned = false;
281 ConstantExprBits.BitWidth = 0;
282 ConstantExprBits.HasCleanup = false;
283 ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
284
285 if (StorageKind == ConstantExpr::RSK_APValue)
286 ::new (getTrailingObjects<APValue>()) APValue();
287}
288
289ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
290 ResultStorageKind StorageKind,
291 bool IsImmediateInvocation) {
292 assert(!isa<ConstantExpr>(E))(static_cast<void> (0));
293 AssertResultStorageKind(StorageKind);
294
295 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
296 StorageKind == ConstantExpr::RSK_APValue,
297 StorageKind == ConstantExpr::RSK_Int64);
298 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
299 return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
300}
301
302ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
303 const APValue &Result) {
304 ResultStorageKind StorageKind = getStorageKind(Result);
305 ConstantExpr *Self = Create(Context, E, StorageKind);
306 Self->SetResult(Result, Context);
307 return Self;
308}
309
310ConstantExpr::ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind)
311 : FullExpr(ConstantExprClass, Empty) {
312 ConstantExprBits.ResultKind = StorageKind;
313
314 if (StorageKind
2.1
'StorageKind' is equal to RSK_APValue
2.1
'StorageKind' is equal to RSK_APValue
== ConstantExpr::RSK_APValue)
3
Taking true branch
315 ::new (getTrailingObjects<APValue>()) APValue();
4
Calling 'TrailingObjects::getTrailingObjects'
13
Returning from 'TrailingObjects::getTrailingObjects'
14
Storage provided to placement new is only 0 bytes, whereas the allocated type requires 72 bytes
316}
317
318ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
319 ResultStorageKind StorageKind) {
320 AssertResultStorageKind(StorageKind);
321
322 unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
323 StorageKind == ConstantExpr::RSK_APValue,
1
Assuming 'StorageKind' is equal to RSK_APValue
324 StorageKind == ConstantExpr::RSK_Int64);
325 void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
326 return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
2
Calling constructor for 'ConstantExpr'
327}
328
329void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
330 assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&(static_cast<void> (0))
331 "Invalid storage for this value kind")(static_cast<void> (0));
332 ConstantExprBits.APValueKind = Value.getKind();
333 switch (ConstantExprBits.ResultKind) {
334 case RSK_None:
335 return;
336 case RSK_Int64:
337 Int64Result() = *Value.getInt().getRawData();
338 ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
339 ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
340 return;
341 case RSK_APValue:
342 if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
343 ConstantExprBits.HasCleanup = true;
344 Context.addDestruction(&APValueResult());
345 }
346 APValueResult() = std::move(Value);
347 return;
348 }
349 llvm_unreachable("Invalid ResultKind Bits")__builtin_unreachable();
350}
351
352llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
353 switch (ConstantExprBits.ResultKind) {
354 case ConstantExpr::RSK_APValue:
355 return APValueResult().getInt();
356 case ConstantExpr::RSK_Int64:
357 return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
358 ConstantExprBits.IsUnsigned);
359 default:
360 llvm_unreachable("invalid Accessor")__builtin_unreachable();
361 }
362}
363
364APValue ConstantExpr::getAPValueResult() const {
365
366 switch (ConstantExprBits.ResultKind) {
367 case ConstantExpr::RSK_APValue:
368 return APValueResult();
369 case ConstantExpr::RSK_Int64:
370 return APValue(
371 llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
372 ConstantExprBits.IsUnsigned));
373 case ConstantExpr::RSK_None:
374 if (ConstantExprBits.APValueKind == APValue::Indeterminate)
375 return APValue::IndeterminateValue();
376 return APValue();
377 }
378 llvm_unreachable("invalid ResultKind")__builtin_unreachable();
379}
380
381DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
382 bool RefersToEnclosingVariableOrCapture, QualType T,
383 ExprValueKind VK, SourceLocation L,
384 const DeclarationNameLoc &LocInfo,
385 NonOdrUseReason NOUR)
386 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
387 DeclRefExprBits.HasQualifier = false;
388 DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
389 DeclRefExprBits.HasFoundDecl = false;
390 DeclRefExprBits.HadMultipleCandidates = false;
391 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
392 RefersToEnclosingVariableOrCapture;
393 DeclRefExprBits.NonOdrUseReason = NOUR;
394 DeclRefExprBits.Loc = L;
395 setDependence(computeDependence(this, Ctx));
396}
397
398DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
399 NestedNameSpecifierLoc QualifierLoc,
400 SourceLocation TemplateKWLoc, ValueDecl *D,
401 bool RefersToEnclosingVariableOrCapture,
402 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
403 const TemplateArgumentListInfo *TemplateArgs,
404 QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
405 : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
406 DNLoc(NameInfo.getInfo()) {
407 DeclRefExprBits.Loc = NameInfo.getLoc();
408 DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
409 if (QualifierLoc)
410 new (getTrailingObjects<NestedNameSpecifierLoc>())
411 NestedNameSpecifierLoc(QualifierLoc);
412 DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
413 if (FoundD)
414 *getTrailingObjects<NamedDecl *>() = FoundD;
415 DeclRefExprBits.HasTemplateKWAndArgsInfo
416 = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
417 DeclRefExprBits.RefersToEnclosingVariableOrCapture =
418 RefersToEnclosingVariableOrCapture;
419 DeclRefExprBits.NonOdrUseReason = NOUR;
420 if (TemplateArgs) {
421 auto Deps = TemplateArgumentDependence::None;
422 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
423 TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
424 Deps);
425 assert(!(Deps & TemplateArgumentDependence::Dependent) &&(static_cast<void> (0))
426 "built a DeclRefExpr with dependent template args")(static_cast<void> (0));
427 } else if (TemplateKWLoc.isValid()) {
428 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
429 TemplateKWLoc);
430 }
431 DeclRefExprBits.HadMultipleCandidates = 0;
432 setDependence(computeDependence(this, Ctx));
433}
434
435DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
436 NestedNameSpecifierLoc QualifierLoc,
437 SourceLocation TemplateKWLoc, ValueDecl *D,
438 bool RefersToEnclosingVariableOrCapture,
439 SourceLocation NameLoc, QualType T,
440 ExprValueKind VK, NamedDecl *FoundD,
441 const TemplateArgumentListInfo *TemplateArgs,
442 NonOdrUseReason NOUR) {
443 return Create(Context, QualifierLoc, TemplateKWLoc, D,
444 RefersToEnclosingVariableOrCapture,
445 DeclarationNameInfo(D->getDeclName(), NameLoc),
446 T, VK, FoundD, TemplateArgs, NOUR);
447}
448
449DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
450 NestedNameSpecifierLoc QualifierLoc,
451 SourceLocation TemplateKWLoc, ValueDecl *D,
452 bool RefersToEnclosingVariableOrCapture,
453 const DeclarationNameInfo &NameInfo,
454 QualType T, ExprValueKind VK,
455 NamedDecl *FoundD,
456 const TemplateArgumentListInfo *TemplateArgs,
457 NonOdrUseReason NOUR) {
458 // Filter out cases where the found Decl is the same as the value refenenced.
459 if (D == FoundD)
460 FoundD = nullptr;
461
462 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
463 std::size_t Size =
464 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
465 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
466 QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
467 HasTemplateKWAndArgsInfo ? 1 : 0,
468 TemplateArgs ? TemplateArgs->size() : 0);
469
470 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
471 return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
472 RefersToEnclosingVariableOrCapture, NameInfo,
473 FoundD, TemplateArgs, T, VK, NOUR);
474}
475
476DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
477 bool HasQualifier,
478 bool HasFoundDecl,
479 bool HasTemplateKWAndArgsInfo,
480 unsigned NumTemplateArgs) {
481 assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo)(static_cast<void> (0));
482 std::size_t Size =
483 totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
484 ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
485 HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
486 NumTemplateArgs);
487 void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
488 return new (Mem) DeclRefExpr(EmptyShell());
489}
490
491void DeclRefExpr::setDecl(ValueDecl *NewD) {
492 D = NewD;
493 if (getType()->isUndeducedType())
494 setType(NewD->getType());
495 setDependence(computeDependence(this, NewD->getASTContext()));
496}
497
498SourceLocation DeclRefExpr::getBeginLoc() const {
499 if (hasQualifier())
500 return getQualifierLoc().getBeginLoc();
501 return getNameInfo().getBeginLoc();
502}
503SourceLocation DeclRefExpr::getEndLoc() const {
504 if (hasExplicitTemplateArgs())
505 return getRAngleLoc();
506 return getNameInfo().getEndLoc();
507}
508
509SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
510 SourceLocation LParen,
511 SourceLocation RParen,
512 QualType ResultTy,
513 TypeSourceInfo *TSI)
514 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
515 OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
516 setTypeSourceInfo(TSI);
517 setDependence(computeDependence(this));
518}
519
520SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
521 QualType ResultTy)
522 : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
523
524SYCLUniqueStableNameExpr *
525SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,
526 SourceLocation LParen, SourceLocation RParen,
527 TypeSourceInfo *TSI) {
528 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
529 return new (Ctx)
530 SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
531}
532
533SYCLUniqueStableNameExpr *
534SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {
535 QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
536 return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
537}
538
539std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {
540 return SYCLUniqueStableNameExpr::ComputeName(Context,
541 getTypeSourceInfo()->getType());
542}
543
544std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
545 QualType Ty) {
546 auto MangleCallback = [](ASTContext &Ctx,
547 const NamedDecl *ND) -> llvm::Optional<unsigned> {
548 // This replaces the 'lambda number' in the mangling with a unique number
549 // based on its order in the declaration. To provide some level of visual
550 // notability (actual uniqueness from normal lambdas isn't necessary, as
551 // these are used differently), we add 10,000 to the number.
552 // For example:
553 // _ZTSZ3foovEUlvE10005_
554 // Demangles to: typeinfo name for foo()::'lambda10005'()
555 // Note that the mangler subtracts 2, since with normal lambdas the lambda
556 // mangling number '0' is an anonymous struct mangle, and '1' is omitted.
557 // So 10,002 results in the first number being 10,000.
558 if (Ctx.IsSYCLKernelNamingDecl(ND))
559 return 10'002 + Ctx.GetSYCLKernelNamingIndex(ND);
560 return llvm::None;
561 };
562 std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
563 Context, Context.getDiagnostics(), MangleCallback)};
564
565 std::string Buffer;
566 Buffer.reserve(128);
567 llvm::raw_string_ostream Out(Buffer);
568 Ctx->mangleTypeName(Ty, Out);
569
570 return Out.str();
571}
572
573PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
574 StringLiteral *SL)
575 : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
576 PredefinedExprBits.Kind = IK;
577 assert((getIdentKind() == IK) &&(static_cast<void> (0))
578 "IdentKind do not fit in PredefinedExprBitfields!")(static_cast<void> (0));
579 bool HasFunctionName = SL != nullptr;
580 PredefinedExprBits.HasFunctionName = HasFunctionName;
581 PredefinedExprBits.Loc = L;
582 if (HasFunctionName)
583 setFunctionName(SL);
584 setDependence(computeDependence(this));
585}
586
587PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
588 : Expr(PredefinedExprClass, Empty) {
589 PredefinedExprBits.HasFunctionName = HasFunctionName;
590}
591
592PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
593 QualType FNTy, IdentKind IK,
594 StringLiteral *SL) {
595 bool HasFunctionName = SL != nullptr;
596 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
597 alignof(PredefinedExpr));
598 return new (Mem) PredefinedExpr(L, FNTy, IK, SL);
599}
600
601PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
602 bool HasFunctionName) {
603 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
604 alignof(PredefinedExpr));
605 return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
606}
607
608StringRef PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
609 switch (IK) {
610 case Func:
611 return "__func__";
612 case Function:
613 return "__FUNCTION__";
614 case FuncDName:
615 return "__FUNCDNAME__";
616 case LFunction:
617 return "L__FUNCTION__";
618 case PrettyFunction:
619 return "__PRETTY_FUNCTION__";
620 case FuncSig:
621 return "__FUNCSIG__";
622 case LFuncSig:
623 return "L__FUNCSIG__";
624 case PrettyFunctionNoVirtual:
625 break;
626 }
627 llvm_unreachable("Unknown ident kind for PredefinedExpr")__builtin_unreachable();
628}
629
630// FIXME: Maybe this should use DeclPrinter with a special "print predefined
631// expr" policy instead.
632std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) {
633 ASTContext &Context = CurrentDecl->getASTContext();
634
635 if (IK == PredefinedExpr::FuncDName) {
636 if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
637 std::unique_ptr<MangleContext> MC;
638 MC.reset(Context.createMangleContext());
639
640 if (MC->shouldMangleDeclName(ND)) {
641 SmallString<256> Buffer;
642 llvm::raw_svector_ostream Out(Buffer);
643 GlobalDecl GD;
644 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
645 GD = GlobalDecl(CD, Ctor_Base);
646 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
647 GD = GlobalDecl(DD, Dtor_Base);
648 else if (ND->hasAttr<CUDAGlobalAttr>())
649 GD = GlobalDecl(cast<FunctionDecl>(ND));
650 else
651 GD = GlobalDecl(ND);
652 MC->mangleName(GD, Out);
653
654 if (!Buffer.empty() && Buffer.front() == '\01')
655 return std::string(Buffer.substr(1));
656 return std::string(Buffer.str());
657 }
658 return std::string(ND->getIdentifier()->getName());
659 }
660 return "";
661 }
662 if (isa<BlockDecl>(CurrentDecl)) {
663 // For blocks we only emit something if it is enclosed in a function
664 // For top-level block we'd like to include the name of variable, but we
665 // don't have it at this point.
666 auto DC = CurrentDecl->getDeclContext();
667 if (DC->isFileContext())
668 return "";
669
670 SmallString<256> Buffer;
671 llvm::raw_svector_ostream Out(Buffer);
672 if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
673 // For nested blocks, propagate up to the parent.
674 Out << ComputeName(IK, DCBlock);
675 else if (auto *DCDecl = dyn_cast<Decl>(DC))
676 Out << ComputeName(IK, DCDecl) << "_block_invoke";
677 return std::string(Out.str());
678 }
679 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
680 if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual &&
681 IK != FuncSig && IK != LFuncSig)
682 return FD->getNameAsString();
683
684 SmallString<256> Name;
685 llvm::raw_svector_ostream Out(Name);
686
687 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
688 if (MD->isVirtual() && IK != PrettyFunctionNoVirtual)
689 Out << "virtual ";
690 if (MD->isStatic())
691 Out << "static ";
692 }
693
694 PrintingPolicy Policy(Context.getLangOpts());
695 std::string Proto;
696 llvm::raw_string_ostream POut(Proto);
697
698 const FunctionDecl *Decl = FD;
699 if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
700 Decl = Pattern;
701 const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
702 const FunctionProtoType *FT = nullptr;
703 if (FD->hasWrittenPrototype())
704 FT = dyn_cast<FunctionProtoType>(AFT);
705
706 if (IK == FuncSig || IK == LFuncSig) {
707 switch (AFT->getCallConv()) {
708 case CC_C: POut << "__cdecl "; break;
709 case CC_X86StdCall: POut << "__stdcall "; break;
710 case CC_X86FastCall: POut << "__fastcall "; break;
711 case CC_X86ThisCall: POut << "__thiscall "; break;
712 case CC_X86VectorCall: POut << "__vectorcall "; break;
713 case CC_X86RegCall: POut << "__regcall "; break;
714 // Only bother printing the conventions that MSVC knows about.
715 default: break;
716 }
717 }
718
719 FD->printQualifiedName(POut, Policy);
720
721 POut << "(";
722 if (FT) {
723 for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
724 if (i) POut << ", ";
725 POut << Decl->getParamDecl(i)->getType().stream(Policy);
726 }
727
728 if (FT->isVariadic()) {
729 if (FD->getNumParams()) POut << ", ";
730 POut << "...";
731 } else if ((IK == FuncSig || IK == LFuncSig ||
732 !Context.getLangOpts().CPlusPlus) &&
733 !Decl->getNumParams()) {
734 POut << "void";
735 }
736 }
737 POut << ")";
738
739 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
740 assert(FT && "We must have a written prototype in this case.")(static_cast<void> (0));
741 if (FT->isConst())
742 POut << " const";
743 if (FT->isVolatile())
744 POut << " volatile";
745 RefQualifierKind Ref = MD->getRefQualifier();
746 if (Ref == RQ_LValue)
747 POut << " &";
748 else if (Ref == RQ_RValue)
749 POut << " &&";
750 }
751
752 typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
753 SpecsTy Specs;
754 const DeclContext *Ctx = FD->getDeclContext();
755 while (Ctx && isa<NamedDecl>(Ctx)) {
756 const ClassTemplateSpecializationDecl *Spec
757 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
758 if (Spec && !Spec->isExplicitSpecialization())
759 Specs.push_back(Spec);
760 Ctx = Ctx->getParent();
761 }
762
763 std::string TemplateParams;
764 llvm::raw_string_ostream TOut(TemplateParams);
765 for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
766 I != E; ++I) {
767 const TemplateParameterList *Params
768 = (*I)->getSpecializedTemplate()->getTemplateParameters();
769 const TemplateArgumentList &Args = (*I)->getTemplateArgs();
770 assert(Params->size() == Args.size())(static_cast<void> (0));
771 for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
772 StringRef Param = Params->getParam(i)->getName();
773 if (Param.empty()) continue;
774 TOut << Param << " = ";
775 Args.get(i).print(
776 Policy, TOut,
777 TemplateParameterList::shouldIncludeTypeForArgument(Params, i));
778 TOut << ", ";
779 }
780 }
781
782 FunctionTemplateSpecializationInfo *FSI
783 = FD->getTemplateSpecializationInfo();
784 if (FSI && !FSI->isExplicitSpecialization()) {
785 const TemplateParameterList* Params
786 = FSI->getTemplate()->getTemplateParameters();
787 const TemplateArgumentList* Args = FSI->TemplateArguments;
788 assert(Params->size() == Args->size())(static_cast<void> (0));
789 for (unsigned i = 0, e = Params->size(); i != e; ++i) {
790 StringRef Param = Params->getParam(i)->getName();
791 if (Param.empty()) continue;
792 TOut << Param << " = ";
793 Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
794 TOut << ", ";
795 }
796 }
797
798 TOut.flush();
799 if (!TemplateParams.empty()) {
800 // remove the trailing comma and space
801 TemplateParams.resize(TemplateParams.size() - 2);
802 POut << " [" << TemplateParams << "]";
803 }
804
805 POut.flush();
806
807 // Print "auto" for all deduced return types. This includes C++1y return
808 // type deduction and lambdas. For trailing return types resolve the
809 // decltype expression. Otherwise print the real type when this is
810 // not a constructor or destructor.
811 if (isa<CXXMethodDecl>(FD) &&
812 cast<CXXMethodDecl>(FD)->getParent()->isLambda())
813 Proto = "auto " + Proto;
814 else if (FT && FT->getReturnType()->getAs<DecltypeType>())
815 FT->getReturnType()
816 ->getAs<DecltypeType>()
817 ->getUnderlyingType()
818 .getAsStringInternal(Proto, Policy);
819 else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
820 AFT->getReturnType().getAsStringInternal(Proto, Policy);
821
822 Out << Proto;
823
824 return std::string(Name);
825 }
826 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
827 for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
828 // Skip to its enclosing function or method, but not its enclosing
829 // CapturedDecl.
830 if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
831 const Decl *D = Decl::castFromDeclContext(DC);
832 return ComputeName(IK, D);
833 }
834 llvm_unreachable("CapturedDecl not inside a function or method")__builtin_unreachable();
835 }
836 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
837 SmallString<256> Name;
838 llvm::raw_svector_ostream Out(Name);
839 Out << (MD->isInstanceMethod() ? '-' : '+');
840 Out << '[';
841
842 // For incorrect code, there might not be an ObjCInterfaceDecl. Do
843 // a null check to avoid a crash.
844 if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
845 Out << *ID;
846
847 if (const ObjCCategoryImplDecl *CID =
848 dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
849 Out << '(' << *CID << ')';
850
851 Out << ' ';
852 MD->getSelector().print(Out);
853 Out << ']';
854
855 return std::string(Name);
856 }
857 if (isa<TranslationUnitDecl>(CurrentDecl) && IK == PrettyFunction) {
858 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
859 return "top level";
860 }
861 return "";
862}
863
864void APNumericStorage::setIntValue(const ASTContext &C,
865 const llvm::APInt &Val) {
866 if (hasAllocation())
867 C.Deallocate(pVal);
868
869 BitWidth = Val.getBitWidth();
870 unsigned NumWords = Val.getNumWords();
871 const uint64_t* Words = Val.getRawData();
872 if (NumWords > 1) {
873 pVal = new (C) uint64_t[NumWords];
874 std::copy(Words, Words + NumWords, pVal);
875 } else if (NumWords == 1)
876 VAL = Words[0];
877 else
878 VAL = 0;
879}
880
881IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
882 QualType type, SourceLocation l)
883 : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
884 assert(type->isIntegerType() && "Illegal type in IntegerLiteral")(static_cast<void> (0));
885 assert(V.getBitWidth() == C.getIntWidth(type) &&(static_cast<void> (0))
886 "Integer type is not the correct size for constant.")(static_cast<void> (0));
887 setValue(C, V);
888 setDependence(ExprDependence::None);
889}
890
891IntegerLiteral *
892IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
893 QualType type, SourceLocation l) {
894 return new (C) IntegerLiteral(C, V, type, l);
895}
896
897IntegerLiteral *
898IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
899 return new (C) IntegerLiteral(Empty);
900}
901
902FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
903 QualType type, SourceLocation l,
904 unsigned Scale)
905 : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
906 Scale(Scale) {
907 assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral")(static_cast<void> (0));
908 assert(V.getBitWidth() == C.getTypeInfo(type).Width &&(static_cast<void> (0))
909 "Fixed point type is not the correct size for constant.")(static_cast<void> (0));
910 setValue(C, V);
911 setDependence(ExprDependence::None);
912}
913
914FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
915 const llvm::APInt &V,
916 QualType type,
917 SourceLocation l,
918 unsigned Scale) {
919 return new (C) FixedPointLiteral(C, V, type, l, Scale);
920}
921
922FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
923 EmptyShell Empty) {
924 return new (C) FixedPointLiteral(Empty);
925}
926
927std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
928 // Currently the longest decimal number that can be printed is the max for an
929 // unsigned long _Accum: 4294967295.99999999976716935634613037109375
930 // which is 43 characters.
931 SmallString<64> S;
932 FixedPointValueToString(
933 S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
934 return std::string(S.str());
935}
936
937void CharacterLiteral::print(unsigned Val, CharacterKind Kind,
938 raw_ostream &OS) {
939 switch (Kind) {
940 case CharacterLiteral::Ascii:
941 break; // no prefix.
942 case CharacterLiteral::Wide:
943 OS << 'L';
944 break;
945 case CharacterLiteral::UTF8:
946 OS << "u8";
947 break;
948 case CharacterLiteral::UTF16:
949 OS << 'u';
950 break;
951 case CharacterLiteral::UTF32:
952 OS << 'U';
953 break;
954 }
955
956 switch (Val) {
957 case '\\':
958 OS << "'\\\\'";
959 break;
960 case '\'':
961 OS << "'\\''";
962 break;
963 case '\a':
964 // TODO: K&R: the meaning of '\\a' is different in traditional C
965 OS << "'\\a'";
966 break;
967 case '\b':
968 OS << "'\\b'";
969 break;
970 // Nonstandard escape sequence.
971 /*case '\e':
972 OS << "'\\e'";
973 break;*/
974 case '\f':
975 OS << "'\\f'";
976 break;
977 case '\n':
978 OS << "'\\n'";
979 break;
980 case '\r':
981 OS << "'\\r'";
982 break;
983 case '\t':
984 OS << "'\\t'";
985 break;
986 case '\v':
987 OS << "'\\v'";
988 break;
989 default:
990 // A character literal might be sign-extended, which
991 // would result in an invalid \U escape sequence.
992 // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
993 // are not correctly handled.
994 if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteral::Ascii)
995 Val &= 0xFFu;
996 if (Val < 256 && isPrintable((unsigned char)Val))
997 OS << "'" << (char)Val << "'";
998 else if (Val < 256)
999 OS << "'\\x" << llvm::format("%02x", Val) << "'";
1000 else if (Val <= 0xFFFF)
1001 OS << "'\\u" << llvm::format("%04x", Val) << "'";
1002 else
1003 OS << "'\\U" << llvm::format("%08x", Val) << "'";
1004 }
1005}
1006
1007FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1008 bool isexact, QualType Type, SourceLocation L)
1009 : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1010 setSemantics(V.getSemantics());
1011 FloatingLiteralBits.IsExact = isexact;
1012 setValue(C, V);
1013 setDependence(ExprDependence::None);
1014}
1015
1016FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1017 : Expr(FloatingLiteralClass, Empty) {
1018 setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1019 FloatingLiteralBits.IsExact = false;
1020}
1021
1022FloatingLiteral *
1023FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1024 bool isexact, QualType Type, SourceLocation L) {
1025 return new (C) FloatingLiteral(C, V, isexact, Type, L);
1026}
1027
1028FloatingLiteral *
1029FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
1030 return new (C) FloatingLiteral(C, Empty);
1031}
1032
1033/// getValueAsApproximateDouble - This returns the value as an inaccurate
1034/// double. Note that this may cause loss of precision, but is useful for
1035/// debugging dumps, etc.
1036double FloatingLiteral::getValueAsApproximateDouble() const {
1037 llvm::APFloat V = getValue();
1038 bool ignored;
1039 V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1040 &ignored);
1041 return V.convertToDouble();
1042}
1043
1044unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1045 StringKind SK) {
1046 unsigned CharByteWidth = 0;
1047 switch (SK) {
1048 case Ascii:
1049 case UTF8:
1050 CharByteWidth = Target.getCharWidth();
1051 break;
1052 case Wide:
1053 CharByteWidth = Target.getWCharWidth();
1054 break;
1055 case UTF16:
1056 CharByteWidth = Target.getChar16Width();
1057 break;
1058 case UTF32:
1059 CharByteWidth = Target.getChar32Width();
1060 break;
1061 }
1062 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple")(static_cast<void> (0));
1063 CharByteWidth /= 8;
1064 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&(static_cast<void> (0))
1065 "The only supported character byte widths are 1,2 and 4!")(static_cast<void> (0));
1066 return CharByteWidth;
1067}
1068
1069StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1070 StringKind Kind, bool Pascal, QualType Ty,
1071 const SourceLocation *Loc,
1072 unsigned NumConcatenated)
1073 : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1074 assert(Ctx.getAsConstantArrayType(Ty) &&(static_cast<void> (0))
1075 "StringLiteral must be of constant array type!")(static_cast<void> (0));
1076 unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1077 unsigned ByteLength = Str.size();
1078 assert((ByteLength % CharByteWidth == 0) &&(static_cast<void> (0))
1079 "The size of the data must be a multiple of CharByteWidth!")(static_cast<void> (0));
1080
1081 // Avoid the expensive division. The compiler should be able to figure it
1082 // out by itself. However as of clang 7, even with the appropriate
1083 // llvm_unreachable added just here, it is not able to do so.
1084 unsigned Length;
1085 switch (CharByteWidth) {
1086 case 1:
1087 Length = ByteLength;
1088 break;
1089 case 2:
1090 Length = ByteLength / 2;
1091 break;
1092 case 4:
1093 Length = ByteLength / 4;
1094 break;
1095 default:
1096 llvm_unreachable("Unsupported character width!")__builtin_unreachable();
1097 }
1098
1099 StringLiteralBits.Kind = Kind;
1100 StringLiteralBits.CharByteWidth = CharByteWidth;
1101 StringLiteralBits.IsPascal = Pascal;
1102 StringLiteralBits.NumConcatenated = NumConcatenated;
1103 *getTrailingObjects<unsigned>() = Length;
1104
1105 // Initialize the trailing array of SourceLocation.
1106 // This is safe since SourceLocation is POD-like.
1107 std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1108 NumConcatenated * sizeof(SourceLocation));
1109
1110 // Initialize the trailing array of char holding the string data.
1111 std::memcpy(getTrailingObjects<char>(), Str.data(), ByteLength);
1112
1113 setDependence(ExprDependence::None);
1114}
1115
1116StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1117 unsigned Length, unsigned CharByteWidth)
1118 : Expr(StringLiteralClass, Empty) {
1119 StringLiteralBits.CharByteWidth = CharByteWidth;
1120 StringLiteralBits.NumConcatenated = NumConcatenated;
1121 *getTrailingObjects<unsigned>() = Length;
1122}
1123
1124StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1125 StringKind Kind, bool Pascal, QualType Ty,
1126 const SourceLocation *Loc,
1127 unsigned NumConcatenated) {
1128 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1129 1, NumConcatenated, Str.size()),
1130 alignof(StringLiteral));
1131 return new (Mem)
1132 StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1133}
1134
1135StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1136 unsigned NumConcatenated,
1137 unsigned Length,
1138 unsigned CharByteWidth) {
1139 void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1140 1, NumConcatenated, Length * CharByteWidth),
1141 alignof(StringLiteral));
1142 return new (Mem)
1143 StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1144}
1145
1146void StringLiteral::outputString(raw_ostream &OS) const {
1147 switch (getKind()) {
1148 case Ascii: break; // no prefix.
1149 case Wide: OS << 'L'; break;
1150 case UTF8: OS << "u8"; break;
1151 case UTF16: OS << 'u'; break;
1152 case UTF32: OS << 'U'; break;
1153 }
1154 OS << '"';
1155 static const char Hex[] = "0123456789ABCDEF";
1156
1157 unsigned LastSlashX = getLength();
1158 for (unsigned I = 0, N = getLength(); I != N; ++I) {
1159 switch (uint32_t Char = getCodeUnit(I)) {
1160 default:
1161 // FIXME: Convert UTF-8 back to codepoints before rendering.
1162
1163 // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1164 // Leave invalid surrogates alone; we'll use \x for those.
1165 if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
1166 Char <= 0xdbff) {
1167 uint32_t Trail = getCodeUnit(I + 1);
1168 if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1169 Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1170 ++I;
1171 }
1172 }
1173
1174 if (Char > 0xff) {
1175 // If this is a wide string, output characters over 0xff using \x
1176 // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1177 // codepoint: use \x escapes for invalid codepoints.
1178 if (getKind() == Wide ||
1179 (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1180 // FIXME: Is this the best way to print wchar_t?
1181 OS << "\\x";
1182 int Shift = 28;
1183 while ((Char >> Shift) == 0)
1184 Shift -= 4;
1185 for (/**/; Shift >= 0; Shift -= 4)
1186 OS << Hex[(Char >> Shift) & 15];
1187 LastSlashX = I;
1188 break;
1189 }
1190
1191 if (Char > 0xffff)
1192 OS << "\\U00"
1193 << Hex[(Char >> 20) & 15]
1194 << Hex[(Char >> 16) & 15];
1195 else
1196 OS << "\\u";
1197 OS << Hex[(Char >> 12) & 15]
1198 << Hex[(Char >> 8) & 15]
1199 << Hex[(Char >> 4) & 15]
1200 << Hex[(Char >> 0) & 15];
1201 break;
1202 }
1203
1204 // If we used \x... for the previous character, and this character is a
1205 // hexadecimal digit, prevent it being slurped as part of the \x.
1206 if (LastSlashX + 1 == I) {
1207 switch (Char) {
1208 case '0': case '1': case '2': case '3': case '4':
1209 case '5': case '6': case '7': case '8': case '9':
1210 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1211 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1212 OS << "\"\"";
1213 }
1214 }
1215
1216 assert(Char <= 0xff &&(static_cast<void> (0))
1217 "Characters above 0xff should already have been handled.")(static_cast<void> (0));
1218
1219 if (isPrintable(Char))
1220 OS << (char)Char;
1221 else // Output anything hard as an octal escape.
1222 OS << '\\'
1223 << (char)('0' + ((Char >> 6) & 7))
1224 << (char)('0' + ((Char >> 3) & 7))
1225 << (char)('0' + ((Char >> 0) & 7));
1226 break;
1227 // Handle some common non-printable cases to make dumps prettier.
1228 case '\\': OS << "\\\\"; break;
1229 case '"': OS << "\\\""; break;
1230 case '\a': OS << "\\a"; break;
1231 case '\b': OS << "\\b"; break;
1232 case '\f': OS << "\\f"; break;
1233 case '\n': OS << "\\n"; break;
1234 case '\r': OS << "\\r"; break;
1235 case '\t': OS << "\\t"; break;
1236 case '\v': OS << "\\v"; break;
1237 }
1238 }
1239 OS << '"';
1240}
1241
1242/// getLocationOfByte - Return a source location that points to the specified
1243/// byte of this string literal.
1244///
1245/// Strings are amazingly complex. They can be formed from multiple tokens and
1246/// can have escape sequences in them in addition to the usual trigraph and
1247/// escaped newline business. This routine handles this complexity.
1248///
1249/// The *StartToken sets the first token to be searched in this function and
1250/// the *StartTokenByteOffset is the byte offset of the first token. Before
1251/// returning, it updates the *StartToken to the TokNo of the token being found
1252/// and sets *StartTokenByteOffset to the byte offset of the token in the
1253/// string.
1254/// Using these two parameters can reduce the time complexity from O(n^2) to
1255/// O(n) if one wants to get the location of byte for all the tokens in a
1256/// string.
1257///
1258SourceLocation
1259StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1260 const LangOptions &Features,
1261 const TargetInfo &Target, unsigned *StartToken,
1262 unsigned *StartTokenByteOffset) const {
1263 assert((getKind() == StringLiteral::Ascii ||(static_cast<void> (0))
1264 getKind() == StringLiteral::UTF8) &&(static_cast<void> (0))
1265 "Only narrow string literals are currently supported")(static_cast<void> (0));
1266
1267 // Loop over all of the tokens in this string until we find the one that
1268 // contains the byte we're looking for.
1269 unsigned TokNo = 0;
1270 unsigned StringOffset = 0;
1271 if (StartToken)
1272 TokNo = *StartToken;
1273 if (StartTokenByteOffset) {
1274 StringOffset = *StartTokenByteOffset;
1275 ByteNo -= StringOffset;
1276 }
1277 while (1) {
1278 assert(TokNo < getNumConcatenated() && "Invalid byte number!")(static_cast<void> (0));
1279 SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1280
1281 // Get the spelling of the string so that we can get the data that makes up
1282 // the string literal, not the identifier for the macro it is potentially
1283 // expanded through.
1284 SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1285
1286 // Re-lex the token to get its length and original spelling.
1287 std::pair<FileID, unsigned> LocInfo =
1288 SM.getDecomposedLoc(StrTokSpellingLoc);
1289 bool Invalid = false;
1290 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1291 if (Invalid) {
1292 if (StartTokenByteOffset != nullptr)
1293 *StartTokenByteOffset = StringOffset;
1294 if (StartToken != nullptr)
1295 *StartToken = TokNo;
1296 return StrTokSpellingLoc;
1297 }
1298
1299 const char *StrData = Buffer.data()+LocInfo.second;
1300
1301 // Create a lexer starting at the beginning of this token.
1302 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1303 Buffer.begin(), StrData, Buffer.end());
1304 Token TheTok;
1305 TheLexer.LexFromRawLexer(TheTok);
1306
1307 // Use the StringLiteralParser to compute the length of the string in bytes.
1308 StringLiteralParser SLP(TheTok, SM, Features, Target);
1309 unsigned TokNumBytes = SLP.GetStringLength();
1310
1311 // If the byte is in this token, return the location of the byte.
1312 if (ByteNo < TokNumBytes ||
1313 (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1314 unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1315
1316 // Now that we know the offset of the token in the spelling, use the
1317 // preprocessor to get the offset in the original source.
1318 if (StartTokenByteOffset != nullptr)
1319 *StartTokenByteOffset = StringOffset;
1320 if (StartToken != nullptr)
1321 *StartToken = TokNo;
1322 return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1323 }
1324
1325 // Move to the next string token.
1326 StringOffset += TokNumBytes;
1327 ++TokNo;
1328 ByteNo -= TokNumBytes;
1329 }
1330}
1331
1332/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1333/// corresponds to, e.g. "sizeof" or "[pre]++".
1334StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1335 switch (Op) {
1336#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1337#include "clang/AST/OperationKinds.def"
1338 }
1339 llvm_unreachable("Unknown unary operator")__builtin_unreachable();
1340}
1341
1342UnaryOperatorKind
1343UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1344 switch (OO) {
1345 default: llvm_unreachable("No unary operator for overloaded function")__builtin_unreachable();
1346 case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc;
1347 case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1348 case OO_Amp: return UO_AddrOf;
1349 case OO_Star: return UO_Deref;
1350 case OO_Plus: return UO_Plus;
1351 case OO_Minus: return UO_Minus;
1352 case OO_Tilde: return UO_Not;
1353 case OO_Exclaim: return UO_LNot;
1354 case OO_Coawait: return UO_Coawait;
1355 }
1356}
1357
1358OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1359 switch (Opc) {
1360 case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1361 case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1362 case UO_AddrOf: return OO_Amp;
1363 case UO_Deref: return OO_Star;
1364 case UO_Plus: return OO_Plus;
1365 case UO_Minus: return OO_Minus;
1366 case UO_Not: return OO_Tilde;
1367 case UO_LNot: return OO_Exclaim;
1368 case UO_Coawait: return OO_Coawait;
1369 default: return OO_None;
1370 }
1371}
1372
1373
1374//===----------------------------------------------------------------------===//
1375// Postfix Operators.
1376//===----------------------------------------------------------------------===//
1377
1378CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1379 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1380 SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1381 unsigned MinNumArgs, ADLCallKind UsesADL)
1382 : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1383 NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1384 unsigned NumPreArgs = PreArgs.size();
1385 CallExprBits.NumPreArgs = NumPreArgs;
1386 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!")(static_cast<void> (0));
1387
1388 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1389 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1390 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&(static_cast<void> (0))
1391 "OffsetToTrailingObjects overflow!")(static_cast<void> (0));
1392
1393 CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1394
1395 setCallee(Fn);
1396 for (unsigned I = 0; I != NumPreArgs; ++I)
1397 setPreArg(I, PreArgs[I]);
1398 for (unsigned I = 0; I != Args.size(); ++I)
1399 setArg(I, Args[I]);
1400 for (unsigned I = Args.size(); I != NumArgs; ++I)
1401 setArg(I, nullptr);
1402
1403 this->computeDependence();
1404
1405 CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1406 if (hasStoredFPFeatures())
1407 setStoredFPFeatures(FPFeatures);
1408}
1409
1410CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1411 bool HasFPFeatures, EmptyShell Empty)
1412 : Expr(SC, Empty), NumArgs(NumArgs) {
1413 CallExprBits.NumPreArgs = NumPreArgs;
1414 assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!")(static_cast<void> (0));
1415
1416 unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1417 CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1418 assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&(static_cast<void> (0))
1419 "OffsetToTrailingObjects overflow!")(static_cast<void> (0));
1420 CallExprBits.HasFPFeatures = HasFPFeatures;
1421}
1422
1423CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1424 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1425 SourceLocation RParenLoc,
1426 FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1427 ADLCallKind UsesADL) {
1428 unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1429 unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1430 /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1431 void *Mem =
1432 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1433 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1434 RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1435}
1436
1437CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1438 ExprValueKind VK, SourceLocation RParenLoc,
1439 ADLCallKind UsesADL) {
1440 assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&(static_cast<void> (0))
1441 "Misaligned memory in CallExpr::CreateTemporary!")(static_cast<void> (0));
1442 return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1443 VK, RParenLoc, FPOptionsOverride(),
1444 /*MinNumArgs=*/0, UsesADL);
1445}
1446
1447CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1448 bool HasFPFeatures, EmptyShell Empty) {
1449 unsigned SizeOfTrailingObjects =
1450 CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1451 void *Mem =
1452 Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1453 return new (Mem)
1454 CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1455}
1456
1457unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1458 switch (SC) {
1459 case CallExprClass:
1460 return sizeof(CallExpr);
1461 case CXXOperatorCallExprClass:
1462 return sizeof(CXXOperatorCallExpr);
1463 case CXXMemberCallExprClass:
1464 return sizeof(CXXMemberCallExpr);
1465 case UserDefinedLiteralClass:
1466 return sizeof(UserDefinedLiteral);
1467 case CUDAKernelCallExprClass:
1468 return sizeof(CUDAKernelCallExpr);
1469 default:
1470 llvm_unreachable("unexpected class deriving from CallExpr!")__builtin_unreachable();
1471 }
1472}
1473
1474Decl *Expr::getReferencedDeclOfCallee() {
1475 Expr *CEE = IgnoreParenImpCasts();
1476
1477 while (SubstNonTypeTemplateParmExpr *NTTP =
1478 dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1479 CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1480 }
1481
1482 // If we're calling a dereference, look at the pointer instead.
1483 while (true) {
1484 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1485 if (BO->isPtrMemOp()) {
1486 CEE = BO->getRHS()->IgnoreParenImpCasts();
1487 continue;
1488 }
1489 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1490 if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1491 UO->getOpcode() == UO_Plus) {
1492 CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1493 continue;
1494 }
1495 }
1496 break;
1497 }
1498
1499 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1500 return DRE->getDecl();
1501 if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1502 return ME->getMemberDecl();
1503 if (auto *BE = dyn_cast<BlockExpr>(CEE))
1504 return BE->getBlockDecl();
1505
1506 return nullptr;
1507}
1508
1509/// If this is a call to a builtin, return the builtin ID. If not, return 0.
1510unsigned CallExpr::getBuiltinCallee() const {
1511 auto *FDecl =
1512 dyn_cast_or_null<FunctionDecl>(getCallee()->getReferencedDeclOfCallee());
1513 return FDecl ? FDecl->getBuiltinID() : 0;
1514}
1515
1516bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1517 if (unsigned BI = getBuiltinCallee())
1518 return Ctx.BuiltinInfo.isUnevaluated(BI);
1519 return false;
1520}
1521
1522QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1523 const Expr *Callee = getCallee();
1524 QualType CalleeType = Callee->getType();
1525 if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1526 CalleeType = FnTypePtr->getPointeeType();
1527 } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1528 CalleeType = BPT->getPointeeType();
1529 } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1530 if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1531 return Ctx.VoidTy;
1532
1533 if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1534 return Ctx.DependentTy;
1535
1536 // This should never be overloaded and so should never return null.
1537 CalleeType = Expr::findBoundMemberType(Callee);
1538 assert(!CalleeType.isNull())(static_cast<void> (0));
1539 } else if (CalleeType->isDependentType() ||
1540 CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1541 return Ctx.DependentTy;
1542 }
1543
1544 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1545 return FnType->getReturnType();
1546}
1547
1548const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1549 // If the return type is a struct, union, or enum that is marked nodiscard,
1550 // then return the return type attribute.
1551 if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1552 if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1553 return A;
1554
1555 // Otherwise, see if the callee is marked nodiscard and return that attribute
1556 // instead.
1557 const Decl *D = getCalleeDecl();
1558 return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1559}
1560
1561SourceLocation CallExpr::getBeginLoc() const {
1562 if (isa<CXXOperatorCallExpr>(this))
1563 return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1564
1565 SourceLocation begin = getCallee()->getBeginLoc();
1566 if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1567 begin = getArg(0)->getBeginLoc();
1568 return begin;
1569}
1570SourceLocation CallExpr::getEndLoc() const {
1571 if (isa<CXXOperatorCallExpr>(this))
1572 return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1573
1574 SourceLocation end = getRParenLoc();
1575 if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1576 end = getArg(getNumArgs() - 1)->getEndLoc();
1577 return end;
1578}
1579
1580OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1581 SourceLocation OperatorLoc,
1582 TypeSourceInfo *tsi,
1583 ArrayRef<OffsetOfNode> comps,
1584 ArrayRef<Expr*> exprs,
1585 SourceLocation RParenLoc) {
1586 void *Mem = C.Allocate(
1587 totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1588
1589 return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1590 RParenLoc);
1591}
1592
1593OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1594 unsigned numComps, unsigned numExprs) {
1595 void *Mem =
1596 C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1597 return new (Mem) OffsetOfExpr(numComps, numExprs);
1598}
1599
1600OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1601 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1602 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1603 SourceLocation RParenLoc)
1604 : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1605 OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1606 NumComps(comps.size()), NumExprs(exprs.size()) {
1607 for (unsigned i = 0; i != comps.size(); ++i)
1608 setComponent(i, comps[i]);
1609 for (unsigned i = 0; i != exprs.size(); ++i)
1610 setIndexExpr(i, exprs[i]);
1611
1612 setDependence(computeDependence(this));
1613}
1614
1615IdentifierInfo *OffsetOfNode::getFieldName() const {
1616 assert(getKind() == Field || getKind() == Identifier)(static_cast<void> (0));
1617 if (getKind() == Field)
1618 return getField()->getIdentifier();
1619
1620 return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1621}
1622
1623UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1624 UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1625 SourceLocation op, SourceLocation rp)
1626 : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1627 OpLoc(op), RParenLoc(rp) {
1628 assert(ExprKind <= UETT_Last && "invalid enum value!")(static_cast<void> (0));
1629 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1630 assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&(static_cast<void> (0))
1631 "UnaryExprOrTypeTraitExprBits.Kind overflow!")(static_cast<void> (0));
1632 UnaryExprOrTypeTraitExprBits.IsType = false;
1633 Argument.Ex = E;
1634 setDependence(computeDependence(this));
1635}
1636
1637MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1638 ValueDecl *MemberDecl,
1639 const DeclarationNameInfo &NameInfo, QualType T,
1640 ExprValueKind VK, ExprObjectKind OK,
1641 NonOdrUseReason NOUR)
1642 : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1643 MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1644 assert(!NameInfo.getName() ||(static_cast<void> (0))
1645 MemberDecl->getDeclName() == NameInfo.getName())(static_cast<void> (0));
1646 MemberExprBits.IsArrow = IsArrow;
1647 MemberExprBits.HasQualifierOrFoundDecl = false;
1648 MemberExprBits.HasTemplateKWAndArgsInfo = false;
1649 MemberExprBits.HadMultipleCandidates = false;
1650 MemberExprBits.NonOdrUseReason = NOUR;
1651 MemberExprBits.OperatorLoc = OperatorLoc;
1652 setDependence(computeDependence(this));
1653}
1654
1655MemberExpr *MemberExpr::Create(
1656 const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1657 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1658 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1659 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1660 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1661 bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1662 FoundDecl.getAccess() != MemberDecl->getAccess();
1663 bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1664 std::size_t Size =
1665 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1666 TemplateArgumentLoc>(
1667 HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1668 TemplateArgs ? TemplateArgs->size() : 0);
1669
1670 void *Mem = C.Allocate(Size, alignof(MemberExpr));
1671 MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1672 NameInfo, T, VK, OK, NOUR);
1673
1674 // FIXME: remove remaining dependence computation to computeDependence().
1675 auto Deps = E->getDependence();
1676 if (HasQualOrFound) {
1677 // FIXME: Wrong. We should be looking at the member declaration we found.
1678 if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent())
1679 Deps |= ExprDependence::TypeValueInstantiation;
1680 else if (QualifierLoc &&
1681 QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1682 Deps |= ExprDependence::Instantiation;
1683
1684 E->MemberExprBits.HasQualifierOrFoundDecl = true;
1685
1686 MemberExprNameQualifier *NQ =
1687 E->getTrailingObjects<MemberExprNameQualifier>();
1688 NQ->QualifierLoc = QualifierLoc;
1689 NQ->FoundDecl = FoundDecl;
1690 }
1691
1692 E->MemberExprBits.HasTemplateKWAndArgsInfo =
1693 TemplateArgs || TemplateKWLoc.isValid();
1694
1695 if (TemplateArgs) {
1696 auto TemplateArgDeps = TemplateArgumentDependence::None;
1697 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1698 TemplateKWLoc, *TemplateArgs,
1699 E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1700 if (TemplateArgDeps & TemplateArgumentDependence::Instantiation)
1701 Deps |= ExprDependence::Instantiation;
1702 } else if (TemplateKWLoc.isValid()) {
1703 E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1704 TemplateKWLoc);
1705 }
1706 E->setDependence(Deps);
1707
1708 return E;
1709}
1710
1711MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1712 bool HasQualifier, bool HasFoundDecl,
1713 bool HasTemplateKWAndArgsInfo,
1714 unsigned NumTemplateArgs) {
1715 assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&(static_cast<void> (0))
1716 "template args but no template arg info?")(static_cast<void> (0));
1717 bool HasQualOrFound = HasQualifier || HasFoundDecl;
1718 std::size_t Size =
1719 totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1720 TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1721 HasTemplateKWAndArgsInfo ? 1 : 0,
1722 NumTemplateArgs);
1723 void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1724 return new (Mem) MemberExpr(EmptyShell());
1725}
1726
1727void MemberExpr::setMemberDecl(ValueDecl *NewD) {
1728 MemberDecl = NewD;
1729 if (getType()->isUndeducedType())
1730 setType(NewD->getType());
1731 setDependence(computeDependence(this));
1732}
1733
1734SourceLocation MemberExpr::getBeginLoc() const {
1735 if (isImplicitAccess()) {
1736 if (hasQualifier())
1737 return getQualifierLoc().getBeginLoc();
1738 return MemberLoc;
1739 }
1740
1741 // FIXME: We don't want this to happen. Rather, we should be able to
1742 // detect all kinds of implicit accesses more cleanly.
1743 SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1744 if (BaseStartLoc.isValid())
1745 return BaseStartLoc;
1746 return MemberLoc;
1747}
1748SourceLocation MemberExpr::getEndLoc() const {
1749 SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1750 if (hasExplicitTemplateArgs())
1751 EndLoc = getRAngleLoc();
1752 else if (EndLoc.isInvalid())
1753 EndLoc = getBase()->getEndLoc();
1754 return EndLoc;
1755}
1756
1757bool CastExpr::CastConsistency() const {
1758 switch (getCastKind()) {
1759 case CK_DerivedToBase:
1760 case CK_UncheckedDerivedToBase:
1761 case CK_DerivedToBaseMemberPointer:
1762 case CK_BaseToDerived:
1763 case CK_BaseToDerivedMemberPointer:
1764 assert(!path_empty() && "Cast kind should have a base path!")(static_cast<void> (0));
1765 break;
1766
1767 case CK_CPointerToObjCPointerCast:
1768 assert(getType()->isObjCObjectPointerType())(static_cast<void> (0));
1769 assert(getSubExpr()->getType()->isPointerType())(static_cast<void> (0));
1770 goto CheckNoBasePath;
1771
1772 case CK_BlockPointerToObjCPointerCast:
1773 assert(getType()->isObjCObjectPointerType())(static_cast<void> (0));
1774 assert(getSubExpr()->getType()->isBlockPointerType())(static_cast<void> (0));
1775 goto CheckNoBasePath;
1776
1777 case CK_ReinterpretMemberPointer:
1778 assert(getType()->isMemberPointerType())(static_cast<void> (0));
1779 assert(getSubExpr()->getType()->isMemberPointerType())(static_cast<void> (0));
1780 goto CheckNoBasePath;
1781
1782 case CK_BitCast:
1783 // Arbitrary casts to C pointer types count as bitcasts.
1784 // Otherwise, we should only have block and ObjC pointer casts
1785 // here if they stay within the type kind.
1786 if (!getType()->isPointerType()) {
1787 assert(getType()->isObjCObjectPointerType() ==(static_cast<void> (0))
1788 getSubExpr()->getType()->isObjCObjectPointerType())(static_cast<void> (0));
1789 assert(getType()->isBlockPointerType() ==(static_cast<void> (0))
1790 getSubExpr()->getType()->isBlockPointerType())(static_cast<void> (0));
1791 }
1792 goto CheckNoBasePath;
1793
1794 case CK_AnyPointerToBlockPointerCast:
1795 assert(getType()->isBlockPointerType())(static_cast<void> (0));
1796 assert(getSubExpr()->getType()->isAnyPointerType() &&(static_cast<void> (0))
1797 !getSubExpr()->getType()->isBlockPointerType())(static_cast<void> (0));
1798 goto CheckNoBasePath;
1799
1800 case CK_CopyAndAutoreleaseBlockObject:
1801 assert(getType()->isBlockPointerType())(static_cast<void> (0));
1802 assert(getSubExpr()->getType()->isBlockPointerType())(static_cast<void> (0));
1803 goto CheckNoBasePath;
1804
1805 case CK_FunctionToPointerDecay:
1806 assert(getType()->isPointerType())(static_cast<void> (0));
1807 assert(getSubExpr()->getType()->isFunctionType())(static_cast<void> (0));
1808 goto CheckNoBasePath;
1809
1810 case CK_AddressSpaceConversion: {
1811 auto Ty = getType();
1812 auto SETy = getSubExpr()->getType();
1813 assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy))(static_cast<void> (0));
1814 if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1815 Ty = Ty->getPointeeType();
1816 SETy = SETy->getPointeeType();
1817 }
1818 assert((Ty->isDependentType() || SETy->isDependentType()) ||(static_cast<void> (0))
1819 (!Ty.isNull() && !SETy.isNull() &&(static_cast<void> (0))
1820 Ty.getAddressSpace() != SETy.getAddressSpace()))(static_cast<void> (0));
1821 goto CheckNoBasePath;
1822 }
1823 // These should not have an inheritance path.
1824 case CK_Dynamic:
1825 case CK_ToUnion:
1826 case CK_ArrayToPointerDecay:
1827 case CK_NullToMemberPointer:
1828 case CK_NullToPointer:
1829 case CK_ConstructorConversion:
1830 case CK_IntegralToPointer:
1831 case CK_PointerToIntegral:
1832 case CK_ToVoid:
1833 case CK_VectorSplat:
1834 case CK_IntegralCast:
1835 case CK_BooleanToSignedIntegral:
1836 case CK_IntegralToFloating:
1837 case CK_FloatingToIntegral:
1838 case CK_FloatingCast:
1839 case CK_ObjCObjectLValueCast:
1840 case CK_FloatingRealToComplex:
1841 case CK_FloatingComplexToReal:
1842 case CK_FloatingComplexCast:
1843 case CK_FloatingComplexToIntegralComplex:
1844 case CK_IntegralRealToComplex:
1845 case CK_IntegralComplexToReal:
1846 case CK_IntegralComplexCast:
1847 case CK_IntegralComplexToFloatingComplex:
1848 case CK_ARCProduceObject:
1849 case CK_ARCConsumeObject:
1850 case CK_ARCReclaimReturnedObject:
1851 case CK_ARCExtendBlockObject:
1852 case CK_ZeroToOCLOpaqueType:
1853 case CK_IntToOCLSampler:
1854 case CK_FloatingToFixedPoint:
1855 case CK_FixedPointToFloating:
1856 case CK_FixedPointCast:
1857 case CK_FixedPointToIntegral:
1858 case CK_IntegralToFixedPoint:
1859 case CK_MatrixCast:
1860 assert(!getType()->isBooleanType() && "unheralded conversion to bool")(static_cast<void> (0));
1861 goto CheckNoBasePath;
1862
1863 case CK_Dependent:
1864 case CK_LValueToRValue:
1865 case CK_NoOp:
1866 case CK_AtomicToNonAtomic:
1867 case CK_NonAtomicToAtomic:
1868 case CK_PointerToBoolean:
1869 case CK_IntegralToBoolean:
1870 case CK_FloatingToBoolean:
1871 case CK_MemberPointerToBoolean:
1872 case CK_FloatingComplexToBoolean:
1873 case CK_IntegralComplexToBoolean:
1874 case CK_LValueBitCast: // -> bool&
1875 case CK_LValueToRValueBitCast:
1876 case CK_UserDefinedConversion: // operator bool()
1877 case CK_BuiltinFnToFnPtr:
1878 case CK_FixedPointToBoolean:
1879 CheckNoBasePath:
1880 assert(path_empty() && "Cast kind should not have a base path!")(static_cast<void> (0));
1881 break;
1882 }
1883 return true;
1884}
1885
1886const char *CastExpr::getCastKindName(CastKind CK) {
1887 switch (CK) {
1888#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1889#include "clang/AST/OperationKinds.def"
1890 }
1891 llvm_unreachable("Unhandled cast kind!")__builtin_unreachable();
1892}
1893
1894namespace {
1895 const Expr *skipImplicitTemporary(const Expr *E) {
1896 // Skip through reference binding to temporary.
1897 if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1898 E = Materialize->getSubExpr();
1899
1900 // Skip any temporary bindings; they're implicit.
1901 if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1902 E = Binder->getSubExpr();
1903
1904 return E;
1905 }
1906}
1907
1908Expr *CastExpr::getSubExprAsWritten() {
1909 const Expr *SubExpr = nullptr;
1910 const CastExpr *E = this;
1911 do {
1912 SubExpr = skipImplicitTemporary(E->getSubExpr());
1913
1914 // Conversions by constructor and conversion functions have a
1915 // subexpression describing the call; strip it off.
1916 if (E->getCastKind() == CK_ConstructorConversion)
1917 SubExpr =
1918 skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr->IgnoreImplicit())->getArg(0));
1919 else if (E->getCastKind() == CK_UserDefinedConversion) {
1920 SubExpr = SubExpr->IgnoreImplicit();
1921 assert((isa<CXXMemberCallExpr>(SubExpr) ||(static_cast<void> (0))
1922 isa<BlockExpr>(SubExpr)) &&(static_cast<void> (0))
1923 "Unexpected SubExpr for CK_UserDefinedConversion.")(static_cast<void> (0));
1924 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1925 SubExpr = MCE->getImplicitObjectArgument();
1926 }
1927
1928 // If the subexpression we're left with is an implicit cast, look
1929 // through that, too.
1930 } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1931
1932 return const_cast<Expr*>(SubExpr);
1933}
1934
1935NamedDecl *CastExpr::getConversionFunction() const {
1936 const Expr *SubExpr = nullptr;
1937
1938 for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1939 SubExpr = skipImplicitTemporary(E->getSubExpr());
1940
1941 if (E->getCastKind() == CK_ConstructorConversion)
1942 return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1943
1944 if (E->getCastKind() == CK_UserDefinedConversion) {
1945 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1946 return MCE->getMethodDecl();
1947 }
1948 }
1949
1950 return nullptr;
1951}
1952
1953CXXBaseSpecifier **CastExpr::path_buffer() {
1954 switch (getStmtClass()) {
1955#define ABSTRACT_STMT(x)
1956#define CASTEXPR(Type, Base) \
1957 case Stmt::Type##Class: \
1958 return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1959#define STMT(Type, Base)
1960#include "clang/AST/StmtNodes.inc"
1961 default:
1962 llvm_unreachable("non-cast expressions not possible here")__builtin_unreachable();
1963 }
1964}
1965
1966const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1967 QualType opType) {
1968 auto RD = unionType->castAs<RecordType>()->getDecl();
1969 return getTargetFieldForToUnionCast(RD, opType);
1970}
1971
1972const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1973 QualType OpType) {
1974 auto &Ctx = RD->getASTContext();
1975 RecordDecl::field_iterator Field, FieldEnd;
1976 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1977 Field != FieldEnd; ++Field) {
1978 if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1979 !Field->isUnnamedBitfield()) {
1980 return *Field;
1981 }
1982 }
1983 return nullptr;
1984}
1985
1986FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
1987 assert(hasStoredFPFeatures())(static_cast<void> (0));
1988 switch (getStmtClass()) {
1989 case ImplicitCastExprClass:
1990 return static_cast<ImplicitCastExpr *>(this)
1991 ->getTrailingObjects<FPOptionsOverride>();
1992 case CStyleCastExprClass:
1993 return static_cast<CStyleCastExpr *>(this)
1994 ->getTrailingObjects<FPOptionsOverride>();
1995 case CXXFunctionalCastExprClass:
1996 return static_cast<CXXFunctionalCastExpr *>(this)
1997 ->getTrailingObjects<FPOptionsOverride>();
1998 case CXXStaticCastExprClass:
1999 return static_cast<CXXStaticCastExpr *>(this)
2000 ->getTrailingObjects<FPOptionsOverride>();
2001 default:
2002 llvm_unreachable("Cast does not have FPFeatures")__builtin_unreachable();
2003 }
2004}
2005
2006ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
2007 CastKind Kind, Expr *Operand,
2008 const CXXCastPath *BasePath,
2009 ExprValueKind VK,
2010 FPOptionsOverride FPO) {
2011 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2012 void *Buffer =
2013 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2014 PathSize, FPO.requiresTrailingStorage()));
2015 // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2016 // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2017 assert((Kind != CK_LValueToRValue ||(static_cast<void> (0))
2018 !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&(static_cast<void> (0))
2019 "invalid type for lvalue-to-rvalue conversion")(static_cast<void> (0));
2020 ImplicitCastExpr *E =
2021 new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2022 if (PathSize)
2023 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2024 E->getTrailingObjects<CXXBaseSpecifier *>());
2025 return E;
2026}
2027
2028ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
2029 unsigned PathSize,
2030 bool HasFPFeatures) {
2031 void *Buffer =
2032 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2033 PathSize, HasFPFeatures));
2034 return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2035}
2036
2037CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2038 ExprValueKind VK, CastKind K, Expr *Op,
2039 const CXXCastPath *BasePath,
2040 FPOptionsOverride FPO,
2041 TypeSourceInfo *WrittenTy,
2042 SourceLocation L, SourceLocation R) {
2043 unsigned PathSize = (BasePath ? BasePath->size() : 0);
2044 void *Buffer =
2045 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2046 PathSize, FPO.requiresTrailingStorage()));
2047 CStyleCastExpr *E =
2048 new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2049 if (PathSize)
2050 std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2051 E->getTrailingObjects<CXXBaseSpecifier *>());
2052 return E;
2053}
2054
2055CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2056 unsigned PathSize,
2057 bool HasFPFeatures) {
2058 void *Buffer =
2059 C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2060 PathSize, HasFPFeatures));
2061 return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2062}
2063
2064/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2065/// corresponds to, e.g. "<<=".
2066StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2067 switch (Op) {
2068#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2069#include "clang/AST/OperationKinds.def"
2070 }
2071 llvm_unreachable("Invalid OpCode!")__builtin_unreachable();
2072}
2073
2074BinaryOperatorKind
2075BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2076 switch (OO) {
2077 default: llvm_unreachable("Not an overloadable binary operator")__builtin_unreachable();
2078 case OO_Plus: return BO_Add;
2079 case OO_Minus: return BO_Sub;
2080 case OO_Star: return BO_Mul;
2081 case OO_Slash: return BO_Div;
2082 case OO_Percent: return BO_Rem;
2083 case OO_Caret: return BO_Xor;
2084 case OO_Amp: return BO_And;
2085 case OO_Pipe: return BO_Or;
2086 case OO_Equal: return BO_Assign;
2087 case OO_Spaceship: return BO_Cmp;
2088 case OO_Less: return BO_LT;
2089 case OO_Greater: return BO_GT;
2090 case OO_PlusEqual: return BO_AddAssign;
2091 case OO_MinusEqual: return BO_SubAssign;
2092 case OO_StarEqual: return BO_MulAssign;
2093 case OO_SlashEqual: return BO_DivAssign;
2094 case OO_PercentEqual: return BO_RemAssign;
2095 case OO_CaretEqual: return BO_XorAssign;
2096 case OO_AmpEqual: return BO_AndAssign;
2097 case OO_PipeEqual: return BO_OrAssign;
2098 case OO_LessLess: return BO_Shl;
2099 case OO_GreaterGreater: return BO_Shr;
2100 case OO_LessLessEqual: return BO_ShlAssign;
2101 case OO_GreaterGreaterEqual: return BO_ShrAssign;
2102 case OO_EqualEqual: return BO_EQ;
2103 case OO_ExclaimEqual: return BO_NE;
2104 case OO_LessEqual: return BO_LE;
2105 case OO_GreaterEqual: return BO_GE;
2106 case OO_AmpAmp: return BO_LAnd;
2107 case OO_PipePipe: return BO_LOr;
2108 case OO_Comma: return BO_Comma;
2109 case OO_ArrowStar: return BO_PtrMemI;
2110 }
2111}
2112
2113OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2114 static const OverloadedOperatorKind OverOps[] = {
2115 /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2116 OO_Star, OO_Slash, OO_Percent,
2117 OO_Plus, OO_Minus,
2118 OO_LessLess, OO_GreaterGreater,
2119 OO_Spaceship,
2120 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2121 OO_EqualEqual, OO_ExclaimEqual,
2122 OO_Amp,
2123 OO_Caret,
2124 OO_Pipe,
2125 OO_AmpAmp,
2126 OO_PipePipe,
2127 OO_Equal, OO_StarEqual,
2128 OO_SlashEqual, OO_PercentEqual,
2129 OO_PlusEqual, OO_MinusEqual,
2130 OO_LessLessEqual, OO_GreaterGreaterEqual,
2131 OO_AmpEqual, OO_CaretEqual,
2132 OO_PipeEqual,
2133 OO_Comma
2134 };
2135 return OverOps[Opc];
2136}
2137
2138bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2139 Opcode Opc,
2140 Expr *LHS, Expr *RHS) {
2141 if (Opc != BO_Add)
2142 return false;
2143
2144 // Check that we have one pointer and one integer operand.
2145 Expr *PExp;
2146 if (LHS->getType()->isPointerType()) {
2147 if (!RHS->getType()->isIntegerType())
2148 return false;
2149 PExp = LHS;
2150 } else if (RHS->getType()->isPointerType()) {
2151 if (!LHS->getType()->isIntegerType())
2152 return false;
2153 PExp = RHS;
2154 } else {
2155 return false;
2156 }
2157
2158 // Check that the pointer is a nullptr.
2159 if (!PExp->IgnoreParenCasts()
2160 ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2161 return false;
2162
2163 // Check that the pointee type is char-sized.
2164 const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2165 if (!PTy || !PTy->getPointeeType()->isCharType())
2166 return false;
2167
2168 return true;
2169}
2170
2171static QualType getDecayedSourceLocExprType(const ASTContext &Ctx,
2172 SourceLocExpr::IdentKind Kind) {
2173 switch (Kind) {
2174 case SourceLocExpr::File:
2175 case SourceLocExpr::Function: {
2176 QualType ArrTy = Ctx.getStringLiteralArrayType(Ctx.CharTy, 0);
2177 return Ctx.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
2178 }
2179 case SourceLocExpr::Line:
2180 case SourceLocExpr::Column:
2181 return Ctx.UnsignedIntTy;
2182 }
2183 llvm_unreachable("unhandled case")__builtin_unreachable();
2184}
2185
2186SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind,
2187 SourceLocation BLoc, SourceLocation RParenLoc,
2188 DeclContext *ParentContext)
2189 : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind),
2190 VK_PRValue, OK_Ordinary),
2191 BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2192 SourceLocExprBits.Kind = Kind;
2193 setDependence(ExprDependence::None);
2194}
2195
2196StringRef SourceLocExpr::getBuiltinStr() const {
2197 switch (getIdentKind()) {
2198 case File:
2199 return "__builtin_FILE";
2200 case Function:
2201 return "__builtin_FUNCTION";
2202 case Line:
2203 return "__builtin_LINE";
2204 case Column:
2205 return "__builtin_COLUMN";
2206 }
2207 llvm_unreachable("unexpected IdentKind!")__builtin_unreachable();
2208}
2209
2210APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2211 const Expr *DefaultExpr) const {
2212 SourceLocation Loc;
2213 const DeclContext *Context;
2214
2215 std::tie(Loc,
2216 Context) = [&]() -> std::pair<SourceLocation, const DeclContext *> {
2217 if (auto *DIE = dyn_cast_or_null<CXXDefaultInitExpr>(DefaultExpr))
2218 return {DIE->getUsedLocation(), DIE->getUsedContext()};
2219 if (auto *DAE = dyn_cast_or_null<CXXDefaultArgExpr>(DefaultExpr))
2220 return {DAE->getUsedLocation(), DAE->getUsedContext()};
2221 return {this->getLocation(), this->getParentContext()};
2222 }();
2223
2224 PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2225 Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2226
2227 auto MakeStringLiteral = [&](StringRef Tmp) {
2228 using LValuePathEntry = APValue::LValuePathEntry;
2229 StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2230 // Decay the string to a pointer to the first character.
2231 LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2232 return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2233 };
2234
2235 switch (getIdentKind()) {
2236 case SourceLocExpr::File: {
2237 SmallString<256> Path(PLoc.getFilename());
2238 Ctx.getLangOpts().remapPathPrefix(Path);
2239 return MakeStringLiteral(Path);
2240 }
2241 case SourceLocExpr::Function: {
2242 const Decl *CurDecl = dyn_cast_or_null<Decl>(Context);
2243 return MakeStringLiteral(
2244 CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl)
2245 : std::string(""));
2246 }
2247 case SourceLocExpr::Line:
2248 case SourceLocExpr::Column: {
2249 llvm::APSInt IntVal(Ctx.getIntWidth(Ctx.UnsignedIntTy),
2250 /*isUnsigned=*/true);
2251 IntVal = getIdentKind() == SourceLocExpr::Line ? PLoc.getLine()
2252 : PLoc.getColumn();
2253 return APValue(IntVal);
2254 }
2255 }
2256 llvm_unreachable("unhandled case")__builtin_unreachable();
2257}
2258
2259InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2260 ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2261 : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2262 InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2263 RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2264 sawArrayRangeDesignator(false);
2265 InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2266
2267 setDependence(computeDependence(this));
2268}
2269
2270void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2271 if (NumInits > InitExprs.size())
2272 InitExprs.reserve(C, NumInits);
2273}
2274
2275void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2276 InitExprs.resize(C, NumInits, nullptr);
2277}
2278
2279Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2280 if (Init >= InitExprs.size()) {
2281 InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2282 setInit(Init, expr);
2283 return nullptr;
2284 }
2285
2286 Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2287 setInit(Init, expr);
2288 return Result;
2289}
2290
2291void InitListExpr::setArrayFiller(Expr *filler) {
2292 assert(!hasArrayFiller() && "Filler already set!")(static_cast<void> (0));
2293 ArrayFillerOrUnionFieldInit = filler;
2294 // Fill out any "holes" in the array due to designated initializers.
2295 Expr **inits = getInits();
2296 for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2297 if (inits[i] == nullptr)
2298 inits[i] = filler;
2299}
2300
2301bool InitListExpr::isStringLiteralInit() const {
2302 if (getNumInits() != 1)
2303 return false;
2304 const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2305 if (!AT || !AT->getElementType()->isIntegerType())
2306 return false;
2307 // It is possible for getInit() to return null.
2308 const Expr *Init = getInit(0);
2309 if (!Init)
2310 return false;
2311 Init = Init->IgnoreParenImpCasts();
2312 return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2313}
2314
2315bool InitListExpr::isTransparent() const {
2316 assert(isSemanticForm() && "syntactic form never semantically transparent")(static_cast<void> (0));
2317
2318 // A glvalue InitListExpr is always just sugar.
2319 if (isGLValue()) {
2320 assert(getNumInits() == 1 && "multiple inits in glvalue init list")(static_cast<void> (0));
2321 return true;
2322 }
2323
2324 // Otherwise, we're sugar if and only if we have exactly one initializer that
2325 // is of the same type.
2326 if (getNumInits() != 1 || !getInit(0))
2327 return false;
2328
2329 // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2330 // transparent struct copy.
2331 if (!getInit(0)->isPRValue() && getType()->isRecordType())
2332 return false;
2333
2334 return getType().getCanonicalType() ==
2335 getInit(0)->getType().getCanonicalType();
2336}
2337
2338bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2339 assert(isSyntacticForm() && "only test syntactic form as zero initializer")(static_cast<void> (0));
2340
2341 if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2342 return false;
2343 }
2344
2345 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2346 return Lit && Lit->getValue() == 0;
2347}
2348
2349SourceLocation InitListExpr::getBeginLoc() const {
2350 if (InitListExpr *SyntacticForm = getSyntacticForm())
2351 return SyntacticForm->getBeginLoc();
2352 SourceLocation Beg = LBraceLoc;
2353 if (Beg.isInvalid()) {
2354 // Find the first non-null initializer.
2355 for (InitExprsTy::const_iterator I = InitExprs.begin(),
2356 E = InitExprs.end();
2357 I != E; ++I) {
2358 if (Stmt *S = *I) {
2359 Beg = S->getBeginLoc();
2360 break;
2361 }
2362 }
2363 }
2364 return Beg;
2365}
2366
2367SourceLocation InitListExpr::getEndLoc() const {
2368 if (InitListExpr *SyntacticForm = getSyntacticForm())
2369 return SyntacticForm->getEndLoc();
2370 SourceLocation End = RBraceLoc;
2371 if (End.isInvalid()) {
2372 // Find the first non-null initializer from the end.
2373 for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2374 E = InitExprs.rend();
2375 I != E; ++I) {
2376 if (Stmt *S = *I) {
2377 End = S->getEndLoc();
2378 break;
2379 }
2380 }
2381 }
2382 return End;
2383}
2384
2385/// getFunctionType - Return the underlying function type for this block.
2386///
2387const FunctionProtoType *BlockExpr::getFunctionType() const {
2388 // The block pointer is never sugared, but the function type might be.
2389 return cast<BlockPointerType>(getType())
2390 ->getPointeeType()->castAs<FunctionProtoType>();
2391}
2392
2393SourceLocation BlockExpr::getCaretLocation() const {
2394 return TheBlock->getCaretLocation();
2395}
2396const Stmt *BlockExpr::getBody() const {
2397 return TheBlock->getBody();
2398}
2399Stmt *BlockExpr::getBody() {
2400 return TheBlock->getBody();
2401}
2402
2403
2404//===----------------------------------------------------------------------===//
2405// Generic Expression Routines
2406//===----------------------------------------------------------------------===//
2407
2408bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2409 // In C++11, discarded-value expressions of a certain form are special,
2410 // according to [expr]p10:
2411 // The lvalue-to-rvalue conversion (4.1) is applied only if the
2412 // expression is a glvalue of volatile-qualified type and it has
2413 // one of the following forms:
2414 if (!isGLValue() || !getType().isVolatileQualified())
2415 return false;
2416
2417 const Expr *E = IgnoreParens();
2418
2419 // - id-expression (5.1.1),
2420 if (isa<DeclRefExpr>(E))
2421 return true;
2422
2423 // - subscripting (5.2.1),
2424 if (isa<ArraySubscriptExpr>(E))
2425 return true;
2426
2427 // - class member access (5.2.5),
2428 if (isa<MemberExpr>(E))
2429 return true;
2430
2431 // - indirection (5.3.1),
2432 if (auto *UO = dyn_cast<UnaryOperator>(E))
2433 if (UO->getOpcode() == UO_Deref)
2434 return true;
2435
2436 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2437 // - pointer-to-member operation (5.5),
2438 if (BO->isPtrMemOp())
2439 return true;
2440
2441 // - comma expression (5.18) where the right operand is one of the above.
2442 if (BO->getOpcode() == BO_Comma)
2443 return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2444 }
2445
2446 // - conditional expression (5.16) where both the second and the third
2447 // operands are one of the above, or
2448 if (auto *CO = dyn_cast<ConditionalOperator>(E))
2449 return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2450 CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2451 // The related edge case of "*x ?: *x".
2452 if (auto *BCO =
2453 dyn_cast<BinaryConditionalOperator>(E)) {
2454 if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2455 return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2456 BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2457 }
2458
2459 // Objective-C++ extensions to the rule.
2460 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
2461 return true;
2462
2463 return false;
2464}
2465
2466/// isUnusedResultAWarning - Return true if this immediate expression should
2467/// be warned about if the result is unused. If so, fill in Loc and Ranges
2468/// with location to warn on and the source range[s] to report with the
2469/// warning.
2470bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2471 SourceRange &R1, SourceRange &R2,
2472 ASTContext &Ctx) const {
2473 // Don't warn if the expr is type dependent. The type could end up
2474 // instantiating to void.
2475 if (isTypeDependent())
2476 return false;
2477
2478 switch (getStmtClass()) {
2479 default:
2480 if (getType()->isVoidType())
2481 return false;
2482 WarnE = this;
2483 Loc = getExprLoc();
2484 R1 = getSourceRange();
2485 return true;
2486 case ParenExprClass:
2487 return cast<ParenExpr>(this)->getSubExpr()->
2488 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2489 case GenericSelectionExprClass:
2490 return cast<GenericSelectionExpr>(this)->getResultExpr()->
2491 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2492 case CoawaitExprClass:
2493 case CoyieldExprClass:
2494 return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2495 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2496 case ChooseExprClass:
2497 return cast<ChooseExpr>(this)->getChosenSubExpr()->
2498 isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2499 case UnaryOperatorClass: {
2500 const UnaryOperator *UO = cast<UnaryOperator>(this);
2501
2502 switch (UO->getOpcode()) {
2503 case UO_Plus:
2504 case UO_Minus:
2505 case UO_AddrOf:
2506 case UO_Not:
2507 case UO_LNot:
2508 case UO_Deref:
2509 break;
2510 case UO_Coawait:
2511 // This is just the 'operator co_await' call inside the guts of a
2512 // dependent co_await call.
2513 case UO_PostInc:
2514 case UO_PostDec:
2515 case UO_PreInc:
2516 case UO_PreDec: // ++/--
2517 return false; // Not a warning.
2518 case UO_Real:
2519 case UO_Imag:
2520 // accessing a piece of a volatile complex is a side-effect.
2521 if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2522 .isVolatileQualified())
2523 return false;
2524 break;
2525 case UO_Extension:
2526 return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2527 }
2528 WarnE = this;
2529 Loc = UO->getOperatorLoc();
2530 R1 = UO->getSubExpr()->getSourceRange();
2531 return true;
2532 }
2533 case BinaryOperatorClass: {
2534 const BinaryOperator *BO = cast<BinaryOperator>(this);
2535 switch (BO->getOpcode()) {
2536 default:
2537 break;
2538 // Consider the RHS of comma for side effects. LHS was checked by
2539 // Sema::CheckCommaOperands.
2540 case BO_Comma:
2541 // ((foo = <blah>), 0) is an idiom for hiding the result (and
2542 // lvalue-ness) of an assignment written in a macro.
2543 if (IntegerLiteral *IE =
2544 dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2545 if (IE->getValue() == 0)
2546 return false;
2547 return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2548 // Consider '||', '&&' to have side effects if the LHS or RHS does.
2549 case BO_LAnd:
2550 case BO_LOr:
2551 if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2552 !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2553 return false;
2554 break;
2555 }
2556 if (BO->isAssignmentOp())
2557 return false;
2558 WarnE = this;
2559 Loc = BO->getOperatorLoc();
2560 R1 = BO->getLHS()->getSourceRange();
2561 R2 = BO->getRHS()->getSourceRange();
2562 return true;
2563 }
2564 case CompoundAssignOperatorClass:
2565 case VAArgExprClass:
2566 case AtomicExprClass:
2567 return false;
2568
2569 case ConditionalOperatorClass: {
2570 // If only one of the LHS or RHS is a warning, the operator might
2571 // be being used for control flow. Only warn if both the LHS and
2572 // RHS are warnings.
2573 const auto *Exp = cast<ConditionalOperator>(this);
2574 return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2575 Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2576 }
2577 case BinaryConditionalOperatorClass: {
2578 const auto *Exp = cast<BinaryConditionalOperator>(this);
2579 return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2580 }
2581
2582 case MemberExprClass:
2583 WarnE = this;
2584 Loc = cast<MemberExpr>(this)->getMemberLoc();
2585 R1 = SourceRange(Loc, Loc);
2586 R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2587 return true;
2588
2589 case ArraySubscriptExprClass:
2590 WarnE = this;
2591 Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2592 R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2593 R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2594 return true;
2595
2596 case CXXOperatorCallExprClass: {
2597 // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2598 // overloads as there is no reasonable way to define these such that they
2599 // have non-trivial, desirable side-effects. See the -Wunused-comparison
2600 // warning: operators == and != are commonly typo'ed, and so warning on them
2601 // provides additional value as well. If this list is updated,
2602 // DiagnoseUnusedComparison should be as well.
2603 const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2604 switch (Op->getOperator()) {
2605 default:
2606 break;
2607 case OO_EqualEqual:
2608 case OO_ExclaimEqual:
2609 case OO_Less:
2610 case OO_Greater:
2611 case OO_GreaterEqual:
2612 case OO_LessEqual:
2613 if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2614 Op->getCallReturnType(Ctx)->isVoidType())
2615 break;
2616 WarnE = this;
2617 Loc = Op->getOperatorLoc();
2618 R1 = Op->getSourceRange();
2619 return true;
2620 }
2621
2622 // Fallthrough for generic call handling.
2623 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2624 }
2625 case CallExprClass:
2626 case CXXMemberCallExprClass:
2627 case UserDefinedLiteralClass: {
2628 // If this is a direct call, get the callee.
2629 const CallExpr *CE = cast<CallExpr>(this);
2630 if (const Decl *FD = CE->getCalleeDecl()) {
2631 // If the callee has attribute pure, const, or warn_unused_result, warn
2632 // about it. void foo() { strlen("bar"); } should warn.
2633 //
2634 // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2635 // updated to match for QoI.
2636 if (CE->hasUnusedResultAttr(Ctx) ||
2637 FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2638 WarnE = this;
2639 Loc = CE->getCallee()->getBeginLoc();
2640 R1 = CE->getCallee()->getSourceRange();
2641
2642 if (unsigned NumArgs = CE->getNumArgs())
2643 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2644 CE->getArg(NumArgs - 1)->getEndLoc());
2645 return true;
2646 }
2647 }
2648 return false;
2649 }
2650
2651 // If we don't know precisely what we're looking at, let's not warn.
2652 case UnresolvedLookupExprClass:
2653 case CXXUnresolvedConstructExprClass:
2654 case RecoveryExprClass:
2655 return false;
2656
2657 case CXXTemporaryObjectExprClass:
2658 case CXXConstructExprClass: {
2659 if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2660 const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2661 if (Type->hasAttr<WarnUnusedAttr>() ||
2662 (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2663 WarnE = this;
2664 Loc = getBeginLoc();
2665 R1 = getSourceRange();
2666 return true;
2667 }
2668 }
2669
2670 const auto *CE = cast<CXXConstructExpr>(this);
2671 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2672 const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2673 if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2674 WarnE = this;
2675 Loc = getBeginLoc();
2676 R1 = getSourceRange();
2677
2678 if (unsigned NumArgs = CE->getNumArgs())
2679 R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2680 CE->getArg(NumArgs - 1)->getEndLoc());
2681 return true;
2682 }
2683 }
2684
2685 return false;
2686 }
2687
2688 case ObjCMessageExprClass: {
2689 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2690 if (Ctx.getLangOpts().ObjCAutoRefCount &&
2691 ME->isInstanceMessage() &&
2692 !ME->getType()->isVoidType() &&
2693 ME->getMethodFamily() == OMF_init) {
2694 WarnE = this;
2695 Loc = getExprLoc();
2696 R1 = ME->getSourceRange();
2697 return true;
2698 }
2699
2700 if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2701 if (MD->hasAttr<WarnUnusedResultAttr>()) {
2702 WarnE = this;
2703 Loc = getExprLoc();
2704 return true;
2705 }
2706
2707 return false;
2708 }
2709
2710 case ObjCPropertyRefExprClass:
2711 WarnE = this;
2712 Loc = getExprLoc();
2713 R1 = getSourceRange();
2714 return true;
2715
2716 case PseudoObjectExprClass: {
2717 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2718
2719 // Only complain about things that have the form of a getter.
2720 if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2721 isa<BinaryOperator>(PO->getSyntacticForm()))
2722 return false;
2723
2724 WarnE = this;
2725 Loc = getExprLoc();
2726 R1 = getSourceRange();
2727 return true;
2728 }
2729
2730 case StmtExprClass: {
2731 // Statement exprs don't logically have side effects themselves, but are
2732 // sometimes used in macros in ways that give them a type that is unused.
2733 // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2734 // however, if the result of the stmt expr is dead, we don't want to emit a
2735 // warning.
2736 const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2737 if (!CS->body_empty()) {
2738 if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2739 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2740 if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2741 if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2742 return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2743 }
2744
2745 if (getType()->isVoidType())
2746 return false;
2747 WarnE = this;
2748 Loc = cast<StmtExpr>(this)->getLParenLoc();
2749 R1 = getSourceRange();
2750 return true;
2751 }
2752 case CXXFunctionalCastExprClass:
2753 case CStyleCastExprClass: {
2754 // Ignore an explicit cast to void, except in C++98 if the operand is a
2755 // volatile glvalue for which we would trigger an implicit read in any
2756 // other language mode. (Such an implicit read always happens as part of
2757 // the lvalue conversion in C, and happens in C++ for expressions of all
2758 // forms where it seems likely the user intended to trigger a volatile
2759 // load.)
2760 const CastExpr *CE = cast<CastExpr>(this);
2761 const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2762 if (CE->getCastKind() == CK_ToVoid) {
2763 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2764 SubE->isReadIfDiscardedInCPlusPlus11()) {
2765 // Suppress the "unused value" warning for idiomatic usage of
2766 // '(void)var;' used to suppress "unused variable" warnings.
2767 if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2768 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2769 if (!VD->isExternallyVisible())
2770 return false;
2771
2772 // The lvalue-to-rvalue conversion would have no effect for an array.
2773 // It's implausible that the programmer expected this to result in a
2774 // volatile array load, so don't warn.
2775 if (SubE->getType()->isArrayType())
2776 return false;
2777
2778 return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2779 }
2780 return false;
2781 }
2782
2783 // If this is a cast to a constructor conversion, check the operand.
2784 // Otherwise, the result of the cast is unused.
2785 if (CE->getCastKind() == CK_ConstructorConversion)
2786 return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2787 if (CE->getCastKind() == CK_Dependent)
2788 return false;
2789
2790 WarnE = this;
2791 if (const CXXFunctionalCastExpr *CXXCE =
2792 dyn_cast<CXXFunctionalCastExpr>(this)) {
2793 Loc = CXXCE->getBeginLoc();
2794 R1 = CXXCE->getSubExpr()->getSourceRange();
2795 } else {
2796 const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2797 Loc = CStyleCE->getLParenLoc();
2798 R1 = CStyleCE->getSubExpr()->getSourceRange();
2799 }
2800 return true;
2801 }
2802 case ImplicitCastExprClass: {
2803 const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2804
2805 // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2806 if (ICE->getCastKind() == CK_LValueToRValue &&
2807 ICE->getSubExpr()->getType().isVolatileQualified())
2808 return false;
2809
2810 return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2811 }
2812 case CXXDefaultArgExprClass:
2813 return (cast<CXXDefaultArgExpr>(this)
2814 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2815 case CXXDefaultInitExprClass:
2816 return (cast<CXXDefaultInitExpr>(this)
2817 ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2818
2819 case CXXNewExprClass:
2820 // FIXME: In theory, there might be new expressions that don't have side
2821 // effects (e.g. a placement new with an uninitialized POD).
2822 case CXXDeleteExprClass:
2823 return false;
2824 case MaterializeTemporaryExprClass:
2825 return cast<MaterializeTemporaryExpr>(this)
2826 ->getSubExpr()
2827 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2828 case CXXBindTemporaryExprClass:
2829 return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2830 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2831 case ExprWithCleanupsClass:
2832 return cast<ExprWithCleanups>(this)->getSubExpr()
2833 ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2834 }
2835}
2836
2837/// isOBJCGCCandidate - Check if an expression is objc gc'able.
2838/// returns true, if it is; false otherwise.
2839bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2840 const Expr *E = IgnoreParens();
2841 switch (E->getStmtClass()) {
2842 default:
2843 return false;
2844 case ObjCIvarRefExprClass:
2845 return true;
2846 case Expr::UnaryOperatorClass:
2847 return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2848 case ImplicitCastExprClass:
2849 return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2850 case MaterializeTemporaryExprClass:
2851 return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2852 Ctx);
2853 case CStyleCastExprClass:
2854 return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2855 case DeclRefExprClass: {
2856 const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2857
2858 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2859 if (VD->hasGlobalStorage())
2860 return true;
2861 QualType T = VD->getType();
2862 // dereferencing to a pointer is always a gc'able candidate,
2863 // unless it is __weak.
2864 return T->isPointerType() &&
2865 (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2866 }
2867 return false;
2868 }
2869 case MemberExprClass: {
2870 const MemberExpr *M = cast<MemberExpr>(E);
2871 return M->getBase()->isOBJCGCCandidate(Ctx);
2872 }
2873 case ArraySubscriptExprClass:
2874 return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2875 }
2876}
2877
2878bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2879 if (isTypeDependent())
2880 return false;
2881 return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2882}
2883
2884QualType Expr::findBoundMemberType(const Expr *expr) {
2885 assert(expr->hasPlaceholderType(BuiltinType::BoundMember))(static_cast<void> (0));
2886
2887 // Bound member expressions are always one of these possibilities:
2888 // x->m x.m x->*y x.*y
2889 // (possibly parenthesized)
2890
2891 expr = expr->IgnoreParens();
2892 if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2893 assert(isa<CXXMethodDecl>(mem->getMemberDecl()))(static_cast<void> (0));
2894 return mem->getMemberDecl()->getType();
2895 }
2896
2897 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2898 QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2899 ->getPointeeType();
2900 assert(type->isFunctionType())(static_cast<void> (0));
2901 return type;
2902 }
2903
2904 assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr))(static_cast<void> (0));
2905 return QualType();
2906}
2907
2908Expr *Expr::IgnoreImpCasts() {
2909 return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
2910}
2911
2912Expr *Expr::IgnoreCasts() {
2913 return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2914}
2915
2916Expr *Expr::IgnoreImplicit() {
2917 return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
2918}
2919
2920Expr *Expr::IgnoreImplicitAsWritten() {
2921 return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
2922}
2923
2924Expr *Expr::IgnoreParens() {
2925 return IgnoreExprNodes(this, IgnoreParensSingleStep);
2926}
2927
2928Expr *Expr::IgnoreParenImpCasts() {
2929 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2930 IgnoreImplicitCastsExtraSingleStep);
2931}
2932
2933Expr *Expr::IgnoreParenCasts() {
2934 return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
2935}
2936
2937Expr *Expr::IgnoreConversionOperatorSingleStep() {
2938 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2939 if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2940 return MCE->getImplicitObjectArgument();
2941 }
2942 return this;
2943}
2944
2945Expr *Expr::IgnoreParenLValueCasts() {
2946 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2947 IgnoreLValueCastsSingleStep);
2948}
2949
2950Expr *Expr::IgnoreParenBaseCasts() {
2951 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2952 IgnoreBaseCastsSingleStep);
2953}
2954
2955Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
2956 auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
2957 if (auto *CE = dyn_cast<CastExpr>(E)) {
2958 // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2959 // ptr<->int casts of the same width. We also ignore all identity casts.
2960 Expr *SubExpr = CE->getSubExpr();
2961 bool IsIdentityCast =
2962 Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2963 bool IsSameWidthCast = (E->getType()->isPointerType() ||
2964 E->getType()->isIntegralType(Ctx)) &&
2965 (SubExpr->getType()->isPointerType() ||
2966 SubExpr->getType()->isIntegralType(Ctx)) &&
2967 (Ctx.getTypeSize(E->getType()) ==
2968 Ctx.getTypeSize(SubExpr->getType()));
2969
2970 if (IsIdentityCast || IsSameWidthCast)
2971 return SubExpr;
2972 } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2973 return NTTP->getReplacement();
2974
2975 return E;
2976 };
2977 return IgnoreExprNodes(this, IgnoreParensSingleStep,
2978 IgnoreNoopCastsSingleStep);
2979}
2980
2981Expr *Expr::IgnoreUnlessSpelledInSource() {
2982 auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
2983 if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
2984 auto *SE = Cast->getSubExpr();
2985 if (SE->getSourceRange() == E->getSourceRange())
2986 return SE;
2987 }
2988
2989 if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
2990 auto NumArgs = C->getNumArgs();
2991 if (NumArgs == 1 ||
2992 (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
2993 Expr *A = C->getArg(0);
2994 if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
2995 return A;
2996 }
2997 }
2998 return E;
2999 };
3000 auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3001 if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3002 Expr *ExprNode = C->getImplicitObjectArgument();
3003 if (ExprNode->getSourceRange() == E->getSourceRange()) {
3004 return ExprNode;
3005 }
3006 if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3007 if (PE->getSourceRange() == C->getSourceRange()) {
3008 return cast<Expr>(PE);
3009 }
3010 }
3011 ExprNode = ExprNode->IgnoreParenImpCasts();
3012 if (ExprNode->getSourceRange() == E->getSourceRange())
3013 return ExprNode;
3014 }
3015 return E;
3016 };
3017 return IgnoreExprNodes(
3018 this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,
3019 IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,
3020 IgnoreImplicitMemberCallSingleStep);
3021}
3022
3023bool Expr::isDefaultArgument() const {
3024 const Expr *E = this;
3025 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3026 E = M->getSubExpr();
3027
3028 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3029 E = ICE->getSubExprAsWritten();
3030
3031 return isa<CXXDefaultArgExpr>(E);
3032}
3033
3034/// Skip over any no-op casts and any temporary-binding
3035/// expressions.
3036static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3037 if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3038 E = M->getSubExpr();
3039
3040 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3041 if (ICE->getCastKind() == CK_NoOp)
3042 E = ICE->getSubExpr();
3043 else
3044 break;
3045 }
3046
3047 while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3048 E = BE->getSubExpr();
3049
3050 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3051 if (ICE->getCastKind() == CK_NoOp)
3052 E = ICE->getSubExpr();
3053 else
3054 break;
3055 }
3056
3057 return E->IgnoreParens();
3058}
3059
3060/// isTemporaryObject - Determines if this expression produces a
3061/// temporary of the given class type.
3062bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3063 if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3064 return false;
3065
3066 const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3067
3068 // Temporaries are by definition pr-values of class type.
3069 if (!E->Classify(C).isPRValue()) {
3070 // In this context, property reference is a message call and is pr-value.
3071 if (!isa<ObjCPropertyRefExpr>(E))
3072 return false;
3073 }
3074
3075 // Black-list a few cases which yield pr-values of class type that don't
3076 // refer to temporaries of that type:
3077
3078 // - implicit derived-to-base conversions
3079 if (isa<ImplicitCastExpr>(E)) {
3080 switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3081 case CK_DerivedToBase:
3082 case CK_UncheckedDerivedToBase:
3083 return false;
3084 default:
3085 break;
3086 }
3087 }
3088
3089 // - member expressions (all)
3090 if (isa<MemberExpr>(E))
3091 return false;
3092
3093 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3094 if (BO->isPtrMemOp())
3095 return false;
3096
3097 // - opaque values (all)
3098 if (isa<OpaqueValueExpr>(E))
3099 return false;
3100
3101 return true;
3102}
3103
3104bool Expr::isImplicitCXXThis() const {
3105 const Expr *E = this;
3106
3107 // Strip away parentheses and casts we don't care about.
3108 while (true) {
3109 if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3110 E = Paren->getSubExpr();
3111 continue;
3112 }
3113
3114 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3115 if (ICE->getCastKind() == CK_NoOp ||
3116 ICE->getCastKind() == CK_LValueToRValue ||
3117 ICE->getCastKind() == CK_DerivedToBase ||
3118 ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3119 E = ICE->getSubExpr();
3120 continue;
3121 }
3122 }
3123
3124 if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3125 if (UnOp->getOpcode() == UO_Extension) {
3126 E = UnOp->getSubExpr();
3127 continue;
3128 }
3129 }
3130
3131 if (const MaterializeTemporaryExpr *M
3132 = dyn_cast<MaterializeTemporaryExpr>(E)) {
3133 E = M->getSubExpr();
3134 continue;
3135 }
3136
3137 break;
3138 }
3139
3140 if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3141 return This->isImplicit();
3142
3143 return false;
3144}
3145
3146/// hasAnyTypeDependentArguments - Determines if any of the expressions
3147/// in Exprs is type-dependent.
3148bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3149 for (unsigned I = 0; I < Exprs.size(); ++I)
3150 if (Exprs[I]->isTypeDependent())
3151 return true;
3152
3153 return false;
3154}
3155
3156bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3157 const Expr **Culprit) const {
3158 assert(!isValueDependent() &&(static_cast<void> (0))
3159 "Expression evaluator can't be called on a dependent expression.")(static_cast<void> (0));
3160
3161 // This function is attempting whether an expression is an initializer
3162 // which can be evaluated at compile-time. It very closely parallels
3163 // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3164 // will lead to unexpected results. Like ConstExprEmitter, it falls back
3165 // to isEvaluatable most of the time.
3166 //
3167 // If we ever capture reference-binding directly in the AST, we can
3168 // kill the second parameter.
3169
3170 if (IsForRef) {
3171 EvalResult Result;
3172 if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3173 return true;
3174 if (Culprit)
3175 *Culprit = this;
3176 return false;
3177 }
3178
3179 switch (getStmtClass()) {
3180 default: break;
3181 case Stmt::ExprWithCleanupsClass:
3182 return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3183 Ctx, IsForRef, Culprit);
3184 case StringLiteralClass:
3185 case ObjCEncodeExprClass:
3186 return true;
3187 case CXXTemporaryObjectExprClass:
3188 case CXXConstructExprClass: {
3189 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3190
3191 if (CE->getConstructor()->isTrivial() &&
3192 CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3193 // Trivial default constructor
3194 if (!CE->getNumArgs()) return true;
3195
3196 // Trivial copy constructor
3197 assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument")(static_cast<void> (0));
3198 return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3199 }
3200
3201 break;
3202 }
3203 case ConstantExprClass: {
3204 // FIXME: We should be able to return "true" here, but it can lead to extra
3205 // error messages. E.g. in Sema/array-init.c.
3206 const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3207 return Exp->isConstantInitializer(Ctx, false, Culprit);
3208 }
3209 case CompoundLiteralExprClass: {
3210 // This handles gcc's extension that allows global initializers like
3211 // "struct x {int x;} x = (struct x) {};".
3212 // FIXME: This accepts other cases it shouldn't!
3213 const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3214 return Exp->isConstantInitializer(Ctx, false, Culprit);
3215 }
3216 case DesignatedInitUpdateExprClass: {
3217 const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3218 return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3219 DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3220 }
3221 case InitListExprClass: {
3222 const InitListExpr *ILE = cast<InitListExpr>(this);
3223 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form")(static_cast<void> (0));
3224 if (ILE->getType()->isArrayType()) {
3225 unsigned numInits = ILE->getNumInits();
3226 for (unsigned i = 0; i < numInits; i++) {
3227 if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3228 return false;
3229 }
3230 return true;
3231 }
3232
3233 if (ILE->getType()->isRecordType()) {
3234 unsigned ElementNo = 0;
3235 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3236 for (const auto *Field : RD->fields()) {
3237 // If this is a union, skip all the fields that aren't being initialized.
3238 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3239 continue;
3240
3241 // Don't emit anonymous bitfields, they just affect layout.
3242 if (Field->isUnnamedBitfield())
3243 continue;
3244
3245 if (ElementNo < ILE->getNumInits()) {
3246 const Expr *Elt = ILE->getInit(ElementNo++);
3247 if (Field->isBitField()) {
3248 // Bitfields have to evaluate to an integer.
3249 EvalResult Result;
3250 if (!Elt->EvaluateAsInt(Result, Ctx)) {
3251 if (Culprit)
3252 *Culprit = Elt;
3253 return false;
3254 }
3255 } else {
3256 bool RefType = Field->getType()->isReferenceType();
3257 if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3258 return false;
3259 }
3260 }
3261 }
3262 return true;
3263 }
3264
3265 break;
3266 }
3267 case ImplicitValueInitExprClass:
3268 case NoInitExprClass:
3269 return true;
3270 case ParenExprClass:
3271 return cast<ParenExpr>(this)->getSubExpr()
3272 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3273 case GenericSelectionExprClass:
3274 return cast<GenericSelectionExpr>(this)->getResultExpr()
3275 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3276 case ChooseExprClass:
3277 if (cast<ChooseExpr>(this)->isConditionDependent()) {
3278 if (Culprit)
3279 *Culprit = this;
3280 return false;
3281 }
3282 return cast<ChooseExpr>(this)->getChosenSubExpr()
3283 ->isConstantInitializer(Ctx, IsForRef, Culprit);
3284 case UnaryOperatorClass: {
3285 const UnaryOperator* Exp = cast<UnaryOperator>(this);
3286 if (Exp->getOpcode() == UO_Extension)
3287 return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3288 break;
3289 }
3290 case CXXFunctionalCastExprClass:
3291 case CXXStaticCastExprClass:
3292 case ImplicitCastExprClass:
3293 case CStyleCastExprClass:
3294 case ObjCBridgedCastExprClass:
3295 case CXXDynamicCastExprClass:
3296 case CXXReinterpretCastExprClass:
3297 case CXXAddrspaceCastExprClass:
3298 case CXXConstCastExprClass: {
3299 const CastExpr *CE = cast<CastExpr>(this);
3300
3301 // Handle misc casts we want to ignore.
3302 if (CE->getCastKind() == CK_NoOp ||
3303 CE->getCastKind() == CK_LValueToRValue ||
3304 CE->getCastKind() == CK_ToUnion ||
3305 CE->getCastKind() == CK_ConstructorConversion ||
3306 CE->getCastKind() == CK_NonAtomicToAtomic ||
3307 CE->getCastKind() == CK_AtomicToNonAtomic ||
3308 CE->getCastKind() == CK_IntToOCLSampler)
3309 return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3310
3311 break;
3312 }
3313 case MaterializeTemporaryExprClass:
3314 return cast<MaterializeTemporaryExpr>(this)
3315 ->getSubExpr()
3316 ->isConstantInitializer(Ctx, false, Culprit);
3317
3318 case SubstNonTypeTemplateParmExprClass:
3319 return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3320 ->isConstantInitializer(Ctx, false, Culprit);
3321 case CXXDefaultArgExprClass:
3322 return cast<CXXDefaultArgExpr>(this)->getExpr()
3323 ->isConstantInitializer(Ctx, false, Culprit);
3324 case CXXDefaultInitExprClass:
3325 return cast<CXXDefaultInitExpr>(this)->getExpr()
3326 ->isConstantInitializer(Ctx, false, Culprit);
3327 }
3328 // Allow certain forms of UB in constant initializers: signed integer
3329 // overflow and floating-point division by zero. We'll give a warning on
3330 // these, but they're common enough that we have to accept them.
3331 if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3332 return true;
3333 if (Culprit)
3334 *Culprit = this;
3335 return false;
3336}
3337
3338bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3339 const FunctionDecl* FD = getDirectCallee();
3340 if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3341 FD->getBuiltinID() != Builtin::BI__builtin_assume))
3342 return false;
3343
3344 const Expr* Arg = getArg(0);
3345 bool ArgVal;
3346 return !Arg->isValueDependent() &&
3347 Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3348}
3349
3350namespace {
3351 /// Look for any side effects within a Stmt.
3352 class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3353 typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3354 const bool IncludePossibleEffects;
3355 bool HasSideEffects;
3356
3357 public:
3358 explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3359 : Inherited(Context),
3360 IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3361
3362 bool hasSideEffects() const { return HasSideEffects; }
3363
3364 void VisitDecl(const Decl *D) {
3365 if (!D)
3366 return;
3367
3368 // We assume the caller checks subexpressions (eg, the initializer, VLA
3369 // bounds) for side-effects on our behalf.
3370 if (auto *VD = dyn_cast<VarDecl>(D)) {
3371 // Registering a destructor is a side-effect.
3372 if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3373 VD->needsDestruction(Context))
3374 HasSideEffects = true;
3375 }
3376 }
3377
3378 void VisitDeclStmt(const DeclStmt *DS) {
3379 for (auto *D : DS->decls())
3380 VisitDecl(D);
3381 Inherited::VisitDeclStmt(DS);
3382 }
3383
3384 void VisitExpr(const Expr *E) {
3385 if (!HasSideEffects &&
3386 E->HasSideEffects(Context, IncludePossibleEffects))
3387 HasSideEffects = true;
3388 }
3389 };
3390}
3391
3392bool Expr::HasSideEffects(const ASTContext &Ctx,
3393 bool IncludePossibleEffects) const {
3394 // In circumstances where we care about definite side effects instead of
3395 // potential side effects, we want to ignore expressions that are part of a
3396 // macro expansion as a potential side effect.
3397 if (!IncludePossibleEffects && getExprLoc().isMacroID())
3398 return false;
3399
3400 switch (getStmtClass()) {
3401 case NoStmtClass:
3402 #define ABSTRACT_STMT(Type)
3403 #define STMT(Type, Base) case Type##Class:
3404 #define EXPR(Type, Base)
3405 #include "clang/AST/StmtNodes.inc"
3406 llvm_unreachable("unexpected Expr kind")__builtin_unreachable();
3407
3408 case DependentScopeDeclRefExprClass:
3409 case CXXUnresolvedConstructExprClass:
3410 case CXXDependentScopeMemberExprClass:
3411 case UnresolvedLookupExprClass:
3412 case UnresolvedMemberExprClass:
3413 case PackExpansionExprClass:
3414 case SubstNonTypeTemplateParmPackExprClass:
3415 case FunctionParmPackExprClass:
3416 case TypoExprClass:
3417 case RecoveryExprClass:
3418 case CXXFoldExprClass:
3419 // Make a conservative assumption for dependent nodes.
3420 return IncludePossibleEffects;
3421
3422 case DeclRefExprClass:
3423 case ObjCIvarRefExprClass:
3424 case PredefinedExprClass:
3425 case IntegerLiteralClass:
3426 case FixedPointLiteralClass:
3427 case FloatingLiteralClass:
3428 case ImaginaryLiteralClass:
3429 case StringLiteralClass:
3430 case CharacterLiteralClass:
3431 case OffsetOfExprClass:
3432 case ImplicitValueInitExprClass:
3433 case UnaryExprOrTypeTraitExprClass:
3434 case AddrLabelExprClass:
3435 case GNUNullExprClass:
3436 case ArrayInitIndexExprClass:
3437 case NoInitExprClass:
3438 case CXXBoolLiteralExprClass:
3439 case CXXNullPtrLiteralExprClass:
3440 case CXXThisExprClass:
3441 case CXXScalarValueInitExprClass:
3442 case TypeTraitExprClass:
3443 case ArrayTypeTraitExprClass:
3444 case ExpressionTraitExprClass:
3445 case CXXNoexceptExprClass:
3446 case SizeOfPackExprClass:
3447 case ObjCStringLiteralClass:
3448 case ObjCEncodeExprClass:
3449 case ObjCBoolLiteralExprClass:
3450 case ObjCAvailabilityCheckExprClass:
3451 case CXXUuidofExprClass:
3452 case OpaqueValueExprClass:
3453 case SourceLocExprClass:
3454 case ConceptSpecializationExprClass:
3455 case RequiresExprClass:
3456 case SYCLUniqueStableNameExprClass:
3457 // These never have a side-effect.
3458 return false;
3459
3460 case ConstantExprClass:
3461 // FIXME: Move this into the "return false;" block above.
3462 return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3463 Ctx, IncludePossibleEffects);
3464
3465 case CallExprClass:
3466 case CXXOperatorCallExprClass:
3467 case CXXMemberCallExprClass:
3468 case CUDAKernelCallExprClass:
3469 case UserDefinedLiteralClass: {
3470 // We don't know a call definitely has side effects, except for calls
3471 // to pure/const functions that definitely don't.
3472 // If the call itself is considered side-effect free, check the operands.
3473 const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3474 bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3475 if (IsPure || !IncludePossibleEffects)
3476 break;
3477 return true;
3478 }
3479
3480 case BlockExprClass:
3481 case CXXBindTemporaryExprClass:
3482 if (!IncludePossibleEffects)
3483 break;
3484 return true;
3485
3486 case MSPropertyRefExprClass:
3487 case MSPropertySubscriptExprClass:
3488 case CompoundAssignOperatorClass:
3489 case VAArgExprClass:
3490 case AtomicExprClass:
3491 case CXXThrowExprClass:
3492 case CXXNewExprClass:
3493 case CXXDeleteExprClass:
3494 case CoawaitExprClass:
3495 case DependentCoawaitExprClass:
3496 case CoyieldExprClass:
3497 // These always have a side-effect.
3498 return true;
3499
3500 case StmtExprClass: {
3501 // StmtExprs have a side-effect if any substatement does.
3502 SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3503 Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3504 return Finder.hasSideEffects();
3505 }
3506
3507 case ExprWithCleanupsClass:
3508 if (IncludePossibleEffects)
3509 if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3510 return true;
3511 break;
3512
3513 case ParenExprClass:
3514 case ArraySubscriptExprClass:
3515 case MatrixSubscriptExprClass:
3516 case OMPArraySectionExprClass:
3517 case OMPArrayShapingExprClass:
3518 case OMPIteratorExprClass:
3519 case MemberExprClass:
3520 case ConditionalOperatorClass:
3521 case BinaryConditionalOperatorClass:
3522 case CompoundLiteralExprClass:
3523 case ExtVectorElementExprClass:
3524 case DesignatedInitExprClass:
3525 case DesignatedInitUpdateExprClass:
3526 case ArrayInitLoopExprClass:
3527 case ParenListExprClass:
3528 case CXXPseudoDestructorExprClass:
3529 case CXXRewrittenBinaryOperatorClass:
3530 case CXXStdInitializerListExprClass:
3531 case SubstNonTypeTemplateParmExprClass:
3532 case MaterializeTemporaryExprClass:
3533 case ShuffleVectorExprClass:
3534 case ConvertVectorExprClass:
3535 case AsTypeExprClass:
3536 // These have a side-effect if any subexpression does.
3537 break;
3538
3539 case UnaryOperatorClass:
3540 if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3541 return true;
3542 break;
3543
3544 case BinaryOperatorClass:
3545 if (cast<BinaryOperator>(this)->isAssignmentOp())
3546 return true;
3547 break;
3548
3549 case InitListExprClass:
3550 // FIXME: The children for an InitListExpr doesn't include the array filler.
3551 if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3552 if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3553 return true;
3554 break;
3555
3556 case GenericSelectionExprClass:
3557 return cast<GenericSelectionExpr>(this)->getResultExpr()->
3558 HasSideEffects(Ctx, IncludePossibleEffects);
3559
3560 case ChooseExprClass:
3561 return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3562 Ctx, IncludePossibleEffects);
3563
3564 case CXXDefaultArgExprClass:
3565 return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3566 Ctx, IncludePossibleEffects);
3567
3568 case CXXDefaultInitExprClass: {
3569 const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3570 if (const Expr *E = FD->getInClassInitializer())
3571 return E->HasSideEffects(Ctx, IncludePossibleEffects);
3572 // If we've not yet parsed the initializer, assume it has side-effects.
3573 return true;
3574 }
3575
3576 case CXXDynamicCastExprClass: {
3577 // A dynamic_cast expression has side-effects if it can throw.
3578 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3579 if (DCE->getTypeAsWritten()->isReferenceType() &&
3580 DCE->getCastKind() == CK_Dynamic)
3581 return true;
3582 }
3583 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3584 case ImplicitCastExprClass:
3585 case CStyleCastExprClass:
3586 case CXXStaticCastExprClass:
3587 case CXXReinterpretCastExprClass:
3588 case CXXConstCastExprClass:
3589 case CXXAddrspaceCastExprClass:
3590 case CXXFunctionalCastExprClass:
3591 case BuiltinBitCastExprClass: {
3592 // While volatile reads are side-effecting in both C and C++, we treat them
3593 // as having possible (not definite) side-effects. This allows idiomatic
3594 // code to behave without warning, such as sizeof(*v) for a volatile-
3595 // qualified pointer.
3596 if (!IncludePossibleEffects)
3597 break;
3598
3599 const CastExpr *CE = cast<CastExpr>(this);
3600 if (CE->getCastKind() == CK_LValueToRValue &&
3601 CE->getSubExpr()->getType().isVolatileQualified())
3602 return true;
3603 break;
3604 }
3605
3606 case CXXTypeidExprClass:
3607 // typeid might throw if its subexpression is potentially-evaluated, so has
3608 // side-effects in that case whether or not its subexpression does.
3609 return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3610
3611 case CXXConstructExprClass:
3612 case CXXTemporaryObjectExprClass: {
3613 const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3614 if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3615 return true;
3616 // A trivial constructor does not add any side-effects of its own. Just look
3617 // at its arguments.
3618 break;
3619 }
3620
3621 case CXXInheritedCtorInitExprClass: {
3622 const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3623 if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3624 return true;
3625 break;
3626 }
3627
3628 case LambdaExprClass: {
3629 const LambdaExpr *LE = cast<LambdaExpr>(this);
3630 for (Expr *E : LE->capture_inits())
3631 if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3632 return true;
3633 return false;
3634 }
3635
3636 case PseudoObjectExprClass: {
3637 // Only look for side-effects in the semantic form, and look past
3638 // OpaqueValueExpr bindings in that form.
3639 const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3640 for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3641 E = PO->semantics_end();
3642 I != E; ++I) {
3643 const Expr *Subexpr = *I;
3644 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3645 Subexpr = OVE->getSourceExpr();
3646 if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3647 return true;
3648 }
3649 return false;
3650 }
3651
3652 case ObjCBoxedExprClass:
3653 case ObjCArrayLiteralClass:
3654 case ObjCDictionaryLiteralClass:
3655 case ObjCSelectorExprClass:
3656 case ObjCProtocolExprClass:
3657 case ObjCIsaExprClass:
3658 case ObjCIndirectCopyRestoreExprClass:
3659 case ObjCSubscriptRefExprClass:
3660 case ObjCBridgedCastExprClass:
3661 case ObjCMessageExprClass:
3662 case ObjCPropertyRefExprClass:
3663 // FIXME: Classify these cases better.
3664 if (IncludePossibleEffects)
3665 return true;
3666 break;
3667 }
3668
3669 // Recurse to children.
3670 for (const Stmt *SubStmt : children())
3671 if (SubStmt &&
3672 cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3673 return true;
3674
3675 return false;
3676}
3677
3678FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
3679 if (auto Call = dyn_cast<CallExpr>(this))
3680 return Call->getFPFeaturesInEffect(LO);
3681 if (auto UO = dyn_cast<UnaryOperator>(this))
3682 return UO->getFPFeaturesInEffect(LO);
3683 if (auto BO = dyn_cast<BinaryOperator>(this))
3684 return BO->getFPFeaturesInEffect(LO);
3685 if (auto Cast = dyn_cast<CastExpr>(this))
3686 return Cast->getFPFeaturesInEffect(LO);
3687 return FPOptions::defaultWithoutTrailingStorage(LO);
3688}
3689
3690namespace {
3691 /// Look for a call to a non-trivial function within an expression.
3692 class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3693 {
3694 typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3695
3696 bool NonTrivial;
3697
3698 public:
3699 explicit NonTrivialCallFinder(const ASTContext &Context)
3700 : Inherited(Context), NonTrivial(false) { }
3701
3702 bool hasNonTrivialCall() const { return NonTrivial; }
3703
3704 void VisitCallExpr(const CallExpr *E) {
3705 if (const CXXMethodDecl *Method
3706 = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3707 if (Method->isTrivial()) {
3708 // Recurse to children of the call.
3709 Inherited::VisitStmt(E);
3710 return;
3711 }
3712 }
3713
3714 NonTrivial = true;
3715 }
3716
3717 void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3718 if (E->getConstructor()->isTrivial()) {
3719 // Recurse to children of the call.
3720 Inherited::VisitStmt(E);
3721 return;
3722 }
3723
3724 NonTrivial = true;
3725 }
3726
3727 void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3728 if (E->getTemporary()->getDestructor()->isTrivial()) {
3729 Inherited::VisitStmt(E);
3730 return;
3731 }
3732
3733 NonTrivial = true;
3734 }
3735 };
3736}
3737
3738bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3739 NonTrivialCallFinder Finder(Ctx);
3740 Finder.Visit(this);
3741 return Finder.hasNonTrivialCall();
3742}
3743
3744/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3745/// pointer constant or not, as well as the specific kind of constant detected.
3746/// Null pointer constants can be integer constant expressions with the
3747/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3748/// (a GNU extension).
3749Expr::NullPointerConstantKind
3750Expr::isNullPointerConstant(ASTContext &Ctx,
3751 NullPointerConstantValueDependence NPC) const {
3752 if (isValueDependent() &&
3753 (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3754 // Error-dependent expr should never be a null pointer.
3755 if (containsErrors())
3756 return NPCK_NotNull;
3757 switch (NPC) {
3758 case NPC_NeverValueDependent:
3759 llvm_unreachable("Unexpected value dependent expression!")__builtin_unreachable();
3760 case NPC_ValueDependentIsNull:
3761 if (isTypeDependent() || getType()->isIntegralType(Ctx))
3762 return NPCK_ZeroExpression;
3763 else
3764 return NPCK_NotNull;
3765
3766 case NPC_ValueDependentIsNotNull:
3767 return NPCK_NotNull;
3768 }
3769 }
3770
3771 // Strip off a cast to void*, if it exists. Except in C++.
3772 if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3773 if (!Ctx.getLangOpts().CPlusPlus) {
3774 // Check that it is a cast to void*.
3775 if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3776 QualType Pointee = PT->getPointeeType();
3777 Qualifiers Qs = Pointee.getQualifiers();
3778 // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3779 // has non-default address space it is not treated as nullptr.
3780 // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3781 // since it cannot be assigned to a pointer to constant address space.
3782 if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
3783 Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3784 (Ctx.getLangOpts().OpenCL &&
3785 Ctx.getLangOpts().OpenCLVersion < 200 &&
3786 Pointee.getAddressSpace() == LangAS::opencl_private))
3787 Qs.removeAddressSpace();
3788
3789 if (Pointee->isVoidType() && Qs.empty() && // to void*
3790 CE->getSubExpr()->getType()->isIntegerType()) // from int
3791 return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3792 }
3793 }
3794 } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3795 // Ignore the ImplicitCastExpr type entirely.
3796 return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3797 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3798 // Accept ((void*)0) as a null pointer constant, as many other
3799 // implementations do.
3800 return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3801 } else if (const GenericSelectionExpr *GE =
3802 dyn_cast<GenericSelectionExpr>(this)) {
3803 if (GE->isResultDependent())
3804 return NPCK_NotNull;
3805 return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3806 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3807 if (CE->isConditionDependent())
3808 return NPCK_NotNull;
3809 return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3810 } else if (const CXXDefaultArgExpr *DefaultArg
3811 = dyn_cast<CXXDefaultArgExpr>(this)) {
3812 // See through default argument expressions.
3813 return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3814 } else if (const CXXDefaultInitExpr *DefaultInit
3815 = dyn_cast<CXXDefaultInitExpr>(this)) {
3816 // See through default initializer expressions.
3817 return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3818 } else if (isa<GNUNullExpr>(this)) {
3819 // The GNU __null extension is always a null pointer constant.
3820 return NPCK_GNUNull;
3821 } else if (const MaterializeTemporaryExpr *M
3822 = dyn_cast<MaterializeTemporaryExpr>(this)) {
3823 return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3824 } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3825 if (const Expr *Source = OVE->getSourceExpr())
3826 return Source->isNullPointerConstant(Ctx, NPC);
3827 }
3828
3829 // If the expression has no type information, it cannot be a null pointer
3830 // constant.
3831 if (getType().isNull())
3832 return NPCK_NotNull;
3833
3834 // C++11 nullptr_t is always a null pointer constant.
3835 if (getType()->isNullPtrType())
3836 return NPCK_CXX11_nullptr;
3837
3838 if (const RecordType *UT = getType()->getAsUnionType())
3839 if (!Ctx.getLangOpts().CPlusPlus11 &&
3840 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3841 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3842 const Expr *InitExpr = CLE->getInitializer();
3843 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3844 return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3845 }
3846 // This expression must be an integer type.
3847 if (!getType()->isIntegerType() ||
3848 (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3849 return NPCK_NotNull;
3850
3851 if (Ctx.getLangOpts().CPlusPlus11) {
3852 // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3853 // value zero or a prvalue of type std::nullptr_t.
3854 // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3855 const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3856 if (Lit && !Lit->getValue())
3857 return NPCK_ZeroLiteral;
3858 if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3859 return NPCK_NotNull;
3860 } else {
3861 // If we have an integer constant expression, we need to *evaluate* it and
3862 // test for the value 0.
3863 if (!isIntegerConstantExpr(Ctx))
3864 return NPCK_NotNull;
3865 }
3866
3867 if (EvaluateKnownConstInt(Ctx) != 0)
3868 return NPCK_NotNull;
3869
3870 if (isa<IntegerLiteral>(this))
3871 return NPCK_ZeroLiteral;
3872 return NPCK_ZeroExpression;
3873}
3874
3875/// If this expression is an l-value for an Objective C
3876/// property, find the underlying property reference expression.
3877const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3878 const Expr *E = this;
3879 while (true) {
3880 assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&(static_cast<void> (0))
3881 "expression is not a property reference")(static_cast<void> (0));
3882 E = E->IgnoreParenCasts();
3883 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3884 if (BO->getOpcode() == BO_Comma) {
3885 E = BO->getRHS();
3886 continue;
3887 }
3888 }
3889
3890 break;
3891 }
3892
3893 return cast<ObjCPropertyRefExpr>(E);
3894}
3895
3896bool Expr::isObjCSelfExpr() const {
3897 const Expr *E = IgnoreParenImpCasts();
3898
3899 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3900 if (!DRE)
3901 return false;
3902
3903 const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3904 if (!Param)
3905 return false;
3906
3907 const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3908 if (!M)
3909 return false;
3910
3911 return M->getSelfDecl() == Param;
3912}
3913
3914FieldDecl *Expr::getSourceBitField() {
3915 Expr *E = this->IgnoreParens();
3916
3917 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3918 if (ICE->getCastKind() == CK_LValueToRValue ||
3919 (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
3920 E = ICE->getSubExpr()->IgnoreParens();
3921 else
3922 break;
3923 }
3924
3925 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3926 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3927 if (Field->isBitField())
3928 return Field;
3929
3930 if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3931 FieldDecl *Ivar = IvarRef->getDecl();
3932 if (Ivar->isBitField())
3933 return Ivar;
3934 }
3935
3936 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3937 if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3938 if (Field->isBitField())
3939 return Field;
3940
3941 if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3942 if (Expr *E = BD->getBinding())
3943 return E->getSourceBitField();
3944 }
3945
3946 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3947 if (BinOp->isAssignmentOp() && BinOp->getLHS())
3948 return BinOp->getLHS()->getSourceBitField();
3949
3950 if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3951 return BinOp->getRHS()->getSourceBitField();
3952 }
3953
3954 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3955 if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3956 return UnOp->getSubExpr()->getSourceBitField();
3957
3958 return nullptr;
3959}
3960
3961bool Expr::refersToVectorElement() const {
3962 // FIXME: Why do we not just look at the ObjectKind here?
3963 const Expr *E = this->IgnoreParens();
3964
3965 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3966 if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
3967 E = ICE->getSubExpr()->IgnoreParens();
3968 else
3969 break;
3970 }
3971
3972 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3973 return ASE->getBase()->getType()->isVectorType();
3974
3975 if (isa<ExtVectorElementExpr>(E))
3976 return true;
3977
3978 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3979 if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3980 if (auto *E = BD->getBinding())
3981 return E->refersToVectorElement();
3982
3983 return false;
3984}
3985
3986bool Expr::refersToGlobalRegisterVar() const {
3987 const Expr *E = this->IgnoreParenImpCasts();
3988
3989 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3990 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3991 if (VD->getStorageClass() == SC_Register &&
3992 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3993 return true;
3994
3995 return false;
3996}
3997
3998bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
3999 E1 = E1->IgnoreParens();
4000 E2 = E2->IgnoreParens();
4001
4002 if (E1->getStmtClass() != E2->getStmtClass())
4003 return false;
4004
4005 switch (E1->getStmtClass()) {
4006 default:
4007 return false;
4008 case CXXThisExprClass:
4009 return true;
4010 case DeclRefExprClass: {
4011 // DeclRefExpr without an ImplicitCastExpr can happen for integral
4012 // template parameters.
4013 const auto *DRE1 = cast<DeclRefExpr>(E1);
4014 const auto *DRE2 = cast<DeclRefExpr>(E2);
4015 return DRE1->isPRValue() && DRE2->isPRValue() &&
4016 DRE1->getDecl() == DRE2->getDecl();
4017 }
4018 case ImplicitCastExprClass: {
4019 // Peel off implicit casts.
4020 while (true) {
4021 const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4022 const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4023 if (!ICE1 || !ICE2)
4024 return false;
4025 if (ICE1->getCastKind() != ICE2->getCastKind())
4026 return false;
4027 E1 = ICE1->getSubExpr()->IgnoreParens();
4028 E2 = ICE2->getSubExpr()->IgnoreParens();
4029 // The final cast must be one of these types.
4030 if (ICE1->getCastKind() == CK_LValueToRValue ||
4031 ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4032 ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4033 break;
4034 }
4035 }
4036
4037 const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4038 const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4039 if (DRE1 && DRE2)
4040 return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4041
4042 const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4043 const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4044 if (Ivar1 && Ivar2) {
4045 return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4046 declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4047 }
4048
4049 const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4050 const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4051 if (Array1 && Array2) {
4052 if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4053 return false;
4054
4055 auto Idx1 = Array1->getIdx();
4056 auto Idx2 = Array2->getIdx();
4057 const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4058 const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4059 if (Integer1 && Integer2) {
4060 if (!llvm::APInt::isSameValue(Integer1->getValue(),
4061 Integer2->getValue()))
4062 return false;
4063 } else {
4064 if (!isSameComparisonOperand(Idx1, Idx2))
4065 return false;
4066 }
4067
4068 return true;
4069 }
4070
4071 // Walk the MemberExpr chain.
4072 while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4073 const auto *ME1 = cast<MemberExpr>(E1);
4074 const auto *ME2 = cast<MemberExpr>(E2);
4075 if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4076 return false;
4077 if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4078 if (D->isStaticDataMember())
4079 return true;
4080 E1 = ME1->getBase()->IgnoreParenImpCasts();
4081 E2 = ME2->getBase()->IgnoreParenImpCasts();
4082 }
4083
4084 if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4085 return true;
4086
4087 // A static member variable can end the MemberExpr chain with either
4088 // a MemberExpr or a DeclRefExpr.
4089 auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4090 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4091 return DRE->getDecl();
4092 if (const auto *ME = dyn_cast<MemberExpr>(E))
4093 return ME->getMemberDecl();
4094 return nullptr;
4095 };
4096
4097 const ValueDecl *VD1 = getAnyDecl(E1);
4098 const ValueDecl *VD2 = getAnyDecl(E2);
4099 return declaresSameEntity(VD1, VD2);
4100 }
4101 }
4102}
4103
4104/// isArrow - Return true if the base expression is a pointer to vector,
4105/// return false if the base expression is a vector.
4106bool ExtVectorElementExpr::isArrow() const {
4107 return getBase()->getType()->isPointerType();
4108}
4109
4110unsigned ExtVectorElementExpr::getNumElements() const {
4111 if (const VectorType *VT = getType()->getAs<VectorType>())
4112 return VT->getNumElements();
4113 return 1;
4114}
4115
4116/// containsDuplicateElements - Return true if any element access is repeated.
4117bool ExtVectorElementExpr::containsDuplicateElements() const {
4118 // FIXME: Refactor this code to an accessor on the AST node which returns the
4119 // "type" of component access, and share with code below and in Sema.
4120 StringRef Comp = Accessor->getName();
4121
4122 // Halving swizzles do not contain duplicate elements.
4123 if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4124 return false;
4125
4126 // Advance past s-char prefix on hex swizzles.
4127 if (Comp[0] == 's' || Comp[0] == 'S')
4128 Comp = Comp.substr(1);
4129
4130 for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4131 if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
4132 return true;
4133
4134 return false;
4135}
4136
4137/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4138void ExtVectorElementExpr::getEncodedElementAccess(
4139 SmallVectorImpl<uint32_t> &Elts) const {
4140 StringRef Comp = Accessor->getName();
4141 bool isNumericAccessor = false;
4142 if (Comp[0] == 's' || Comp[0] == 'S') {
4143 Comp = Comp.substr(1);
4144 isNumericAccessor = true;
4145 }
4146
4147 bool isHi = Comp == "hi";
4148 bool isLo = Comp == "lo";
4149 bool isEven = Comp == "even";
4150 bool isOdd = Comp == "odd";
4151
4152 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4153 uint64_t Index;
4154
4155 if (isHi)
4156 Index = e + i;
4157 else if (isLo)
4158 Index = i;
4159 else if (isEven)
4160 Index = 2 * i;
4161 else if (isOdd)
4162 Index = 2 * i + 1;
4163 else
4164 Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4165
4166 Elts.push_back(Index);
4167 }
4168}
4169
4170ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4171 QualType Type, SourceLocation BLoc,
4172 SourceLocation RP)
4173 : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4174 BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4175 SubExprs = new (C) Stmt*[args.size()];
4176 for (unsigned i = 0; i != args.size(); i++)
4177 SubExprs[i] = args[i];
4178
4179 setDependence(computeDependence(this));
4180}
4181
4182void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4183 if (SubExprs) C.Deallocate(SubExprs);
4184
4185 this->NumExprs = Exprs.size();
4186 SubExprs = new (C) Stmt*[NumExprs];
4187 memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4188}
4189
4190GenericSelectionExpr::GenericSelectionExpr(
4191 const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4192 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4193 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4194 bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4195 : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4196 AssocExprs[ResultIndex]->getValueKind(),
4197 AssocExprs[ResultIndex]->getObjectKind()),
4198 NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4199 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4200 assert(AssocTypes.size() == AssocExprs.size() &&(static_cast<void> (0))
4201 "Must have the same number of association expressions"(static_cast<void> (0))
4202 " and TypeSourceInfo!")(static_cast<void> (0));
4203 assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!")(static_cast<void> (0));
4204
4205 GenericSelectionExprBits.GenericLoc = GenericLoc;
4206 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4207 std::copy(AssocExprs.begin(), AssocExprs.end(),
4208 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4209 std::copy(AssocTypes.begin(), AssocTypes.end(),
4210 getTrailingObjects<TypeSourceInfo *>());
4211
4212 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4213}
4214
4215GenericSelectionExpr::GenericSelectionExpr(
4216 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4217 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4218 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4219 bool ContainsUnexpandedParameterPack)
4220 : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4221 OK_Ordinary),
4222 NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4223 DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4224 assert(AssocTypes.size() == AssocExprs.size() &&(static_cast<void> (0))
4225 "Must have the same number of association expressions"(static_cast<void> (0))
4226 " and TypeSourceInfo!")(static_cast<void> (0));
4227
4228 GenericSelectionExprBits.GenericLoc = GenericLoc;
4229 getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
4230 std::copy(AssocExprs.begin(), AssocExprs.end(),
4231 getTrailingObjects<Stmt *>() + AssocExprStartIndex);
4232 std::copy(AssocTypes.begin(), AssocTypes.end(),
4233 getTrailingObjects<TypeSourceInfo *>());
4234
4235 setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4236}
4237
4238GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4239 : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4240
4241GenericSelectionExpr *GenericSelectionExpr::Create(
4242 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4243 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4244 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4245 bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4246 unsigned NumAssocs = AssocExprs.size();
4247 void *Mem = Context.Allocate(
4248 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4249 alignof(GenericSelectionExpr));
4250 return new (Mem) GenericSelectionExpr(
4251 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4252 RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4253}
4254
4255GenericSelectionExpr *GenericSelectionExpr::Create(
4256 const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4257 ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4258 SourceLocation DefaultLoc, SourceLocation RParenLoc,
4259 bool ContainsUnexpandedParameterPack) {
4260 unsigned NumAssocs = AssocExprs.size();
4261 void *Mem = Context.Allocate(
4262 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4263 alignof(GenericSelectionExpr));
4264 return new (Mem) GenericSelectionExpr(
4265 Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4266 RParenLoc, ContainsUnexpandedParameterPack);
4267}
4268
4269GenericSelectionExpr *
4270GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4271 unsigned NumAssocs) {
4272 void *Mem = Context.Allocate(
4273 totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4274 alignof(GenericSelectionExpr));
4275 return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4276}
4277
4278//===----------------------------------------------------------------------===//
4279// DesignatedInitExpr
4280//===----------------------------------------------------------------------===//
4281
4282IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4283 assert(Kind == FieldDesignator && "Only valid on a field designator")(static_cast<void> (0));
4284 if (Field.NameOrField & 0x01)
4285 return reinterpret_cast<IdentifierInfo *>(Field.NameOrField & ~0x01);
4286 return getField()->getIdentifier();
4287}
4288
4289DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4290 llvm::ArrayRef<Designator> Designators,
4291 SourceLocation EqualOrColonLoc,
4292 bool GNUSyntax,
4293 ArrayRef<Expr *> IndexExprs, Expr *Init)
4294 : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4295 Init->getObjectKind()),
4296 EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4297 NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4298 this->Designators = new (C) Designator[NumDesignators];
4299
4300 // Record the initializer itself.
4301 child_iterator Child = child_begin();
4302 *Child++ = Init;
4303
4304 // Copy the designators and their subexpressions, computing
4305 // value-dependence along the way.
4306 unsigned IndexIdx = 0;
4307 for (unsigned I = 0; I != NumDesignators; ++I) {
4308 this->Designators[I] = Designators[I];
4309 if (this->Designators[I].isArrayDesignator()) {
4310 // Copy the index expressions into permanent storage.
4311 *Child++ = IndexExprs[IndexIdx++];
4312 } else if (this->Designators[I].isArrayRangeDesignator()) {
4313 // Copy the start/end expressions into permanent storage.
4314 *Child++ = IndexExprs[IndexIdx++];
4315 *Child++ = IndexExprs[IndexIdx++];
4316 }
4317 }
4318
4319 assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions")(static_cast<void> (0));
4320 setDependence(computeDependence(this));
4321}
4322
4323DesignatedInitExpr *
4324DesignatedInitExpr::Create(const ASTContext &C,
4325 llvm::ArrayRef<Designator> Designators,
4326 ArrayRef<Expr*> IndexExprs,
4327 SourceLocation ColonOrEqualLoc,
4328 bool UsesColonSyntax, Expr *Init) {
4329 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4330 alignof(DesignatedInitExpr));
4331 return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4332 ColonOrEqualLoc, UsesColonSyntax,
4333 IndexExprs, Init);
4334}
4335
4336DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4337 unsigned NumIndexExprs) {
4338 void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4339 alignof(DesignatedInitExpr));
4340 return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4341}
4342
4343void DesignatedInitExpr::setDesignators(const ASTContext &C,
4344 const Designator *Desigs,
4345 unsigned NumDesigs) {
4346 Designators = new (C) Designator[NumDesigs];
4347 NumDesignators = NumDesigs;
4348 for (unsigned I = 0; I != NumDesigs; ++I)
4349 Designators[I] = Desigs[I];
4350}
4351
4352SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4353 DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4354 if (size() == 1)
4355 return DIE->getDesignator(0)->getSourceRange();
4356 return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4357 DIE->getDesignator(size() - 1)->getEndLoc());
4358}
4359
4360SourceLocation DesignatedInitExpr::getBeginLoc() const {
4361 SourceLocation StartLoc;
4362 auto *DIE = const_cast<DesignatedInitExpr *>(this);
4363 Designator &First = *DIE->getDesignator(0);
4364 if (First.isFieldDesignator())
4365 StartLoc = GNUSyntax ? First.Field.FieldLoc : First.Field.DotLoc;
4366 else
4367 StartLoc = First.ArrayOrRange.LBracketLoc;
4368 return StartLoc;
4369}
4370
4371SourceLocation DesignatedInitExpr::getEndLoc() const {
4372 return getInit()->getEndLoc();
4373}
4374
4375Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4376 assert(D.Kind == Designator::ArrayDesignator && "Requires array designator")(static_cast<void> (0));
4377 return getSubExpr(D.ArrayOrRange.Index + 1);
4378}
4379
4380Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4381 assert(D.Kind == Designator::ArrayRangeDesignator &&(static_cast<void> (0))
4382 "Requires array range designator")(static_cast<void> (0));
4383 return getSubExpr(D.ArrayOrRange.Index + 1);
4384}
4385
4386Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4387 assert(D.Kind == Designator::ArrayRangeDesignator &&(static_cast<void> (0))
4388 "Requires array range designator")(static_cast<void> (0));
4389 return getSubExpr(D.ArrayOrRange.Index + 2);
4390}
4391
4392/// Replaces the designator at index @p Idx with the series
4393/// of designators in [First, Last).
4394void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4395 const Designator *First,
4396 const Designator *Last) {
4397 unsigned NumNewDesignators = Last - First;
4398 if (NumNewDesignators == 0) {
4399 std::copy_backward(Designators + Idx + 1,
4400 Designators + NumDesignators,
4401 Designators + Idx);
4402 --NumNewDesignators;
4403 return;
4404 }
4405 if (NumNewDesignators == 1) {
4406 Designators[Idx] = *First;
4407 return;
4408 }
4409
4410 Designator *NewDesignators
4411 = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4412 std::copy(Designators, Designators + Idx, NewDesignators);
4413 std::copy(First, Last, NewDesignators + Idx);
4414 std::copy(Designators + Idx + 1, Designators + NumDesignators,
4415 NewDesignators + Idx + NumNewDesignators);
4416 Designators = NewDesignators;
4417 NumDesignators = NumDesignators - 1 + NumNewDesignators;
4418}
4419
4420DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4421 SourceLocation lBraceLoc,
4422 Expr *baseExpr,
4423 SourceLocation rBraceLoc)
4424 : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4425 OK_Ordinary) {
4426 BaseAndUpdaterExprs[0] = baseExpr;
4427
4428 InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4429 ILE->setType(baseExpr->getType());
4430 BaseAndUpdaterExprs[1] = ILE;
4431
4432 // FIXME: this is wrong, set it correctly.
4433 setDependence(ExprDependence::None);
4434}
4435
4436SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4437 return getBase()->getBeginLoc();
4438}
4439
4440SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4441 return getBase()->getEndLoc();
4442}
4443
4444ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4445 SourceLocation RParenLoc)
4446 : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4447 LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4448 ParenListExprBits.NumExprs = Exprs.size();
4449
4450 for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4451 getTrailingObjects<Stmt *>()[I] = Exprs[I];
4452 setDependence(computeDependence(this));
4453}
4454
4455ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4456 : Expr(ParenListExprClass, Empty) {
4457 ParenListExprBits.NumExprs = NumExprs;
4458}
4459
4460ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4461 SourceLocation LParenLoc,
4462 ArrayRef<Expr *> Exprs,
4463 SourceLocation RParenLoc) {
4464 void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4465 alignof(ParenListExpr));
4466 return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4467}
4468
4469ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4470 unsigned NumExprs) {
4471 void *Mem =
4472 Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4473 return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4474}
4475
4476BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4477 Opcode opc, QualType ResTy, ExprValueKind VK,
4478 ExprObjectKind OK, SourceLocation opLoc,
4479 FPOptionsOverride FPFeatures)
4480 : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4481 BinaryOperatorBits.Opc = opc;
4482 assert(!isCompoundAssignmentOp() &&(static_cast<void> (0))
4483 "Use CompoundAssignOperator for compound assignments")(static_cast<void> (0));
4484 BinaryOperatorBits.OpLoc = opLoc;
4485 SubExprs[LHS] = lhs;
4486 SubExprs[RHS] = rhs;
4487 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4488 if (hasStoredFPFeatures())
4489 setStoredFPFeatures(FPFeatures);
4490 setDependence(computeDependence(this));
4491}
4492
4493BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4494 Opcode opc, QualType ResTy, ExprValueKind VK,
4495 ExprObjectKind OK, SourceLocation opLoc,
4496 FPOptionsOverride FPFeatures, bool dead2)
4497 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4498 BinaryOperatorBits.Opc = opc;
4499 assert(isCompoundAssignmentOp() &&(static_cast<void> (0))
4500 "Use CompoundAssignOperator for compound assignments")(static_cast<void> (0));
4501 BinaryOperatorBits.OpLoc = opLoc;
4502 SubExprs[LHS] = lhs;
4503 SubExprs[RHS] = rhs;
4504 BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4505 if (hasStoredFPFeatures())
4506 setStoredFPFeatures(FPFeatures);
4507 setDependence(computeDependence(this));
4508}
4509
4510BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
4511 bool HasFPFeatures) {
4512 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4513 void *Mem =
4514 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4515 return new (Mem) BinaryOperator(EmptyShell());
4516}
4517
4518BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
4519 Expr *rhs, Opcode opc, QualType ResTy,
4520 ExprValueKind VK, ExprObjectKind OK,
4521 SourceLocation opLoc,
4522 FPOptionsOverride FPFeatures) {
4523 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4524 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4525 void *Mem =
4526 C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4527 return new (Mem)
4528 BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4529}
4530
4531CompoundAssignOperator *
4532CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4533 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4534 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4535 alignof(CompoundAssignOperator));
4536 return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4537}
4538
4539CompoundAssignOperator *
4540CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4541 Opcode opc, QualType ResTy, ExprValueKind VK,
4542 ExprObjectKind OK, SourceLocation opLoc,
4543 FPOptionsOverride FPFeatures,
4544 QualType CompLHSType, QualType CompResultType) {
4545 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4546 unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4547 void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4548 alignof(CompoundAssignOperator));
4549 return new (Mem)
4550 CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4551 CompLHSType, CompResultType);
4552}
4553
4554UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
4555 bool hasFPFeatures) {
4556 void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4557 alignof(UnaryOperator));
4558 return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4559}
4560
4561UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
4562 QualType type, ExprValueKind VK, ExprObjectKind OK,
4563 SourceLocation l, bool CanOverflow,
4564 FPOptionsOverride FPFeatures)
4565 : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4566 UnaryOperatorBits.Opc = opc;
4567 UnaryOperatorBits.CanOverflow = CanOverflow;
4568 UnaryOperatorBits.Loc = l;
4569 UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4570 if (hasStoredFPFeatures())
4571 setStoredFPFeatures(FPFeatures);
4572 setDependence(computeDependence(this, Ctx));
4573}
4574
4575UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
4576 Opcode opc, QualType type,
4577 ExprValueKind VK, ExprObjectKind OK,
4578 SourceLocation l, bool CanOverflow,
4579 FPOptionsOverride FPFeatures) {
4580 bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4581 unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4582 void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4583 return new (Mem)
4584 UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4585}
4586
4587const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4588 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4589 e = ewc->getSubExpr();
4590 if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4591 e = m->getSubExpr();
4592 e = cast<CXXConstructExpr>(e)->getArg(0);
4593 while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4594 e = ice->getSubExpr();
4595 return cast<OpaqueValueExpr>(e);
4596}
4597
4598PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4599 EmptyShell sh,
4600 unsigned numSemanticExprs) {
4601 void *buffer =
4602 Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4603 alignof(PseudoObjectExpr));
4604 return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4605}
4606
4607PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4608 : Expr(PseudoObjectExprClass, shell) {
4609 PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4610}
4611
4612PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4613 ArrayRef<Expr*> semantics,
4614 unsigned resultIndex) {
4615 assert(syntax && "no syntactic expression!")(static_cast<void> (0));
4616 assert(semantics.size() && "no semantic expressions!")(static_cast<void> (0));
4617
4618 QualType type;
4619 ExprValueKind VK;
4620 if (resultIndex == NoResult) {
4621 type = C.VoidTy;
4622 VK = VK_PRValue;
4623 } else {
4624 assert(resultIndex < semantics.size())(static_cast<void> (0));
4625 type = semantics[resultIndex]->getType();
4626 VK = semantics[resultIndex]->getValueKind();
4627 assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary)(static_cast<void> (0));
4628 }
4629
4630 void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4631 alignof(PseudoObjectExpr));
4632 return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4633 resultIndex);
4634}
4635
4636PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4637 Expr *syntax, ArrayRef<Expr *> semantics,
4638 unsigned resultIndex)
4639 : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4640 PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4641 PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4642
4643 for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4644 Expr *E = (i == 0 ? syntax : semantics[i-1]);
4645 getSubExprsBuffer()[i] = E;
4646
4647 if (isa<OpaqueValueExpr>(E))
4648 assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&(static_cast<void> (0))
4649 "opaque-value semantic expressions for pseudo-object "(static_cast<void> (0))
4650 "operations must have sources")(static_cast<void> (0));
4651 }
4652
4653 setDependence(computeDependence(this));
4654}
4655
4656//===----------------------------------------------------------------------===//
4657// Child Iterators for iterating over subexpressions/substatements
4658//===----------------------------------------------------------------------===//
4659
4660// UnaryExprOrTypeTraitExpr
4661Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4662 const_child_range CCR =
4663 const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4664 return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4665}
4666
4667Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4668 // If this is of a type and the type is a VLA type (and not a typedef), the
4669 // size expression of the VLA needs to be treated as an executable expression.
4670 // Why isn't this weirdness documented better in StmtIterator?
4671 if (isArgumentType()) {
4672 if (const VariableArrayType *T =
4673 dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4674 return const_child_range(const_child_iterator(T), const_child_iterator());
4675 return const_child_range(const_child_iterator(), const_child_iterator());
4676 }
4677 return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4678}
4679
4680AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
4681 AtomicOp op, SourceLocation RP)
4682 : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
4683 NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4684 assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions")(static_cast<void> (0));
4685 for (unsigned i = 0; i != args.size(); i++)
4686 SubExprs[i] = args[i];
4687 setDependence(computeDependence(this));
4688}
4689
4690unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4691 switch (Op) {
4692 case AO__c11_atomic_init:
4693 case AO__opencl_atomic_init:
4694 case AO__c11_atomic_load:
4695 case AO__atomic_load_n:
4696 return 2;
4697
4698 case AO__opencl_atomic_load:
4699 case AO__c11_atomic_store:
4700 case AO__c11_atomic_exchange:
4701 case AO__atomic_load:
4702 case AO__atomic_store:
4703 case AO__atomic_store_n:
4704 case AO__atomic_exchange_n:
4705 case AO__c11_atomic_fetch_add:
4706 case AO__c11_atomic_fetch_sub:
4707 case AO__c11_atomic_fetch_and:
4708 case AO__c11_atomic_fetch_or:
4709 case AO__c11_atomic_fetch_xor:
4710 case AO__c11_atomic_fetch_max:
4711 case AO__c11_atomic_fetch_min:
4712 case AO__atomic_fetch_add:
4713 case AO__atomic_fetch_sub:
4714 case AO__atomic_fetch_and:
4715 case AO__atomic_fetch_or:
4716 case AO__atomic_fetch_xor:
4717 case AO__atomic_fetch_nand:
4718 case AO__atomic_add_fetch:
4719 case AO__atomic_sub_fetch:
4720 case AO__atomic_and_fetch:
4721 case AO__atomic_or_fetch:
4722 case AO__atomic_xor_fetch:
4723 case AO__atomic_nand_fetch:
4724 case AO__atomic_min_fetch:
4725 case AO__atomic_max_fetch:
4726 case AO__atomic_fetch_min:
4727 case AO__atomic_fetch_max:
4728 return 3;
4729
4730 case AO__opencl_atomic_store:
4731 case AO__opencl_atomic_exchange:
4732 case AO__opencl_atomic_fetch_add:
4733 case AO__opencl_atomic_fetch_sub:
4734 case AO__opencl_atomic_fetch_and:
4735 case AO__opencl_atomic_fetch_or:
4736 case AO__opencl_atomic_fetch_xor:
4737 case AO__opencl_atomic_fetch_min:
4738 case AO__opencl_atomic_fetch_max:
4739 case AO__atomic_exchange:
4740 return 4;
4741
4742 case AO__c11_atomic_compare_exchange_strong:
4743 case AO__c11_atomic_compare_exchange_weak:
4744 return 5;
4745
4746 case AO__opencl_atomic_compare_exchange_strong:
4747 case AO__opencl_atomic_compare_exchange_weak:
4748 case AO__atomic_compare_exchange:
4749 case AO__atomic_compare_exchange_n:
4750 return 6;
4751 }
4752 llvm_unreachable("unknown atomic op")__builtin_unreachable();
4753}
4754
4755QualType AtomicExpr::getValueType() const {
4756 auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4757 if (auto AT = T->getAs<AtomicType>())
4758 return AT->getValueType();
4759 return T;
4760}
4761
4762QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4763 unsigned ArraySectionCount = 0;
4764 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4765 Base = OASE->getBase();
4766 ++ArraySectionCount;
4767 }
4768 while (auto *ASE =
4769 dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4770 Base = ASE->getBase();
4771 ++ArraySectionCount;
4772 }
4773 Base = Base->IgnoreParenImpCasts();
4774 auto OriginalTy = Base->getType();
4775 if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4776 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4777 OriginalTy = PVD->getOriginalType().getNonReferenceType();
4778
4779 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4780 if (OriginalTy->isAnyPointerType())
4781 OriginalTy = OriginalTy->getPointeeType();
4782 else {
4783 assert (OriginalTy->isArrayType())(static_cast<void> (0));
4784 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4785 }
4786 }
4787 return OriginalTy;
4788}
4789
4790RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
4791 SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
4792 : Expr(RecoveryExprClass, T.getNonReferenceType(),
4793 T->isDependentType() ? VK_LValue : getValueKindForType(T),
4794 OK_Ordinary),
4795 BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
4796 assert(!T.isNull())(static_cast<void> (0));
4797 assert(llvm::all_of(SubExprs, [](Expr* E) { return E != nullptr; }))(static_cast<void> (0));
4798
4799 llvm::copy(SubExprs, getTrailingObjects<Expr *>());
4800 setDependence(computeDependence(this));
4801}
4802
4803RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
4804 SourceLocation BeginLoc,
4805 SourceLocation EndLoc,
4806 ArrayRef<Expr *> SubExprs) {
4807 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
4808 alignof(RecoveryExpr));
4809 return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
4810}
4811
4812RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
4813 void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
4814 alignof(RecoveryExpr));
4815 return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
4816}
4817
4818void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
4819 assert((static_cast<void> (0))
4820 NumDims == Dims.size() &&(static_cast<void> (0))
4821 "Preallocated number of dimensions is different from the provided one.")(static_cast<void> (0));
4822 llvm::copy(Dims, getTrailingObjects<Expr *>());
4823}
4824
4825void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
4826 assert((static_cast<void> (0))
4827 NumDims == BR.size() &&(static_cast<void> (0))
4828 "Preallocated number of dimensions is different from the provided one.")(static_cast<void> (0));
4829 llvm::copy(BR, getTrailingObjects<SourceRange>());
4830}
4831
4832OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
4833 SourceLocation L, SourceLocation R,
4834 ArrayRef<Expr *> Dims)
4835 : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
4836 RPLoc(R), NumDims(Dims.size()) {
4837 setBase(Op);
4838 setDimensions(Dims);
4839 setDependence(computeDependence(this));
4840}
4841
4842OMPArrayShapingExpr *
4843OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
4844 SourceLocation L, SourceLocation R,
4845 ArrayRef<Expr *> Dims,
4846 ArrayRef<SourceRange> BracketRanges) {
4847 assert(Dims.size() == BracketRanges.size() &&(static_cast<void> (0))
4848 "Different number of dimensions and brackets ranges.")(static_cast<void> (0));
4849 void *Mem = Context.Allocate(
4850 totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
4851 alignof(OMPArrayShapingExpr));
4852 auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
4853 E->setBracketsRanges(BracketRanges);
4854 return E;
4855}
4856
4857OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
4858 unsigned NumDims) {
4859 void *Mem = Context.Allocate(
4860 totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
4861 alignof(OMPArrayShapingExpr));
4862 return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
4863}
4864
4865void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
4866 assert(I < NumIterators &&(static_cast<void> (0))
4867 "Idx is greater or equal the number of iterators definitions.")(static_cast<void> (0));
4868 getTrailingObjects<Decl *>()[I] = D;
4869}
4870
4871void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
4872 assert(I < NumIterators &&(static_cast<void> (0))
4873 "Idx is greater or equal the number of iterators definitions.")(static_cast<void> (0));
4874 getTrailingObjects<
4875 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4876 static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
4877}
4878
4879void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
4880 SourceLocation ColonLoc, Expr *End,
4881 SourceLocation SecondColonLoc,
4882 Expr *Step) {
4883 assert(I < NumIterators &&(static_cast<void> (0))
4884 "Idx is greater or equal the number of iterators definitions.")(static_cast<void> (0));
4885 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4886 static_cast<int>(RangeExprOffset::Begin)] =
4887 Begin;
4888 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4889 static_cast<int>(RangeExprOffset::End)] = End;
4890 getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
4891 static_cast<int>(RangeExprOffset::Step)] = Step;
4892 getTrailingObjects<
4893 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4894 static_cast<int>(RangeLocOffset::FirstColonLoc)] =
4895 ColonLoc;
4896 getTrailingObjects<
4897 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4898 static_cast<int>(RangeLocOffset::SecondColonLoc)] =
4899 SecondColonLoc;
4900}
4901
4902Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
4903 return getTrailingObjects<Decl *>()[I];
4904}
4905
4906OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
4907 IteratorRange Res;
4908 Res.Begin =
4909 getTrailingObjects<Expr *>()[I * static_cast<int>(
4910 RangeExprOffset::Total) +
4911 static_cast<int>(RangeExprOffset::Begin)];
4912 Res.End =
4913 getTrailingObjects<Expr *>()[I * static_cast<int>(
4914 RangeExprOffset::Total) +
4915 static_cast<int>(RangeExprOffset::End)];
4916 Res.Step =
4917 getTrailingObjects<Expr *>()[I * static_cast<int>(
4918 RangeExprOffset::Total) +
4919 static_cast<int>(RangeExprOffset::Step)];
4920 return Res;
4921}
4922
4923SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
4924 return getTrailingObjects<
4925 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4926 static_cast<int>(RangeLocOffset::AssignLoc)];
4927}
4928
4929SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
4930 return getTrailingObjects<
4931 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4932 static_cast<int>(RangeLocOffset::FirstColonLoc)];
4933}
4934
4935SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
4936 return getTrailingObjects<
4937 SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
4938 static_cast<int>(RangeLocOffset::SecondColonLoc)];
4939}
4940
4941void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
4942 getTrailingObjects<OMPIteratorHelperData>()[I] = D;
4943}
4944
4945OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
4946 return getTrailingObjects<OMPIteratorHelperData>()[I];
4947}
4948
4949const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
4950 return getTrailingObjects<OMPIteratorHelperData>()[I];
4951}
4952
4953OMPIteratorExpr::OMPIteratorExpr(
4954 QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
4955 SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
4956 ArrayRef<OMPIteratorHelperData> Helpers)
4957 : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
4958 IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
4959 NumIterators(Data.size()) {
4960 for (unsigned I = 0, E = Data.size(); I < E; ++I) {
4961 const IteratorDefinition &D = Data[I];
4962 setIteratorDeclaration(I, D.IteratorDecl);
4963 setAssignmentLoc(I, D.AssignmentLoc);
4964 setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
4965 D.SecondColonLoc, D.Range.Step);
4966 setHelper(I, Helpers[I]);
4967 }
4968 setDependence(computeDependence(this));
4969}
4970
4971OMPIteratorExpr *
4972OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
4973 SourceLocation IteratorKwLoc, SourceLocation L,
4974 SourceLocation R,
4975 ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
4976 ArrayRef<OMPIteratorHelperData> Helpers) {
4977 assert(Data.size() == Helpers.size() &&(static_cast<void> (0))
4978 "Data and helpers must have the same size.")(static_cast<void> (0));
4979 void *Mem = Context.Allocate(
4980 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4981 Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
4982 Data.size() * static_cast<int>(RangeLocOffset::Total),
4983 Helpers.size()),
4984 alignof(OMPIteratorExpr));
4985 return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
4986}
4987
4988OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
4989 unsigned NumIterators) {
4990 void *Mem = Context.Allocate(
4991 totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
4992 NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
4993 NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
4994 alignof(OMPIteratorExpr));
4995 return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
4996}

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include/llvm/Support/TrailingObjects.h

1//===--- TrailingObjects.h - Variable-length classes ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This header defines support for implementing classes that have
11/// some trailing object (or arrays of objects) appended to them. The
12/// main purpose is to make it obvious where this idiom is being used,
13/// and to make the usage more idiomatic and more difficult to get
14/// wrong.
15///
16/// The TrailingObject template abstracts away the reinterpret_cast,
17/// pointer arithmetic, and size calculations used for the allocation
18/// and access of appended arrays of objects, and takes care that they
19/// are all allocated at their required alignment. Additionally, it
20/// ensures that the base type is final -- deriving from a class that
21/// expects data appended immediately after it is typically not safe.
22///
23/// Users are expected to derive from this template, and provide
24/// numTrailingObjects implementations for each trailing type except
25/// the last, e.g. like this sample:
26///
27/// \code
28/// class VarLengthObj : private TrailingObjects<VarLengthObj, int, double> {
29/// friend TrailingObjects;
30///
31/// unsigned NumInts, NumDoubles;
32/// size_t numTrailingObjects(OverloadToken<int>) const { return NumInts; }
33/// };
34/// \endcode
35///
36/// You can access the appended arrays via 'getTrailingObjects', and
37/// determine the size needed for allocation via
38/// 'additionalSizeToAlloc' and 'totalSizeToAlloc'.
39///
40/// All the methods implemented by this class are are intended for use
41/// by the implementation of the class, not as part of its interface
42/// (thus, private inheritance is suggested).
43///
44//===----------------------------------------------------------------------===//
45
46#ifndef LLVM_SUPPORT_TRAILINGOBJECTS_H
47#define LLVM_SUPPORT_TRAILINGOBJECTS_H
48
49#include "llvm/Support/AlignOf.h"
50#include "llvm/Support/Alignment.h"
51#include "llvm/Support/Compiler.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/type_traits.h"
54#include <new>
55#include <type_traits>
56
57namespace llvm {
58
59namespace trailing_objects_internal {
60/// Helper template to calculate the max alignment requirement for a set of
61/// objects.
62template <typename First, typename... Rest> class AlignmentCalcHelper {
63private:
64 enum {
65 FirstAlignment = alignof(First),
66 RestAlignment = AlignmentCalcHelper<Rest...>::Alignment,
67 };
68
69public:
70 enum {
71 Alignment = FirstAlignment > RestAlignment ? FirstAlignment : RestAlignment
72 };
73};
74
75template <typename First> class AlignmentCalcHelper<First> {
76public:
77 enum { Alignment = alignof(First) };
78};
79
80/// The base class for TrailingObjects* classes.
81class TrailingObjectsBase {
82protected:
83 /// OverloadToken's purpose is to allow specifying function overloads
84 /// for different types, without actually taking the types as
85 /// parameters. (Necessary because member function templates cannot
86 /// be specialized, so overloads must be used instead of
87 /// specialization.)
88 template <typename T> struct OverloadToken {};
89};
90
91// Just a little helper for transforming a type pack into the same
92// number of a different type. e.g.:
93// ExtractSecondType<Foo..., int>::type
94template <typename Ty1, typename Ty2> struct ExtractSecondType {
95 typedef Ty2 type;
96};
97
98// TrailingObjectsImpl is somewhat complicated, because it is a
99// recursively inheriting template, in order to handle the template
100// varargs. Each level of inheritance picks off a single trailing type
101// then recurses on the rest. The "Align", "BaseTy", and
102// "TopTrailingObj" arguments are passed through unchanged through the
103// recursion. "PrevTy" is, at each level, the type handled by the
104// level right above it.
105
106template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
107 typename... MoreTys>
108class TrailingObjectsImpl {
109 // The main template definition is never used -- the two
110 // specializations cover all possibilities.
111};
112
113template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
114 typename NextTy, typename... MoreTys>
115class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
116 MoreTys...>
117 : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
118 MoreTys...> {
119
120 typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
121 ParentType;
122
123 struct RequiresRealignment {
124 static const bool value = alignof(PrevTy) < alignof(NextTy);
125 };
126
127 static constexpr bool requiresRealignment() {
128 return RequiresRealignment::value;
129 }
130
131protected:
132 // Ensure the inherited getTrailingObjectsImpl is not hidden.
133 using ParentType::getTrailingObjectsImpl;
134
135 // These two functions are helper functions for
136 // TrailingObjects::getTrailingObjects. They recurse to the left --
137 // the result for each type in the list of trailing types depends on
138 // the result of calling the function on the type to the
139 // left. However, the function for the type to the left is
140 // implemented by a *subclass* of this class, so we invoke it via
141 // the TopTrailingObj, which is, via the
142 // curiously-recurring-template-pattern, the most-derived type in
143 // this recursion, and thus, contains all the overloads.
144 static const NextTy *
145 getTrailingObjectsImpl(const BaseTy *Obj,
146 TrailingObjectsBase::OverloadToken<NextTy>) {
147 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
148 Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
149 TopTrailingObj::callNumTrailingObjects(
150 Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
151
152 if (requiresRealignment())
153 return reinterpret_cast<const NextTy *>(
154 alignAddr(Ptr, Align::Of<NextTy>()));
155 else
156 return reinterpret_cast<const NextTy *>(Ptr);
157 }
158
159 static NextTy *
160 getTrailingObjectsImpl(BaseTy *Obj,
161 TrailingObjectsBase::OverloadToken<NextTy>) {
162 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
8
'Ptr' initialized here
163 Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
7
Passing value via 1st parameter 'Obj'
164 TopTrailingObj::callNumTrailingObjects(
165 Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
166
167 if (requiresRealignment())
9
Taking false branch
168 return reinterpret_cast<NextTy *>(alignAddr(Ptr, Align::Of<NextTy>()));
169 else
170 return reinterpret_cast<NextTy *>(Ptr);
10
Returning pointer (loaded from 'Ptr')
171 }
172
173 // Helper function for TrailingObjects::additionalSizeToAlloc: this
174 // function recurses to superclasses, each of which requires one
175 // fewer size_t argument, and adds its own size.
176 static constexpr size_t additionalSizeToAllocImpl(
177 size_t SizeSoFar, size_t Count1,
178 typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
179 return ParentType::additionalSizeToAllocImpl(
180 (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
181 : SizeSoFar) +
182 sizeof(NextTy) * Count1,
183 MoreCounts...);
184 }
185};
186
187// The base case of the TrailingObjectsImpl inheritance recursion,
188// when there's no more trailing types.
189template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
190class alignas(Align) TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
191 : public TrailingObjectsBase {
192protected:
193 // This is a dummy method, only here so the "using" doesn't fail --
194 // it will never be called, because this function recurses backwards
195 // up the inheritance chain to subclasses.
196 static void getTrailingObjectsImpl();
197
198 static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
199 return SizeSoFar;
200 }
201
202 template <bool CheckAlignment> static void verifyTrailingObjectsAlignment() {}
203};
204
205} // end namespace trailing_objects_internal
206
207// Finally, the main type defined in this file, the one intended for users...
208
209/// See the file comment for details on the usage of the
210/// TrailingObjects type.
211template <typename BaseTy, typename... TrailingTys>
212class TrailingObjects : private trailing_objects_internal::TrailingObjectsImpl<
213 trailing_objects_internal::AlignmentCalcHelper<
214 TrailingTys...>::Alignment,
215 BaseTy, TrailingObjects<BaseTy, TrailingTys...>,
216 BaseTy, TrailingTys...> {
217
218 template <int A, typename B, typename T, typename P, typename... M>
219 friend class trailing_objects_internal::TrailingObjectsImpl;
220
221 template <typename... Tys> class Foo {};
222
223 typedef trailing_objects_internal::TrailingObjectsImpl<
224 trailing_objects_internal::AlignmentCalcHelper<TrailingTys...>::Alignment,
225 BaseTy, TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...>
226 ParentType;
227 using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
228
229 using ParentType::getTrailingObjectsImpl;
230
231 // This function contains only a static_assert BaseTy is final. The
232 // static_assert must be in a function, and not at class-level
233 // because BaseTy isn't complete at class instantiation time, but
234 // will be by the time this function is instantiated.
235 static void verifyTrailingObjectsAssertions() {
236 static_assert(std::is_final<BaseTy>(), "BaseTy must be final.");
237 }
238
239 // These two methods are the base of the recursion for this method.
240 static const BaseTy *
241 getTrailingObjectsImpl(const BaseTy *Obj,
242 TrailingObjectsBase::OverloadToken<BaseTy>) {
243 return Obj;
244 }
245
246 static BaseTy *
247 getTrailingObjectsImpl(BaseTy *Obj,
248 TrailingObjectsBase::OverloadToken<BaseTy>) {
249 return Obj;
250 }
251
252 // callNumTrailingObjects simply calls numTrailingObjects on the
253 // provided Obj -- except when the type being queried is BaseTy
254 // itself. There is always only one of the base object, so that case
255 // is handled here. (An additional benefit of indirecting through
256 // this function is that consumers only say "friend
257 // TrailingObjects", and thus, only this class itself can call the
258 // numTrailingObjects function.)
259 static size_t
260 callNumTrailingObjects(const BaseTy *Obj,
261 TrailingObjectsBase::OverloadToken<BaseTy>) {
262 return 1;
263 }
264
265 template <typename T>
266 static size_t callNumTrailingObjects(const BaseTy *Obj,
267 TrailingObjectsBase::OverloadToken<T>) {
268 return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
269 }
270
271public:
272 // Make this (privately inherited) member public.
273#ifndef _MSC_VER
274 using ParentType::OverloadToken;
275#else
276 // An MSVC bug prevents the above from working, (last tested at CL version
277 // 19.28). "Class5" in TrailingObjectsTest.cpp tests the problematic case.
278 template <typename T>
279 using OverloadToken = typename ParentType::template OverloadToken<T>;
280#endif
281
282 /// Returns a pointer to the trailing object array of the given type
283 /// (which must be one of those specified in the class template). The
284 /// array may have zero or more elements in it.
285 template <typename T> const T *getTrailingObjects() const {
286 verifyTrailingObjectsAssertions();
287 // Forwards to an impl function with overloads, since member
288 // function templates can't be specialized.
289 return this->getTrailingObjectsImpl(
290 static_cast<const BaseTy *>(this),
291 TrailingObjectsBase::OverloadToken<T>());
292 }
293
294 /// Returns a pointer to the trailing object array of the given type
295 /// (which must be one of those specified in the class template). The
296 /// array may have zero or more elements in it.
297 template <typename T> T *getTrailingObjects() {
298 verifyTrailingObjectsAssertions();
299 // Forwards to an impl function with overloads, since member
300 // function templates can't be specialized.
301 return this->getTrailingObjectsImpl(
6
Calling 'TrailingObjectsImpl::getTrailingObjectsImpl'
11
Returning from 'TrailingObjectsImpl::getTrailingObjectsImpl'
12
Returning pointer
302 static_cast<BaseTy *>(this), TrailingObjectsBase::OverloadToken<T>());
5
Passing value via 1st parameter 'Obj'
303 }
304
305 /// Returns the size of the trailing data, if an object were
306 /// allocated with the given counts (The counts are in the same order
307 /// as the template arguments). This does not include the size of the
308 /// base object. The template arguments must be the same as those
309 /// used in the class; they are supplied here redundantly only so
310 /// that it's clear what the counts are counting in callers.
311 template <typename... Tys>
312 static constexpr std::enable_if_t<
313 std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
314 additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
315 TrailingTys, size_t>::type... Counts) {
316 return ParentType::additionalSizeToAllocImpl(0, Counts...);
317 }
318
319 /// Returns the total size of an object if it were allocated with the
320 /// given trailing object counts. This is the same as
321 /// additionalSizeToAlloc, except it *does* include the size of the base
322 /// object.
323 template <typename... Tys>
324 static constexpr std::enable_if_t<
325 std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
326 totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
327 TrailingTys, size_t>::type... Counts) {
328 return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
329 }
330
331 TrailingObjects() = default;
332 TrailingObjects(const TrailingObjects &) = delete;
333 TrailingObjects(TrailingObjects &&) = delete;
334 TrailingObjects &operator=(const TrailingObjects &) = delete;
335 TrailingObjects &operator=(TrailingObjects &&) = delete;
336
337 /// A type where its ::with_counts template member has a ::type member
338 /// suitable for use as uninitialized storage for an object with the given
339 /// trailing object counts. The template arguments are similar to those
340 /// of additionalSizeToAlloc.
341 ///
342 /// Use with FixedSizeStorageOwner, e.g.:
343 ///
344 /// \code{.cpp}
345 ///
346 /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
347 /// MyObj::FixedSizeStorageOwner
348 /// myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
349 /// MyObj *const myStackObjPtr = myStackObjOwner.get();
350 ///
351 /// \endcode
352 template <typename... Tys> struct FixedSizeStorage {
353 template <size_t... Counts> struct with_counts {
354 enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
355 struct type {
356 alignas(BaseTy) char buffer[Size];
357 };
358 };
359 };
360
361 /// A type that acts as the owner for an object placed into fixed storage.
362 class FixedSizeStorageOwner {
363 public:
364 FixedSizeStorageOwner(BaseTy *p) : p(p) {}
365 ~FixedSizeStorageOwner() {
366 assert(p && "FixedSizeStorageOwner owns null?")(static_cast<void> (0));
367 p->~BaseTy();
368 }
369
370 BaseTy *get() { return p; }
371 const BaseTy *get() const { return p; }
372
373 private:
374 FixedSizeStorageOwner(const FixedSizeStorageOwner &) = delete;
375 FixedSizeStorageOwner(FixedSizeStorageOwner &&) = delete;
376 FixedSizeStorageOwner &operator=(const FixedSizeStorageOwner &) = delete;
377 FixedSizeStorageOwner &operator=(FixedSizeStorageOwner &&) = delete;
378
379 BaseTy *const p;
380 };
381};
382
383} // end namespace llvm
384
385#endif