Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 4853, column 18
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExpr.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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp

1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/RecursiveASTVisitor.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/FixedPoint.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/LiteralSupport.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Sema/AnalysisBasedWarnings.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/DelayedDiagnostic.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/Overload.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/SemaFixItUtils.h"
46#include "clang/Sema/SemaInternal.h"
47#include "clang/Sema/Template.h"
48#include "llvm/Support/ConvertUTF.h"
49#include "llvm/Support/SaveAndRestore.h"
50using namespace clang;
51using namespace sema;
52
53/// Determine whether the use of this declaration is valid, without
54/// emitting diagnostics.
55bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
56 // See if this is an auto-typed variable whose initializer we are parsing.
57 if (ParsingInitForAutoVars.count(D))
58 return false;
59
60 // See if this is a deleted function.
61 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
62 if (FD->isDeleted())
63 return false;
64
65 // If the function has a deduced return type, and we can't deduce it,
66 // then we can't use it either.
67 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
68 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
69 return false;
70
71 // See if this is an aligned allocation/deallocation function that is
72 // unavailable.
73 if (TreatUnavailableAsInvalid &&
74 isUnavailableAlignedAllocationFunction(*FD))
75 return false;
76 }
77
78 // See if this function is unavailable.
79 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
80 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
81 return false;
82
83 return true;
84}
85
86static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
87 // Warn if this is used but marked unused.
88 if (const auto *A = D->getAttr<UnusedAttr>()) {
89 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
90 // should diagnose them.
91 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
92 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
93 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
94 if (DC && !DC->hasAttr<UnusedAttr>())
95 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
96 }
97 }
98}
99
100/// Emit a note explaining that this function is deleted.
101void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
102 assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void
> (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 102, __PRETTY_FUNCTION__))
;
103
104 if (Decl->isDefaulted()) {
105 // If the method was explicitly defaulted, point at that declaration.
106 if (!Decl->isImplicit())
107 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108
109 // Try to diagnose why this special member function was implicitly
110 // deleted. This might fail, if that reason no longer applies.
111 DiagnoseDeletedDefaultedFunction(Decl);
112 return;
113 }
114
115 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
116 if (Ctor && Ctor->isInheritingConstructor())
117 return NoteDeletedInheritingConstructor(Ctor);
118
119 Diag(Decl->getLocation(), diag::note_availability_specified_here)
120 << Decl << 1;
121}
122
123/// Determine whether a FunctionDecl was ever declared with an
124/// explicit storage class.
125static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
126 for (auto I : D->redecls()) {
127 if (I->getStorageClass() != SC_None)
128 return true;
129 }
130 return false;
131}
132
133/// Check whether we're in an extern inline function and referring to a
134/// variable or function with internal linkage (C11 6.7.4p3).
135///
136/// This is only a warning because we used to silently accept this code, but
137/// in many cases it will not behave correctly. This is not enabled in C++ mode
138/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
139/// and so while there may still be user mistakes, most of the time we can't
140/// prove that there are errors.
141static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
142 const NamedDecl *D,
143 SourceLocation Loc) {
144 // This is disabled under C++; there are too many ways for this to fire in
145 // contexts where the warning is a false positive, or where it is technically
146 // correct but benign.
147 if (S.getLangOpts().CPlusPlus)
148 return;
149
150 // Check if this is an inlined function or method.
151 FunctionDecl *Current = S.getCurFunctionDecl();
152 if (!Current)
153 return;
154 if (!Current->isInlined())
155 return;
156 if (!Current->isExternallyVisible())
157 return;
158
159 // Check if the decl has internal linkage.
160 if (D->getFormalLinkage() != InternalLinkage)
161 return;
162
163 // Downgrade from ExtWarn to Extension if
164 // (1) the supposedly external inline function is in the main file,
165 // and probably won't be included anywhere else.
166 // (2) the thing we're referencing is a pure function.
167 // (3) the thing we're referencing is another inline function.
168 // This last can give us false negatives, but it's better than warning on
169 // wrappers for simple C library functions.
170 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
171 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
172 if (!DowngradeWarning && UsedFn)
173 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
174
175 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
176 : diag::ext_internal_in_extern_inline)
177 << /*IsVar=*/!UsedFn << D;
178
179 S.MaybeSuggestAddingStaticToDecl(Current);
180
181 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
182 << D;
183}
184
185void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
186 const FunctionDecl *First = Cur->getFirstDecl();
187
188 // Suggest "static" on the function, if possible.
189 if (!hasAnyExplicitStorageClass(First)) {
190 SourceLocation DeclBegin = First->getSourceRange().getBegin();
191 Diag(DeclBegin, diag::note_convert_inline_to_static)
192 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
193 }
194}
195
196/// Determine whether the use of this declaration is valid, and
197/// emit any corresponding diagnostics.
198///
199/// This routine diagnoses various problems with referencing
200/// declarations that can occur when using a declaration. For example,
201/// it might warn if a deprecated or unavailable declaration is being
202/// used, or produce an error (and return true) if a C++0x deleted
203/// function is being used.
204///
205/// \returns true if there was an error (this declaration cannot be
206/// referenced), false otherwise.
207///
208bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
209 const ObjCInterfaceDecl *UnknownObjCClass,
210 bool ObjCPropertyAccess,
211 bool AvoidPartialAvailabilityChecks,
212 ObjCInterfaceDecl *ClassReceiver) {
213 SourceLocation Loc = Locs.front();
214 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
215 // If there were any diagnostics suppressed by template argument deduction,
216 // emit them now.
217 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
218 if (Pos != SuppressedDiagnostics.end()) {
219 for (const PartialDiagnosticAt &Suppressed : Pos->second)
220 Diag(Suppressed.first, Suppressed.second);
221
222 // Clear out the list of suppressed diagnostics, so that we don't emit
223 // them again for this specialization. However, we don't obsolete this
224 // entry from the table, because we want to avoid ever emitting these
225 // diagnostics again.
226 Pos->second.clear();
227 }
228
229 // C++ [basic.start.main]p3:
230 // The function 'main' shall not be used within a program.
231 if (cast<FunctionDecl>(D)->isMain())
232 Diag(Loc, diag::ext_main_used);
233
234 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
235 }
236
237 // See if this is an auto-typed variable whose initializer we are parsing.
238 if (ParsingInitForAutoVars.count(D)) {
239 if (isa<BindingDecl>(D)) {
240 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
241 << D->getDeclName();
242 } else {
243 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
244 << D->getDeclName() << cast<VarDecl>(D)->getType();
245 }
246 return true;
247 }
248
249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
250 // See if this is a deleted function.
251 if (FD->isDeleted()) {
252 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
253 if (Ctor && Ctor->isInheritingConstructor())
254 Diag(Loc, diag::err_deleted_inherited_ctor_use)
255 << Ctor->getParent()
256 << Ctor->getInheritedConstructor().getConstructor()->getParent();
257 else
258 Diag(Loc, diag::err_deleted_function_use);
259 NoteDeletedFunction(FD);
260 return true;
261 }
262
263 // [expr.prim.id]p4
264 // A program that refers explicitly or implicitly to a function with a
265 // trailing requires-clause whose constraint-expression is not satisfied,
266 // other than to declare it, is ill-formed. [...]
267 //
268 // See if this is a function with constraints that need to be satisfied.
269 // Check this before deducing the return type, as it might instantiate the
270 // definition.
271 if (FD->getTrailingRequiresClause()) {
272 ConstraintSatisfaction Satisfaction;
273 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
274 // A diagnostic will have already been generated (non-constant
275 // constraint expression, for example)
276 return true;
277 if (!Satisfaction.IsSatisfied) {
278 Diag(Loc,
279 diag::err_reference_to_function_with_unsatisfied_constraints)
280 << D;
281 DiagnoseUnsatisfiedConstraint(Satisfaction);
282 return true;
283 }
284 }
285
286 // If the function has a deduced return type, and we can't deduce it,
287 // then we can't use it either.
288 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
289 DeduceReturnType(FD, Loc))
290 return true;
291
292 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
293 return true;
294 }
295
296 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
297 // Lambdas are only default-constructible or assignable in C++2a onwards.
298 if (MD->getParent()->isLambda() &&
299 ((isa<CXXConstructorDecl>(MD) &&
300 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
301 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
302 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
303 << !isa<CXXConstructorDecl>(MD);
304 }
305 }
306
307 auto getReferencedObjCProp = [](const NamedDecl *D) ->
308 const ObjCPropertyDecl * {
309 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
310 return MD->findPropertyDecl();
311 return nullptr;
312 };
313 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
314 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
315 return true;
316 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
317 return true;
318 }
319
320 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
321 // Only the variables omp_in and omp_out are allowed in the combiner.
322 // Only the variables omp_priv and omp_orig are allowed in the
323 // initializer-clause.
324 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
325 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
326 isa<VarDecl>(D)) {
327 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
328 << getCurFunction()->HasOMPDeclareReductionCombiner;
329 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
330 return true;
331 }
332
333 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
334 // List-items in map clauses on this construct may only refer to the declared
335 // variable var and entities that could be referenced by a procedure defined
336 // at the same location
337 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
338 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
339 isa<VarDecl>(D)) {
340 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
341 << DMD->getVarName().getAsString();
342 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
343 return true;
344 }
345
346 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
347 AvoidPartialAvailabilityChecks, ClassReceiver);
348
349 DiagnoseUnusedOfDecl(*this, D, Loc);
350
351 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
352
353 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
354 !isUnevaluatedContext()) {
355 // C++ [expr.prim.req.nested] p3
356 // A local parameter shall only appear as an unevaluated operand
357 // (Clause 8) within the constraint-expression.
358 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
359 << D;
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 return false;
365}
366
367/// DiagnoseSentinelCalls - This routine checks whether a call or
368/// message-send is to a declaration with the sentinel attribute, and
369/// if so, it checks that the requirements of the sentinel are
370/// satisfied.
371void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
372 ArrayRef<Expr *> Args) {
373 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
374 if (!attr)
375 return;
376
377 // The number of formal parameters of the declaration.
378 unsigned numFormalParams;
379
380 // The kind of declaration. This is also an index into a %select in
381 // the diagnostic.
382 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
383
384 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
385 numFormalParams = MD->param_size();
386 calleeType = CT_Method;
387 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
388 numFormalParams = FD->param_size();
389 calleeType = CT_Function;
390 } else if (isa<VarDecl>(D)) {
391 QualType type = cast<ValueDecl>(D)->getType();
392 const FunctionType *fn = nullptr;
393 if (const PointerType *ptr = type->getAs<PointerType>()) {
394 fn = ptr->getPointeeType()->getAs<FunctionType>();
395 if (!fn) return;
396 calleeType = CT_Function;
397 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
398 fn = ptr->getPointeeType()->castAs<FunctionType>();
399 calleeType = CT_Block;
400 } else {
401 return;
402 }
403
404 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
405 numFormalParams = proto->getNumParams();
406 } else {
407 numFormalParams = 0;
408 }
409 } else {
410 return;
411 }
412
413 // "nullPos" is the number of formal parameters at the end which
414 // effectively count as part of the variadic arguments. This is
415 // useful if you would prefer to not have *any* formal parameters,
416 // but the language forces you to have at least one.
417 unsigned nullPos = attr->getNullPos();
418 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"
) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 418, __PRETTY_FUNCTION__))
;
419 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
420
421 // The number of arguments which should follow the sentinel.
422 unsigned numArgsAfterSentinel = attr->getSentinel();
423
424 // If there aren't enough arguments for all the formal parameters,
425 // the sentinel, and the args after the sentinel, complain.
426 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
427 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
428 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429 return;
430 }
431
432 // Otherwise, find the sentinel expression.
433 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
434 if (!sentinelExpr) return;
435 if (sentinelExpr->isValueDependent()) return;
436 if (Context.isSentinelNullExpr(sentinelExpr)) return;
437
438 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
439 // or 'NULL' if those are actually defined in the context. Only use
440 // 'nil' for ObjC methods, where it's much more likely that the
441 // variadic arguments form a list of object pointers.
442 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
443 std::string NullValue;
444 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
445 NullValue = "nil";
446 else if (getLangOpts().CPlusPlus11)
447 NullValue = "nullptr";
448 else if (PP.isMacroDefined("NULL"))
449 NullValue = "NULL";
450 else
451 NullValue = "(void*) 0";
452
453 if (MissingNilLoc.isInvalid())
454 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
455 else
456 Diag(MissingNilLoc, diag::warn_missing_sentinel)
457 << int(calleeType)
458 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
459 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460}
461
462SourceRange Sema::getExprRange(Expr *E) const {
463 return E ? E->getSourceRange() : SourceRange();
464}
465
466//===----------------------------------------------------------------------===//
467// Standard Promotions and Conversions
468//===----------------------------------------------------------------------===//
469
470/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
471ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
472 // Handle any placeholder expressions which made it here.
473 if (E->getType()->isPlaceholderType()) {
474 ExprResult result = CheckPlaceholderExpr(E);
475 if (result.isInvalid()) return ExprError();
476 E = result.get();
477 }
478
479 QualType Ty = E->getType();
480 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 480, __PRETTY_FUNCTION__))
;
481
482 if (Ty->isFunctionType()) {
483 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
484 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
485 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
486 return ExprError();
487
488 E = ImpCastExprToType(E, Context.getPointerType(Ty),
489 CK_FunctionToPointerDecay).get();
490 } else if (Ty->isArrayType()) {
491 // In C90 mode, arrays only promote to pointers if the array expression is
492 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
493 // type 'array of type' is converted to an expression that has type 'pointer
494 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
495 // that has type 'array of type' ...". The relevant change is "an lvalue"
496 // (C90) to "an expression" (C99).
497 //
498 // C++ 4.2p1:
499 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
500 // T" can be converted to an rvalue of type "pointer to T".
501 //
502 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
503 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
504 CK_ArrayToPointerDecay).get();
505 }
506 return E;
507}
508
509static void CheckForNullPointerDereference(Sema &S, Expr *E) {
510 // Check to see if we are dereferencing a null pointer. If so,
511 // and if not volatile-qualified, this is undefined behavior that the
512 // optimizer will delete, so warn about it. People sometimes try to use this
513 // to get a deterministic trap and are surprised by clang's behavior. This
514 // only handles the pattern "*null", which is a very syntactic check.
515 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
516 if (UO && UO->getOpcode() == UO_Deref &&
517 UO->getSubExpr()->getType()->isPointerType()) {
518 const LangAS AS =
519 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
520 if ((!isTargetAddressSpace(AS) ||
521 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
522 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
523 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
524 !UO->getType().isVolatileQualified()) {
525 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
526 S.PDiag(diag::warn_indirection_through_null)
527 << UO->getSubExpr()->getSourceRange());
528 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
529 S.PDiag(diag::note_indirection_through_null));
530 }
531 }
532}
533
534static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
535 SourceLocation AssignLoc,
536 const Expr* RHS) {
537 const ObjCIvarDecl *IV = OIRE->getDecl();
538 if (!IV)
539 return;
540
541 DeclarationName MemberName = IV->getDeclName();
542 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
543 if (!Member || !Member->isStr("isa"))
544 return;
545
546 const Expr *Base = OIRE->getBase();
547 QualType BaseType = Base->getType();
548 if (OIRE->isArrow())
549 BaseType = BaseType->getPointeeType();
550 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
551 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
552 ObjCInterfaceDecl *ClassDeclared = nullptr;
553 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
554 if (!ClassDeclared->getSuperClass()
555 && (*ClassDeclared->ivar_begin()) == IV) {
556 if (RHS) {
557 NamedDecl *ObjectSetClass =
558 S.LookupSingleName(S.TUScope,
559 &S.Context.Idents.get("object_setClass"),
560 SourceLocation(), S.LookupOrdinaryName);
561 if (ObjectSetClass) {
562 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
563 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
564 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
565 "object_setClass(")
566 << FixItHint::CreateReplacement(
567 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
568 << FixItHint::CreateInsertion(RHSLocEnd, ")");
569 }
570 else
571 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
572 } else {
573 NamedDecl *ObjectGetClass =
574 S.LookupSingleName(S.TUScope,
575 &S.Context.Idents.get("object_getClass"),
576 SourceLocation(), S.LookupOrdinaryName);
577 if (ObjectGetClass)
578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580 "object_getClass(")
581 << FixItHint::CreateReplacement(
582 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
583 else
584 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
585 }
586 S.Diag(IV->getLocation(), diag::note_ivar_decl);
587 }
588 }
589}
590
591ExprResult Sema::DefaultLvalueConversion(Expr *E) {
592 // Handle any placeholder expressions which made it here.
593 if (E->getType()->isPlaceholderType()) {
594 ExprResult result = CheckPlaceholderExpr(E);
595 if (result.isInvalid()) return ExprError();
596 E = result.get();
597 }
598
599 // C++ [conv.lval]p1:
600 // A glvalue of a non-function, non-array type T can be
601 // converted to a prvalue.
602 if (!E->isGLValue()) return E;
603
604 QualType T = E->getType();
605 assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 605, __PRETTY_FUNCTION__))
;
606
607 // We don't want to throw lvalue-to-rvalue casts on top of
608 // expressions of certain types in C++.
609 if (getLangOpts().CPlusPlus &&
610 (E->getType() == Context.OverloadTy ||
611 T->isDependentType() ||
612 T->isRecordType()))
613 return E;
614
615 // The C standard is actually really unclear on this point, and
616 // DR106 tells us what the result should be but not why. It's
617 // generally best to say that void types just doesn't undergo
618 // lvalue-to-rvalue at all. Note that expressions of unqualified
619 // 'void' type are never l-values, but qualified void can be.
620 if (T->isVoidType())
621 return E;
622
623 // OpenCL usually rejects direct accesses to values of 'half' type.
624 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
625 T->isHalfType()) {
626 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
627 << 0 << T;
628 return ExprError();
629 }
630
631 CheckForNullPointerDereference(*this, E);
632 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
633 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
634 &Context.Idents.get("object_getClass"),
635 SourceLocation(), LookupOrdinaryName);
636 if (ObjectGetClass)
637 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
638 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
639 << FixItHint::CreateReplacement(
640 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
641 else
642 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
643 }
644 else if (const ObjCIvarRefExpr *OIRE =
645 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
646 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
647
648 // C++ [conv.lval]p1:
649 // [...] If T is a non-class type, the type of the prvalue is the
650 // cv-unqualified version of T. Otherwise, the type of the
651 // rvalue is T.
652 //
653 // C99 6.3.2.1p2:
654 // If the lvalue has qualified type, the value has the unqualified
655 // version of the type of the lvalue; otherwise, the value has the
656 // type of the lvalue.
657 if (T.hasQualifiers())
658 T = T.getUnqualifiedType();
659
660 // Under the MS ABI, lock down the inheritance model now.
661 if (T->isMemberPointerType() &&
662 Context.getTargetInfo().getCXXABI().isMicrosoft())
663 (void)isCompleteType(E->getExprLoc(), T);
664
665 ExprResult Res = CheckLValueToRValueConversionOperand(E);
666 if (Res.isInvalid())
667 return Res;
668 E = Res.get();
669
670 // Loading a __weak object implicitly retains the value, so we need a cleanup to
671 // balance that.
672 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
673 Cleanup.setExprNeedsCleanups(true);
674
675 // C++ [conv.lval]p3:
676 // If T is cv std::nullptr_t, the result is a null pointer constant.
677 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
678 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
679
680 // C11 6.3.2.1p2:
681 // ... if the lvalue has atomic type, the value has the non-atomic version
682 // of the type of the lvalue ...
683 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
684 T = Atomic->getValueType().getUnqualifiedType();
685 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
686 nullptr, VK_RValue);
687 }
688
689 return Res;
690}
691
692ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
693 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
694 if (Res.isInvalid())
695 return ExprError();
696 Res = DefaultLvalueConversion(Res.get());
697 if (Res.isInvalid())
698 return ExprError();
699 return Res;
700}
701
702/// CallExprUnaryConversions - a special case of an unary conversion
703/// performed on a function designator of a call expression.
704ExprResult Sema::CallExprUnaryConversions(Expr *E) {
705 QualType Ty = E->getType();
706 ExprResult Res = E;
707 // Only do implicit cast for a function type, but not for a pointer
708 // to function type.
709 if (Ty->isFunctionType()) {
710 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
711 CK_FunctionToPointerDecay).get();
712 if (Res.isInvalid())
713 return ExprError();
714 }
715 Res = DefaultLvalueConversion(Res.get());
716 if (Res.isInvalid())
717 return ExprError();
718 return Res.get();
719}
720
721/// UsualUnaryConversions - Performs various conversions that are common to most
722/// operators (C99 6.3). The conversions of array and function types are
723/// sometimes suppressed. For example, the array->pointer conversion doesn't
724/// apply if the array is an argument to the sizeof or address (&) operators.
725/// In these instances, this routine should *not* be called.
726ExprResult Sema::UsualUnaryConversions(Expr *E) {
727 // First, convert to an r-value.
728 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
729 if (Res.isInvalid())
730 return ExprError();
731 E = Res.get();
732
733 QualType Ty = E->getType();
734 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 734, __PRETTY_FUNCTION__))
;
735
736 // Half FP have to be promoted to float unless it is natively supported
737 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
738 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
739
740 // Try to perform integral promotions if the object has a theoretically
741 // promotable type.
742 if (Ty->isIntegralOrUnscopedEnumerationType()) {
743 // C99 6.3.1.1p2:
744 //
745 // The following may be used in an expression wherever an int or
746 // unsigned int may be used:
747 // - an object or expression with an integer type whose integer
748 // conversion rank is less than or equal to the rank of int
749 // and unsigned int.
750 // - A bit-field of type _Bool, int, signed int, or unsigned int.
751 //
752 // If an int can represent all values of the original type, the
753 // value is converted to an int; otherwise, it is converted to an
754 // unsigned int. These are called the integer promotions. All
755 // other types are unchanged by the integer promotions.
756
757 QualType PTy = Context.isPromotableBitField(E);
758 if (!PTy.isNull()) {
759 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
760 return E;
761 }
762 if (Ty->isPromotableIntegerType()) {
763 QualType PT = Context.getPromotedIntegerType(Ty);
764 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
765 return E;
766 }
767 }
768 return E;
769}
770
771/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
772/// do not have a prototype. Arguments that have type float or __fp16
773/// are promoted to double. All other argument types are converted by
774/// UsualUnaryConversions().
775ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
776 QualType Ty = E->getType();
777 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 777, __PRETTY_FUNCTION__))
;
778
779 ExprResult Res = UsualUnaryConversions(E);
780 if (Res.isInvalid())
781 return ExprError();
782 E = Res.get();
783
784 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
785 // promote to double.
786 // Note that default argument promotion applies only to float (and
787 // half/fp16); it does not apply to _Float16.
788 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
789 if (BTy && (BTy->getKind() == BuiltinType::Half ||
790 BTy->getKind() == BuiltinType::Float)) {
791 if (getLangOpts().OpenCL &&
792 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
793 if (BTy->getKind() == BuiltinType::Half) {
794 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
795 }
796 } else {
797 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
798 }
799 }
800
801 // C++ performs lvalue-to-rvalue conversion as a default argument
802 // promotion, even on class types, but note:
803 // C++11 [conv.lval]p2:
804 // When an lvalue-to-rvalue conversion occurs in an unevaluated
805 // operand or a subexpression thereof the value contained in the
806 // referenced object is not accessed. Otherwise, if the glvalue
807 // has a class type, the conversion copy-initializes a temporary
808 // of type T from the glvalue and the result of the conversion
809 // is a prvalue for the temporary.
810 // FIXME: add some way to gate this entire thing for correctness in
811 // potentially potentially evaluated contexts.
812 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
813 ExprResult Temp = PerformCopyInitialization(
814 InitializedEntity::InitializeTemporary(E->getType()),
815 E->getExprLoc(), E);
816 if (Temp.isInvalid())
817 return ExprError();
818 E = Temp.get();
819 }
820
821 return E;
822}
823
824/// Determine the degree of POD-ness for an expression.
825/// Incomplete types are considered POD, since this check can be performed
826/// when we're in an unevaluated context.
827Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
828 if (Ty->isIncompleteType()) {
829 // C++11 [expr.call]p7:
830 // After these conversions, if the argument does not have arithmetic,
831 // enumeration, pointer, pointer to member, or class type, the program
832 // is ill-formed.
833 //
834 // Since we've already performed array-to-pointer and function-to-pointer
835 // decay, the only such type in C++ is cv void. This also handles
836 // initializer lists as variadic arguments.
837 if (Ty->isVoidType())
838 return VAK_Invalid;
839
840 if (Ty->isObjCObjectType())
841 return VAK_Invalid;
842 return VAK_Valid;
843 }
844
845 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
846 return VAK_Invalid;
847
848 if (Ty.isCXX98PODType(Context))
849 return VAK_Valid;
850
851 // C++11 [expr.call]p7:
852 // Passing a potentially-evaluated argument of class type (Clause 9)
853 // having a non-trivial copy constructor, a non-trivial move constructor,
854 // or a non-trivial destructor, with no corresponding parameter,
855 // is conditionally-supported with implementation-defined semantics.
856 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
857 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
858 if (!Record->hasNonTrivialCopyConstructor() &&
859 !Record->hasNonTrivialMoveConstructor() &&
860 !Record->hasNonTrivialDestructor())
861 return VAK_ValidInCXX11;
862
863 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
864 return VAK_Valid;
865
866 if (Ty->isObjCObjectType())
867 return VAK_Invalid;
868
869 if (getLangOpts().MSVCCompat)
870 return VAK_MSVCUndefined;
871
872 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
873 // permitted to reject them. We should consider doing so.
874 return VAK_Undefined;
875}
876
877void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
878 // Don't allow one to pass an Objective-C interface to a vararg.
879 const QualType &Ty = E->getType();
880 VarArgKind VAK = isValidVarArgType(Ty);
881
882 // Complain about passing non-POD types through varargs.
883 switch (VAK) {
884 case VAK_ValidInCXX11:
885 DiagRuntimeBehavior(
886 E->getBeginLoc(), nullptr,
887 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
888 LLVM_FALLTHROUGH[[gnu::fallthrough]];
889 case VAK_Valid:
890 if (Ty->isRecordType()) {
891 // This is unlikely to be what the user intended. If the class has a
892 // 'c_str' member function, the user probably meant to call that.
893 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
894 PDiag(diag::warn_pass_class_arg_to_vararg)
895 << Ty << CT << hasCStrMethod(E) << ".c_str()");
896 }
897 break;
898
899 case VAK_Undefined:
900 case VAK_MSVCUndefined:
901 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
902 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
903 << getLangOpts().CPlusPlus11 << Ty << CT);
904 break;
905
906 case VAK_Invalid:
907 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
908 Diag(E->getBeginLoc(),
909 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
910 << Ty << CT;
911 else if (Ty->isObjCObjectType())
912 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
913 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
914 << Ty << CT);
915 else
916 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
917 << isa<InitListExpr>(E) << Ty << CT;
918 break;
919 }
920}
921
922/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
923/// will create a trap if the resulting type is not a POD type.
924ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
925 FunctionDecl *FDecl) {
926 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
927 // Strip the unbridged-cast placeholder expression off, if applicable.
928 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
929 (CT == VariadicMethod ||
930 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
931 E = stripARCUnbridgedCast(E);
932
933 // Otherwise, do normal placeholder checking.
934 } else {
935 ExprResult ExprRes = CheckPlaceholderExpr(E);
936 if (ExprRes.isInvalid())
937 return ExprError();
938 E = ExprRes.get();
939 }
940 }
941
942 ExprResult ExprRes = DefaultArgumentPromotion(E);
943 if (ExprRes.isInvalid())
944 return ExprError();
945 E = ExprRes.get();
946
947 // Diagnostics regarding non-POD argument types are
948 // emitted along with format string checking in Sema::CheckFunctionCall().
949 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
950 // Turn this into a trap.
951 CXXScopeSpec SS;
952 SourceLocation TemplateKWLoc;
953 UnqualifiedId Name;
954 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
955 E->getBeginLoc());
956 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
957 /*HasTrailingLParen=*/true,
958 /*IsAddressOfOperand=*/false);
959 if (TrapFn.isInvalid())
960 return ExprError();
961
962 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
963 None, E->getEndLoc());
964 if (Call.isInvalid())
965 return ExprError();
966
967 ExprResult Comma =
968 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
969 if (Comma.isInvalid())
970 return ExprError();
971 return Comma.get();
972 }
973
974 if (!getLangOpts().CPlusPlus &&
975 RequireCompleteType(E->getExprLoc(), E->getType(),
976 diag::err_call_incomplete_argument))
977 return ExprError();
978
979 return E;
980}
981
982/// Converts an integer to complex float type. Helper function of
983/// UsualArithmeticConversions()
984///
985/// \return false if the integer expression is an integer type and is
986/// successfully converted to the complex type.
987static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
988 ExprResult &ComplexExpr,
989 QualType IntTy,
990 QualType ComplexTy,
991 bool SkipCast) {
992 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
993 if (SkipCast) return false;
994 if (IntTy->isIntegerType()) {
995 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
996 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
997 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
998 CK_FloatingRealToComplex);
999 } else {
1000 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1000, __PRETTY_FUNCTION__))
;
1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1002 CK_IntegralComplexToFloatingComplex);
1003 }
1004 return false;
1005}
1006
1007/// Handle arithmetic conversion with complex types. Helper function of
1008/// UsualArithmeticConversions()
1009static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1010 ExprResult &RHS, QualType LHSType,
1011 QualType RHSType,
1012 bool IsCompAssign) {
1013 // if we have an integer operand, the result is the complex type.
1014 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1015 /*skipCast*/false))
1016 return LHSType;
1017 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1018 /*skipCast*/IsCompAssign))
1019 return RHSType;
1020
1021 // This handles complex/complex, complex/float, or float/complex.
1022 // When both operands are complex, the shorter operand is converted to the
1023 // type of the longer, and that is the type of the result. This corresponds
1024 // to what is done when combining two real floating-point operands.
1025 // The fun begins when size promotion occur across type domains.
1026 // From H&S 6.3.4: When one operand is complex and the other is a real
1027 // floating-point type, the less precise type is converted, within it's
1028 // real or complex domain, to the precision of the other type. For example,
1029 // when combining a "long double" with a "double _Complex", the
1030 // "double _Complex" is promoted to "long double _Complex".
1031
1032 // Compute the rank of the two types, regardless of whether they are complex.
1033 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1034
1035 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1036 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1037 QualType LHSElementType =
1038 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1039 QualType RHSElementType =
1040 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1041
1042 QualType ResultType = S.Context.getComplexType(LHSElementType);
1043 if (Order < 0) {
1044 // Promote the precision of the LHS if not an assignment.
1045 ResultType = S.Context.getComplexType(RHSElementType);
1046 if (!IsCompAssign) {
1047 if (LHSComplexType)
1048 LHS =
1049 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1050 else
1051 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1052 }
1053 } else if (Order > 0) {
1054 // Promote the precision of the RHS.
1055 if (RHSComplexType)
1056 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1057 else
1058 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1059 }
1060 return ResultType;
1061}
1062
1063/// Handle arithmetic conversion from integer to float. Helper function
1064/// of UsualArithmeticConversions()
1065static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1066 ExprResult &IntExpr,
1067 QualType FloatTy, QualType IntTy,
1068 bool ConvertFloat, bool ConvertInt) {
1069 if (IntTy->isIntegerType()) {
1070 if (ConvertInt)
1071 // Convert intExpr to the lhs floating point type.
1072 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1073 CK_IntegralToFloating);
1074 return FloatTy;
1075 }
1076
1077 // Convert both sides to the appropriate complex float.
1078 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1078, __PRETTY_FUNCTION__))
;
1079 QualType result = S.Context.getComplexType(FloatTy);
1080
1081 // _Complex int -> _Complex float
1082 if (ConvertInt)
1083 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1084 CK_IntegralComplexToFloatingComplex);
1085
1086 // float -> _Complex float
1087 if (ConvertFloat)
1088 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1089 CK_FloatingRealToComplex);
1090
1091 return result;
1092}
1093
1094/// Handle arithmethic conversion with floating point types. Helper
1095/// function of UsualArithmeticConversions()
1096static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1097 ExprResult &RHS, QualType LHSType,
1098 QualType RHSType, bool IsCompAssign) {
1099 bool LHSFloat = LHSType->isRealFloatingType();
1100 bool RHSFloat = RHSType->isRealFloatingType();
1101
1102 // If we have two real floating types, convert the smaller operand
1103 // to the bigger result.
1104 if (LHSFloat && RHSFloat) {
1105 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1106 if (order > 0) {
1107 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1108 return LHSType;
1109 }
1110
1111 assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast
<void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1111, __PRETTY_FUNCTION__))
;
1112 if (!IsCompAssign)
1113 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1114 return RHSType;
1115 }
1116
1117 if (LHSFloat) {
1118 // Half FP has to be promoted to float unless it is natively supported
1119 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1120 LHSType = S.Context.FloatTy;
1121
1122 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1123 /*ConvertFloat=*/!IsCompAssign,
1124 /*ConvertInt=*/ true);
1125 }
1126 assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1126, __PRETTY_FUNCTION__))
;
1127 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1128 /*convertInt=*/ true,
1129 /*convertFloat=*/!IsCompAssign);
1130}
1131
1132/// Diagnose attempts to convert between __float128 and long double if
1133/// there is no support for such conversion. Helper function of
1134/// UsualArithmeticConversions().
1135static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1136 QualType RHSType) {
1137 /* No issue converting if at least one of the types is not a floating point
1138 type or the two types have the same rank.
1139 */
1140 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1141 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1142 return false;
1143
1144 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1145, __PRETTY_FUNCTION__))
1145 "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1145, __PRETTY_FUNCTION__))
;
1146
1147 auto *LHSComplex = LHSType->getAs<ComplexType>();
1148 auto *RHSComplex = RHSType->getAs<ComplexType>();
1149
1150 QualType LHSElemType = LHSComplex ?
1151 LHSComplex->getElementType() : LHSType;
1152 QualType RHSElemType = RHSComplex ?
1153 RHSComplex->getElementType() : RHSType;
1154
1155 // No issue if the two types have the same representation
1156 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1157 &S.Context.getFloatTypeSemantics(RHSElemType))
1158 return false;
1159
1160 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1161 RHSElemType == S.Context.LongDoubleTy);
1162 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1163 RHSElemType == S.Context.Float128Ty);
1164
1165 // We've handled the situation where __float128 and long double have the same
1166 // representation. We allow all conversions for all possible long double types
1167 // except PPC's double double.
1168 return Float128AndLongDouble &&
1169 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1170 &llvm::APFloat::PPCDoubleDouble());
1171}
1172
1173typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1174
1175namespace {
1176/// These helper callbacks are placed in an anonymous namespace to
1177/// permit their use as function template parameters.
1178ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1179 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1180}
1181
1182ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1183 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1184 CK_IntegralComplexCast);
1185}
1186}
1187
1188/// Handle integer arithmetic conversions. Helper function of
1189/// UsualArithmeticConversions()
1190template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1191static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1192 ExprResult &RHS, QualType LHSType,
1193 QualType RHSType, bool IsCompAssign) {
1194 // The rules for this case are in C99 6.3.1.8
1195 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1196 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1197 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1198 if (LHSSigned == RHSSigned) {
1199 // Same signedness; use the higher-ranked type
1200 if (order >= 0) {
1201 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1202 return LHSType;
1203 } else if (!IsCompAssign)
1204 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1205 return RHSType;
1206 } else if (order != (LHSSigned ? 1 : -1)) {
1207 // The unsigned type has greater than or equal rank to the
1208 // signed type, so use the unsigned type
1209 if (RHSSigned) {
1210 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1211 return LHSType;
1212 } else if (!IsCompAssign)
1213 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1214 return RHSType;
1215 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1216 // The two types are different widths; if we are here, that
1217 // means the signed type is larger than the unsigned type, so
1218 // use the signed type.
1219 if (LHSSigned) {
1220 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1221 return LHSType;
1222 } else if (!IsCompAssign)
1223 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1224 return RHSType;
1225 } else {
1226 // The signed type is higher-ranked than the unsigned type,
1227 // but isn't actually any bigger (like unsigned int and long
1228 // on most 32-bit systems). Use the unsigned type corresponding
1229 // to the signed type.
1230 QualType result =
1231 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1232 RHS = (*doRHSCast)(S, RHS.get(), result);
1233 if (!IsCompAssign)
1234 LHS = (*doLHSCast)(S, LHS.get(), result);
1235 return result;
1236 }
1237}
1238
1239/// Handle conversions with GCC complex int extension. Helper function
1240/// of UsualArithmeticConversions()
1241static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1242 ExprResult &RHS, QualType LHSType,
1243 QualType RHSType,
1244 bool IsCompAssign) {
1245 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1246 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1247
1248 if (LHSComplexInt && RHSComplexInt) {
1249 QualType LHSEltType = LHSComplexInt->getElementType();
1250 QualType RHSEltType = RHSComplexInt->getElementType();
1251 QualType ScalarType =
1252 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1253 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1254
1255 return S.Context.getComplexType(ScalarType);
1256 }
1257
1258 if (LHSComplexInt) {
1259 QualType LHSEltType = LHSComplexInt->getElementType();
1260 QualType ScalarType =
1261 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1262 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1263 QualType ComplexType = S.Context.getComplexType(ScalarType);
1264 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1265 CK_IntegralRealToComplex);
1266
1267 return ComplexType;
1268 }
1269
1270 assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail
("RHSComplexInt", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1270, __PRETTY_FUNCTION__))
;
1271
1272 QualType RHSEltType = RHSComplexInt->getElementType();
1273 QualType ScalarType =
1274 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1275 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1276 QualType ComplexType = S.Context.getComplexType(ScalarType);
1277
1278 if (!IsCompAssign)
1279 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1280 CK_IntegralRealToComplex);
1281 return ComplexType;
1282}
1283
1284/// Return the rank of a given fixed point or integer type. The value itself
1285/// doesn't matter, but the values must be increasing with proper increasing
1286/// rank as described in N1169 4.1.1.
1287static unsigned GetFixedPointRank(QualType Ty) {
1288 const auto *BTy = Ty->getAs<BuiltinType>();
1289 assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast<
void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1289, __PRETTY_FUNCTION__))
;
1290
1291 switch (BTy->getKind()) {
1292 case BuiltinType::ShortFract:
1293 case BuiltinType::UShortFract:
1294 case BuiltinType::SatShortFract:
1295 case BuiltinType::SatUShortFract:
1296 return 1;
1297 case BuiltinType::Fract:
1298 case BuiltinType::UFract:
1299 case BuiltinType::SatFract:
1300 case BuiltinType::SatUFract:
1301 return 2;
1302 case BuiltinType::LongFract:
1303 case BuiltinType::ULongFract:
1304 case BuiltinType::SatLongFract:
1305 case BuiltinType::SatULongFract:
1306 return 3;
1307 case BuiltinType::ShortAccum:
1308 case BuiltinType::UShortAccum:
1309 case BuiltinType::SatShortAccum:
1310 case BuiltinType::SatUShortAccum:
1311 return 4;
1312 case BuiltinType::Accum:
1313 case BuiltinType::UAccum:
1314 case BuiltinType::SatAccum:
1315 case BuiltinType::SatUAccum:
1316 return 5;
1317 case BuiltinType::LongAccum:
1318 case BuiltinType::ULongAccum:
1319 case BuiltinType::SatLongAccum:
1320 case BuiltinType::SatULongAccum:
1321 return 6;
1322 default:
1323 if (BTy->isInteger())
1324 return 0;
1325 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1325)
;
1326 }
1327}
1328
1329/// handleFixedPointConversion - Fixed point operations between fixed
1330/// point types and integers or other fixed point types do not fall under
1331/// usual arithmetic conversion since these conversions could result in loss
1332/// of precsision (N1169 4.1.4). These operations should be calculated with
1333/// the full precision of their result type (N1169 4.1.6.2.1).
1334static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1335 QualType RHSTy) {
1336 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1337, __PRETTY_FUNCTION__))
1337 "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1337, __PRETTY_FUNCTION__))
;
1338 assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1341, __PRETTY_FUNCTION__))
1339 RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1341, __PRETTY_FUNCTION__))
1340 "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1341, __PRETTY_FUNCTION__))
1341 "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1341, __PRETTY_FUNCTION__))
;
1342
1343 // If one operand has signed fixed-point type and the other operand has
1344 // unsigned fixed-point type, then the unsigned fixed-point operand is
1345 // converted to its corresponding signed fixed-point type and the resulting
1346 // type is the type of the converted operand.
1347 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1348 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1349 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1350 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1351
1352 // The result type is the type with the highest rank, whereby a fixed-point
1353 // conversion rank is always greater than an integer conversion rank; if the
1354 // type of either of the operands is a saturating fixedpoint type, the result
1355 // type shall be the saturating fixed-point type corresponding to the type
1356 // with the highest rank; the resulting value is converted (taking into
1357 // account rounding and overflow) to the precision of the resulting type.
1358 // Same ranks between signed and unsigned types are resolved earlier, so both
1359 // types are either signed or both unsigned at this point.
1360 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1361 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1362
1363 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1364
1365 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1366 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1367
1368 return ResultTy;
1369}
1370
1371/// Check that the usual arithmetic conversions can be performed on this pair of
1372/// expressions that might be of enumeration type.
1373static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1374 SourceLocation Loc,
1375 Sema::ArithConvKind ACK) {
1376 // C++2a [expr.arith.conv]p1:
1377 // If one operand is of enumeration type and the other operand is of a
1378 // different enumeration type or a floating-point type, this behavior is
1379 // deprecated ([depr.arith.conv.enum]).
1380 //
1381 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1382 // Eventually we will presumably reject these cases (in C++23 onwards?).
1383 QualType L = LHS->getType(), R = RHS->getType();
1384 bool LEnum = L->isUnscopedEnumerationType(),
1385 REnum = R->isUnscopedEnumerationType();
1386 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1387 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1388 (REnum && L->isFloatingType())) {
1389 S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1390 ? diag::warn_arith_conv_enum_float_cxx2a
1391 : diag::warn_arith_conv_enum_float)
1392 << LHS->getSourceRange() << RHS->getSourceRange()
1393 << (int)ACK << LEnum << L << R;
1394 } else if (!IsCompAssign && LEnum && REnum &&
1395 !S.Context.hasSameUnqualifiedType(L, R)) {
1396 unsigned DiagID;
1397 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1398 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1399 // If either enumeration type is unnamed, it's less likely that the
1400 // user cares about this, but this situation is still deprecated in
1401 // C++2a. Use a different warning group.
1402 DiagID = S.getLangOpts().CPlusPlus2a
1403 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1404 : diag::warn_arith_conv_mixed_anon_enum_types;
1405 } else if (ACK == Sema::ACK_Conditional) {
1406 // Conditional expressions are separated out because they have
1407 // historically had a different warning flag.
1408 DiagID = S.getLangOpts().CPlusPlus2a
1409 ? diag::warn_conditional_mixed_enum_types_cxx2a
1410 : diag::warn_conditional_mixed_enum_types;
1411 } else if (ACK == Sema::ACK_Comparison) {
1412 // Comparison expressions are separated out because they have
1413 // historically had a different warning flag.
1414 DiagID = S.getLangOpts().CPlusPlus2a
1415 ? diag::warn_comparison_mixed_enum_types_cxx2a
1416 : diag::warn_comparison_mixed_enum_types;
1417 } else {
1418 DiagID = S.getLangOpts().CPlusPlus2a
1419 ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1420 : diag::warn_arith_conv_mixed_enum_types;
1421 }
1422 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1423 << (int)ACK << L << R;
1424 }
1425}
1426
1427/// UsualArithmeticConversions - Performs various conversions that are common to
1428/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1429/// routine returns the first non-arithmetic type found. The client is
1430/// responsible for emitting appropriate error diagnostics.
1431QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1432 SourceLocation Loc,
1433 ArithConvKind ACK) {
1434 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1435
1436 if (ACK != ACK_CompAssign) {
1437 LHS = UsualUnaryConversions(LHS.get());
1438 if (LHS.isInvalid())
1439 return QualType();
1440 }
1441
1442 RHS = UsualUnaryConversions(RHS.get());
1443 if (RHS.isInvalid())
1444 return QualType();
1445
1446 // For conversion purposes, we ignore any qualifiers.
1447 // For example, "const float" and "float" are equivalent.
1448 QualType LHSType =
1449 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1450 QualType RHSType =
1451 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1452
1453 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1454 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1455 LHSType = AtomicLHS->getValueType();
1456
1457 // If both types are identical, no conversion is needed.
1458 if (LHSType == RHSType)
1459 return LHSType;
1460
1461 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1462 // The caller can deal with this (e.g. pointer + int).
1463 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1464 return QualType();
1465
1466 // Apply unary and bitfield promotions to the LHS's type.
1467 QualType LHSUnpromotedType = LHSType;
1468 if (LHSType->isPromotableIntegerType())
1469 LHSType = Context.getPromotedIntegerType(LHSType);
1470 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1471 if (!LHSBitfieldPromoteTy.isNull())
1472 LHSType = LHSBitfieldPromoteTy;
1473 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1474 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1475
1476 // If both types are identical, no conversion is needed.
1477 if (LHSType == RHSType)
1478 return LHSType;
1479
1480 // At this point, we have two different arithmetic types.
1481
1482 // Diagnose attempts to convert between __float128 and long double where
1483 // such conversions currently can't be handled.
1484 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1485 return QualType();
1486
1487 // Handle complex types first (C99 6.3.1.8p1).
1488 if (LHSType->isComplexType() || RHSType->isComplexType())
1489 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1490 ACK == ACK_CompAssign);
1491
1492 // Now handle "real" floating types (i.e. float, double, long double).
1493 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1494 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1495 ACK == ACK_CompAssign);
1496
1497 // Handle GCC complex int extension.
1498 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1499 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1500 ACK == ACK_CompAssign);
1501
1502 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1503 return handleFixedPointConversion(*this, LHSType, RHSType);
1504
1505 // Finally, we have two differing integer types.
1506 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1507 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1508}
1509
1510//===----------------------------------------------------------------------===//
1511// Semantic Analysis for various Expression Types
1512//===----------------------------------------------------------------------===//
1513
1514
1515ExprResult
1516Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1517 SourceLocation DefaultLoc,
1518 SourceLocation RParenLoc,
1519 Expr *ControllingExpr,
1520 ArrayRef<ParsedType> ArgTypes,
1521 ArrayRef<Expr *> ArgExprs) {
1522 unsigned NumAssocs = ArgTypes.size();
1523 assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0)
: __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1523, __PRETTY_FUNCTION__))
;
1524
1525 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1526 for (unsigned i = 0; i < NumAssocs; ++i) {
1527 if (ArgTypes[i])
1528 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1529 else
1530 Types[i] = nullptr;
1531 }
1532
1533 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1534 ControllingExpr,
1535 llvm::makeArrayRef(Types, NumAssocs),
1536 ArgExprs);
1537 delete [] Types;
1538 return ER;
1539}
1540
1541ExprResult
1542Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1543 SourceLocation DefaultLoc,
1544 SourceLocation RParenLoc,
1545 Expr *ControllingExpr,
1546 ArrayRef<TypeSourceInfo *> Types,
1547 ArrayRef<Expr *> Exprs) {
1548 unsigned NumAssocs = Types.size();
1549 assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail
("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1549, __PRETTY_FUNCTION__))
;
1550
1551 // Decay and strip qualifiers for the controlling expression type, and handle
1552 // placeholder type replacement. See committee discussion from WG14 DR423.
1553 {
1554 EnterExpressionEvaluationContext Unevaluated(
1555 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1556 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1557 if (R.isInvalid())
1558 return ExprError();
1559 ControllingExpr = R.get();
1560 }
1561
1562 // The controlling expression is an unevaluated operand, so side effects are
1563 // likely unintended.
1564 if (!inTemplateInstantiation() &&
1565 ControllingExpr->HasSideEffects(Context, false))
1566 Diag(ControllingExpr->getExprLoc(),
1567 diag::warn_side_effects_unevaluated_context);
1568
1569 bool TypeErrorFound = false,
1570 IsResultDependent = ControllingExpr->isTypeDependent(),
1571 ContainsUnexpandedParameterPack
1572 = ControllingExpr->containsUnexpandedParameterPack();
1573
1574 for (unsigned i = 0; i < NumAssocs; ++i) {
1575 if (Exprs[i]->containsUnexpandedParameterPack())
1576 ContainsUnexpandedParameterPack = true;
1577
1578 if (Types[i]) {
1579 if (Types[i]->getType()->containsUnexpandedParameterPack())
1580 ContainsUnexpandedParameterPack = true;
1581
1582 if (Types[i]->getType()->isDependentType()) {
1583 IsResultDependent = true;
1584 } else {
1585 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1586 // complete object type other than a variably modified type."
1587 unsigned D = 0;
1588 if (Types[i]->getType()->isIncompleteType())
1589 D = diag::err_assoc_type_incomplete;
1590 else if (!Types[i]->getType()->isObjectType())
1591 D = diag::err_assoc_type_nonobject;
1592 else if (Types[i]->getType()->isVariablyModifiedType())
1593 D = diag::err_assoc_type_variably_modified;
1594
1595 if (D != 0) {
1596 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1597 << Types[i]->getTypeLoc().getSourceRange()
1598 << Types[i]->getType();
1599 TypeErrorFound = true;
1600 }
1601
1602 // C11 6.5.1.1p2 "No two generic associations in the same generic
1603 // selection shall specify compatible types."
1604 for (unsigned j = i+1; j < NumAssocs; ++j)
1605 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1606 Context.typesAreCompatible(Types[i]->getType(),
1607 Types[j]->getType())) {
1608 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1609 diag::err_assoc_compatible_types)
1610 << Types[j]->getTypeLoc().getSourceRange()
1611 << Types[j]->getType()
1612 << Types[i]->getType();
1613 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1614 diag::note_compat_assoc)
1615 << Types[i]->getTypeLoc().getSourceRange()
1616 << Types[i]->getType();
1617 TypeErrorFound = true;
1618 }
1619 }
1620 }
1621 }
1622 if (TypeErrorFound)
1623 return ExprError();
1624
1625 // If we determined that the generic selection is result-dependent, don't
1626 // try to compute the result expression.
1627 if (IsResultDependent)
1628 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1629 Exprs, DefaultLoc, RParenLoc,
1630 ContainsUnexpandedParameterPack);
1631
1632 SmallVector<unsigned, 1> CompatIndices;
1633 unsigned DefaultIndex = -1U;
1634 for (unsigned i = 0; i < NumAssocs; ++i) {
1635 if (!Types[i])
1636 DefaultIndex = i;
1637 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1638 Types[i]->getType()))
1639 CompatIndices.push_back(i);
1640 }
1641
1642 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1643 // type compatible with at most one of the types named in its generic
1644 // association list."
1645 if (CompatIndices.size() > 1) {
1646 // We strip parens here because the controlling expression is typically
1647 // parenthesized in macro definitions.
1648 ControllingExpr = ControllingExpr->IgnoreParens();
1649 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1650 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1651 << (unsigned)CompatIndices.size();
1652 for (unsigned I : CompatIndices) {
1653 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1654 diag::note_compat_assoc)
1655 << Types[I]->getTypeLoc().getSourceRange()
1656 << Types[I]->getType();
1657 }
1658 return ExprError();
1659 }
1660
1661 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1662 // its controlling expression shall have type compatible with exactly one of
1663 // the types named in its generic association list."
1664 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1665 // We strip parens here because the controlling expression is typically
1666 // parenthesized in macro definitions.
1667 ControllingExpr = ControllingExpr->IgnoreParens();
1668 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1669 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1670 return ExprError();
1671 }
1672
1673 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1674 // type name that is compatible with the type of the controlling expression,
1675 // then the result expression of the generic selection is the expression
1676 // in that generic association. Otherwise, the result expression of the
1677 // generic selection is the expression in the default generic association."
1678 unsigned ResultIndex =
1679 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1680
1681 return GenericSelectionExpr::Create(
1682 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1683 ContainsUnexpandedParameterPack, ResultIndex);
1684}
1685
1686/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1687/// location of the token and the offset of the ud-suffix within it.
1688static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1689 unsigned Offset) {
1690 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1691 S.getLangOpts());
1692}
1693
1694/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1695/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1696static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1697 IdentifierInfo *UDSuffix,
1698 SourceLocation UDSuffixLoc,
1699 ArrayRef<Expr*> Args,
1700 SourceLocation LitEndLoc) {
1701 assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator"
) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1701, __PRETTY_FUNCTION__))
;
1702
1703 QualType ArgTy[2];
1704 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1705 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1706 if (ArgTy[ArgIdx]->isArrayType())
1707 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1708 }
1709
1710 DeclarationName OpName =
1711 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1712 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1713 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1714
1715 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1716 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1717 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1718 /*AllowStringTemplate*/ false,
1719 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1720 return ExprError();
1721
1722 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1723}
1724
1725/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1726/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1727/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1728/// multiple tokens. However, the common case is that StringToks points to one
1729/// string.
1730///
1731ExprResult
1732Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1733 assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!"
) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1733, __PRETTY_FUNCTION__))
;
1734
1735 StringLiteralParser Literal(StringToks, PP);
1736 if (Literal.hadError)
1737 return ExprError();
1738
1739 SmallVector<SourceLocation, 4> StringTokLocs;
1740 for (const Token &Tok : StringToks)
1741 StringTokLocs.push_back(Tok.getLocation());
1742
1743 QualType CharTy = Context.CharTy;
1744 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1745 if (Literal.isWide()) {
1746 CharTy = Context.getWideCharType();
1747 Kind = StringLiteral::Wide;
1748 } else if (Literal.isUTF8()) {
1749 if (getLangOpts().Char8)
1750 CharTy = Context.Char8Ty;
1751 Kind = StringLiteral::UTF8;
1752 } else if (Literal.isUTF16()) {
1753 CharTy = Context.Char16Ty;
1754 Kind = StringLiteral::UTF16;
1755 } else if (Literal.isUTF32()) {
1756 CharTy = Context.Char32Ty;
1757 Kind = StringLiteral::UTF32;
1758 } else if (Literal.isPascal()) {
1759 CharTy = Context.UnsignedCharTy;
1760 }
1761
1762 // Warn on initializing an array of char from a u8 string literal; this
1763 // becomes ill-formed in C++2a.
1764 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1765 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1766 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1767
1768 // Create removals for all 'u8' prefixes in the string literal(s). This
1769 // ensures C++2a compatibility (but may change the program behavior when
1770 // built by non-Clang compilers for which the execution character set is
1771 // not always UTF-8).
1772 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1773 SourceLocation RemovalDiagLoc;
1774 for (const Token &Tok : StringToks) {
1775 if (Tok.getKind() == tok::utf8_string_literal) {
1776 if (RemovalDiagLoc.isInvalid())
1777 RemovalDiagLoc = Tok.getLocation();
1778 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1779 Tok.getLocation(),
1780 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1781 getSourceManager(), getLangOpts())));
1782 }
1783 }
1784 Diag(RemovalDiagLoc, RemovalDiag);
1785 }
1786
1787 QualType StrTy =
1788 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1789
1790 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1791 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1792 Kind, Literal.Pascal, StrTy,
1793 &StringTokLocs[0],
1794 StringTokLocs.size());
1795 if (Literal.getUDSuffix().empty())
1796 return Lit;
1797
1798 // We're building a user-defined literal.
1799 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1800 SourceLocation UDSuffixLoc =
1801 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1802 Literal.getUDSuffixOffset());
1803
1804 // Make sure we're allowed user-defined literals here.
1805 if (!UDLScope)
1806 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1807
1808 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1809 // operator "" X (str, len)
1810 QualType SizeType = Context.getSizeType();
1811
1812 DeclarationName OpName =
1813 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1814 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1815 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1816
1817 QualType ArgTy[] = {
1818 Context.getArrayDecayedType(StrTy), SizeType
1819 };
1820
1821 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1822 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1823 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1824 /*AllowStringTemplate*/ true,
1825 /*DiagnoseMissing*/ true)) {
1826
1827 case LOLR_Cooked: {
1828 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1829 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1830 StringTokLocs[0]);
1831 Expr *Args[] = { Lit, LenArg };
1832
1833 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1834 }
1835
1836 case LOLR_StringTemplate: {
1837 TemplateArgumentListInfo ExplicitArgs;
1838
1839 unsigned CharBits = Context.getIntWidth(CharTy);
1840 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1841 llvm::APSInt Value(CharBits, CharIsUnsigned);
1842
1843 TemplateArgument TypeArg(CharTy);
1844 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1845 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1846
1847 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1848 Value = Lit->getCodeUnit(I);
1849 TemplateArgument Arg(Context, Value, CharTy);
1850 TemplateArgumentLocInfo ArgInfo;
1851 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1852 }
1853 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1854 &ExplicitArgs);
1855 }
1856 case LOLR_Raw:
1857 case LOLR_Template:
1858 case LOLR_ErrorNoDiagnostic:
1859 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1859)
;
1860 case LOLR_Error:
1861 return ExprError();
1862 }
1863 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1863)
;
1864}
1865
1866DeclRefExpr *
1867Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1868 SourceLocation Loc,
1869 const CXXScopeSpec *SS) {
1870 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1871 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1872}
1873
1874DeclRefExpr *
1875Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1876 const DeclarationNameInfo &NameInfo,
1877 const CXXScopeSpec *SS, NamedDecl *FoundD,
1878 SourceLocation TemplateKWLoc,
1879 const TemplateArgumentListInfo *TemplateArgs) {
1880 NestedNameSpecifierLoc NNS =
1881 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1882 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1883 TemplateArgs);
1884}
1885
1886NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1887 // A declaration named in an unevaluated operand never constitutes an odr-use.
1888 if (isUnevaluatedContext())
1889 return NOUR_Unevaluated;
1890
1891 // C++2a [basic.def.odr]p4:
1892 // A variable x whose name appears as a potentially-evaluated expression e
1893 // is odr-used by e unless [...] x is a reference that is usable in
1894 // constant expressions.
1895 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1896 if (VD->getType()->isReferenceType() &&
1897 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1898 VD->isUsableInConstantExpressions(Context))
1899 return NOUR_Constant;
1900 }
1901
1902 // All remaining non-variable cases constitute an odr-use. For variables, we
1903 // need to wait and see how the expression is used.
1904 return NOUR_None;
1905}
1906
1907/// BuildDeclRefExpr - Build an expression that references a
1908/// declaration that does not require a closure capture.
1909DeclRefExpr *
1910Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1911 const DeclarationNameInfo &NameInfo,
1912 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1913 SourceLocation TemplateKWLoc,
1914 const TemplateArgumentListInfo *TemplateArgs) {
1915 bool RefersToCapturedVariable =
1916 isa<VarDecl>(D) &&
1917 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1918
1919 DeclRefExpr *E = DeclRefExpr::Create(
1920 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1921 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1922 MarkDeclRefReferenced(E);
1923
1924 // C++ [except.spec]p17:
1925 // An exception-specification is considered to be needed when:
1926 // - in an expression, the function is the unique lookup result or
1927 // the selected member of a set of overloaded functions.
1928 //
1929 // We delay doing this until after we've built the function reference and
1930 // marked it as used so that:
1931 // a) if the function is defaulted, we get errors from defining it before /
1932 // instead of errors from computing its exception specification, and
1933 // b) if the function is a defaulted comparison, we can use the body we
1934 // build when defining it as input to the exception specification
1935 // computation rather than computing a new body.
1936 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1937 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1938 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1939 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1940 }
1941 }
1942
1943 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1944 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1945 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1946 getCurFunction()->recordUseOfWeak(E);
1947
1948 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1949 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1950 FD = IFD->getAnonField();
1951 if (FD) {
1952 UnusedPrivateFields.remove(FD);
1953 // Just in case we're building an illegal pointer-to-member.
1954 if (FD->isBitField())
1955 E->setObjectKind(OK_BitField);
1956 }
1957
1958 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1959 // designates a bit-field.
1960 if (auto *BD = dyn_cast<BindingDecl>(D))
1961 if (auto *BE = BD->getBinding())
1962 E->setObjectKind(BE->getObjectKind());
1963
1964 return E;
1965}
1966
1967/// Decomposes the given name into a DeclarationNameInfo, its location, and
1968/// possibly a list of template arguments.
1969///
1970/// If this produces template arguments, it is permitted to call
1971/// DecomposeTemplateName.
1972///
1973/// This actually loses a lot of source location information for
1974/// non-standard name kinds; we should consider preserving that in
1975/// some way.
1976void
1977Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1978 TemplateArgumentListInfo &Buffer,
1979 DeclarationNameInfo &NameInfo,
1980 const TemplateArgumentListInfo *&TemplateArgs) {
1981 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1982 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1983 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1984
1985 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1986 Id.TemplateId->NumArgs);
1987 translateTemplateArguments(TemplateArgsPtr, Buffer);
1988
1989 TemplateName TName = Id.TemplateId->Template.get();
1990 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1991 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1992 TemplateArgs = &Buffer;
1993 } else {
1994 NameInfo = GetNameFromUnqualifiedId(Id);
1995 TemplateArgs = nullptr;
1996 }
1997}
1998
1999static void emitEmptyLookupTypoDiagnostic(
2000 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2001 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2002 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2003 DeclContext *Ctx =
2004 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2005 if (!TC) {
2006 // Emit a special diagnostic for failed member lookups.
2007 // FIXME: computing the declaration context might fail here (?)
2008 if (Ctx)
2009 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2010 << SS.getRange();
2011 else
2012 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2013 return;
2014 }
2015
2016 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2017 bool DroppedSpecifier =
2018 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2019 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2020 ? diag::note_implicit_param_decl
2021 : diag::note_previous_decl;
2022 if (!Ctx)
2023 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2024 SemaRef.PDiag(NoteID));
2025 else
2026 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2027 << Typo << Ctx << DroppedSpecifier
2028 << SS.getRange(),
2029 SemaRef.PDiag(NoteID));
2030}
2031
2032/// Diagnose an empty lookup.
2033///
2034/// \return false if new lookup candidates were found
2035bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2036 CorrectionCandidateCallback &CCC,
2037 TemplateArgumentListInfo *ExplicitTemplateArgs,
2038 ArrayRef<Expr *> Args, TypoExpr **Out) {
2039 DeclarationName Name = R.getLookupName();
2040
2041 unsigned diagnostic = diag::err_undeclared_var_use;
2042 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2043 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2044 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2045 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2046 diagnostic = diag::err_undeclared_use;
2047 diagnostic_suggest = diag::err_undeclared_use_suggest;
2048 }
2049
2050 // If the original lookup was an unqualified lookup, fake an
2051 // unqualified lookup. This is useful when (for example) the
2052 // original lookup would not have found something because it was a
2053 // dependent name.
2054 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2055 while (DC) {
2056 if (isa<CXXRecordDecl>(DC)) {
2057 LookupQualifiedName(R, DC);
2058
2059 if (!R.empty()) {
2060 // Don't give errors about ambiguities in this lookup.
2061 R.suppressDiagnostics();
2062
2063 // During a default argument instantiation the CurContext points
2064 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2065 // function parameter list, hence add an explicit check.
2066 bool isDefaultArgument =
2067 !CodeSynthesisContexts.empty() &&
2068 CodeSynthesisContexts.back().Kind ==
2069 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2070 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2071 bool isInstance = CurMethod &&
2072 CurMethod->isInstance() &&
2073 DC == CurMethod->getParent() && !isDefaultArgument;
2074
2075 // Give a code modification hint to insert 'this->'.
2076 // TODO: fixit for inserting 'Base<T>::' in the other cases.
2077 // Actually quite difficult!
2078 if (getLangOpts().MSVCCompat)
2079 diagnostic = diag::ext_found_via_dependent_bases_lookup;
2080 if (isInstance) {
2081 Diag(R.getNameLoc(), diagnostic) << Name
2082 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2083 CheckCXXThisCapture(R.getNameLoc());
2084 } else {
2085 Diag(R.getNameLoc(), diagnostic) << Name;
2086 }
2087
2088 // Do we really want to note all of these?
2089 for (NamedDecl *D : R)
2090 Diag(D->getLocation(), diag::note_dependent_var_use);
2091
2092 // Return true if we are inside a default argument instantiation
2093 // and the found name refers to an instance member function, otherwise
2094 // the function calling DiagnoseEmptyLookup will try to create an
2095 // implicit member call and this is wrong for default argument.
2096 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2097 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2098 return true;
2099 }
2100
2101 // Tell the callee to try to recover.
2102 return false;
2103 }
2104
2105 R.clear();
2106 }
2107
2108 DC = DC->getLookupParent();
2109 }
2110
2111 // We didn't find anything, so try to correct for a typo.
2112 TypoCorrection Corrected;
2113 if (S && Out) {
2114 SourceLocation TypoLoc = R.getNameLoc();
2115 assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2116, __PRETTY_FUNCTION__))
2116 "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2116, __PRETTY_FUNCTION__))
;
2117 *Out = CorrectTypoDelayed(
2118 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2119 [=](const TypoCorrection &TC) {
2120 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2121 diagnostic, diagnostic_suggest);
2122 },
2123 nullptr, CTK_ErrorRecovery);
2124 if (*Out)
2125 return true;
2126 } else if (S &&
2127 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2128 S, &SS, CCC, CTK_ErrorRecovery))) {
2129 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2130 bool DroppedSpecifier =
2131 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2132 R.setLookupName(Corrected.getCorrection());
2133
2134 bool AcceptableWithRecovery = false;
2135 bool AcceptableWithoutRecovery = false;
2136 NamedDecl *ND = Corrected.getFoundDecl();
2137 if (ND) {
2138 if (Corrected.isOverloaded()) {
2139 OverloadCandidateSet OCS(R.getNameLoc(),
2140 OverloadCandidateSet::CSK_Normal);
2141 OverloadCandidateSet::iterator Best;
2142 for (NamedDecl *CD : Corrected) {
2143 if (FunctionTemplateDecl *FTD =
2144 dyn_cast<FunctionTemplateDecl>(CD))
2145 AddTemplateOverloadCandidate(
2146 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2147 Args, OCS);
2148 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2149 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2150 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2151 Args, OCS);
2152 }
2153 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2154 case OR_Success:
2155 ND = Best->FoundDecl;
2156 Corrected.setCorrectionDecl(ND);
2157 break;
2158 default:
2159 // FIXME: Arbitrarily pick the first declaration for the note.
2160 Corrected.setCorrectionDecl(ND);
2161 break;
2162 }
2163 }
2164 R.addDecl(ND);
2165 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2166 CXXRecordDecl *Record = nullptr;
2167 if (Corrected.getCorrectionSpecifier()) {
2168 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2169 Record = Ty->getAsCXXRecordDecl();
2170 }
2171 if (!Record)
2172 Record = cast<CXXRecordDecl>(
2173 ND->getDeclContext()->getRedeclContext());
2174 R.setNamingClass(Record);
2175 }
2176
2177 auto *UnderlyingND = ND->getUnderlyingDecl();
2178 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2179 isa<FunctionTemplateDecl>(UnderlyingND);
2180 // FIXME: If we ended up with a typo for a type name or
2181 // Objective-C class name, we're in trouble because the parser
2182 // is in the wrong place to recover. Suggest the typo
2183 // correction, but don't make it a fix-it since we're not going
2184 // to recover well anyway.
2185 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2186 getAsTypeTemplateDecl(UnderlyingND) ||
2187 isa<ObjCInterfaceDecl>(UnderlyingND);
2188 } else {
2189 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2190 // because we aren't able to recover.
2191 AcceptableWithoutRecovery = true;
2192 }
2193
2194 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2195 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2196 ? diag::note_implicit_param_decl
2197 : diag::note_previous_decl;
2198 if (SS.isEmpty())
2199 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2200 PDiag(NoteID), AcceptableWithRecovery);
2201 else
2202 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2203 << Name << computeDeclContext(SS, false)
2204 << DroppedSpecifier << SS.getRange(),
2205 PDiag(NoteID), AcceptableWithRecovery);
2206
2207 // Tell the callee whether to try to recover.
2208 return !AcceptableWithRecovery;
2209 }
2210 }
2211 R.clear();
2212
2213 // Emit a special diagnostic for failed member lookups.
2214 // FIXME: computing the declaration context might fail here (?)
2215 if (!SS.isEmpty()) {
2216 Diag(R.getNameLoc(), diag::err_no_member)
2217 << Name << computeDeclContext(SS, false)
2218 << SS.getRange();
2219 return true;
2220 }
2221
2222 // Give up, we can't recover.
2223 Diag(R.getNameLoc(), diagnostic) << Name;
2224 return true;
2225}
2226
2227/// In Microsoft mode, if we are inside a template class whose parent class has
2228/// dependent base classes, and we can't resolve an unqualified identifier, then
2229/// assume the identifier is a member of a dependent base class. We can only
2230/// recover successfully in static methods, instance methods, and other contexts
2231/// where 'this' is available. This doesn't precisely match MSVC's
2232/// instantiation model, but it's close enough.
2233static Expr *
2234recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2235 DeclarationNameInfo &NameInfo,
2236 SourceLocation TemplateKWLoc,
2237 const TemplateArgumentListInfo *TemplateArgs) {
2238 // Only try to recover from lookup into dependent bases in static methods or
2239 // contexts where 'this' is available.
2240 QualType ThisType = S.getCurrentThisType();
2241 const CXXRecordDecl *RD = nullptr;
2242 if (!ThisType.isNull())
2243 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2244 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2245 RD = MD->getParent();
2246 if (!RD || !RD->hasAnyDependentBases())
2247 return nullptr;
2248
2249 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2250 // is available, suggest inserting 'this->' as a fixit.
2251 SourceLocation Loc = NameInfo.getLoc();
2252 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2253 DB << NameInfo.getName() << RD;
2254
2255 if (!ThisType.isNull()) {
2256 DB << FixItHint::CreateInsertion(Loc, "this->");
2257 return CXXDependentScopeMemberExpr::Create(
2258 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2259 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2260 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2261 }
2262
2263 // Synthesize a fake NNS that points to the derived class. This will
2264 // perform name lookup during template instantiation.
2265 CXXScopeSpec SS;
2266 auto *NNS =
2267 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2268 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2269 return DependentScopeDeclRefExpr::Create(
2270 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2271 TemplateArgs);
2272}
2273
2274ExprResult
2275Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2276 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2277 bool HasTrailingLParen, bool IsAddressOfOperand,
2278 CorrectionCandidateCallback *CCC,
2279 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2280 assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2281, __PRETTY_FUNCTION__))
2281 "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2281, __PRETTY_FUNCTION__))
;
2282 if (SS.isInvalid())
2283 return ExprError();
2284
2285 TemplateArgumentListInfo TemplateArgsBuffer;
2286
2287 // Decompose the UnqualifiedId into the following data.
2288 DeclarationNameInfo NameInfo;
2289 const TemplateArgumentListInfo *TemplateArgs;
2290 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2291
2292 DeclarationName Name = NameInfo.getName();
2293 IdentifierInfo *II = Name.getAsIdentifierInfo();
2294 SourceLocation NameLoc = NameInfo.getLoc();
2295
2296 if (II && II->isEditorPlaceholder()) {
2297 // FIXME: When typed placeholders are supported we can create a typed
2298 // placeholder expression node.
2299 return ExprError();
2300 }
2301
2302 // C++ [temp.dep.expr]p3:
2303 // An id-expression is type-dependent if it contains:
2304 // -- an identifier that was declared with a dependent type,
2305 // (note: handled after lookup)
2306 // -- a template-id that is dependent,
2307 // (note: handled in BuildTemplateIdExpr)
2308 // -- a conversion-function-id that specifies a dependent type,
2309 // -- a nested-name-specifier that contains a class-name that
2310 // names a dependent type.
2311 // Determine whether this is a member of an unknown specialization;
2312 // we need to handle these differently.
2313 bool DependentID = false;
2314 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2315 Name.getCXXNameType()->isDependentType()) {
2316 DependentID = true;
2317 } else if (SS.isSet()) {
2318 if (DeclContext *DC = computeDeclContext(SS, false)) {
2319 if (RequireCompleteDeclContext(SS, DC))
2320 return ExprError();
2321 } else {
2322 DependentID = true;
2323 }
2324 }
2325
2326 if (DependentID)
2327 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2328 IsAddressOfOperand, TemplateArgs);
2329
2330 // Perform the required lookup.
2331 LookupResult R(*this, NameInfo,
2332 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2333 ? LookupObjCImplicitSelfParam
2334 : LookupOrdinaryName);
2335 if (TemplateKWLoc.isValid() || TemplateArgs) {
2336 // Lookup the template name again to correctly establish the context in
2337 // which it was found. This is really unfortunate as we already did the
2338 // lookup to determine that it was a template name in the first place. If
2339 // this becomes a performance hit, we can work harder to preserve those
2340 // results until we get here but it's likely not worth it.
2341 bool MemberOfUnknownSpecialization;
2342 AssumedTemplateKind AssumedTemplate;
2343 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2344 MemberOfUnknownSpecialization, TemplateKWLoc,
2345 &AssumedTemplate))
2346 return ExprError();
2347
2348 if (MemberOfUnknownSpecialization ||
2349 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2350 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2351 IsAddressOfOperand, TemplateArgs);
2352 } else {
2353 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2354 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2355
2356 // If the result might be in a dependent base class, this is a dependent
2357 // id-expression.
2358 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2359 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2360 IsAddressOfOperand, TemplateArgs);
2361
2362 // If this reference is in an Objective-C method, then we need to do
2363 // some special Objective-C lookup, too.
2364 if (IvarLookupFollowUp) {
2365 ExprResult E(LookupInObjCMethod(R, S, II, true));
2366 if (E.isInvalid())
2367 return ExprError();
2368
2369 if (Expr *Ex = E.getAs<Expr>())
2370 return Ex;
2371 }
2372 }
2373
2374 if (R.isAmbiguous())
2375 return ExprError();
2376
2377 // This could be an implicitly declared function reference (legal in C90,
2378 // extension in C99, forbidden in C++).
2379 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2380 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2381 if (D) R.addDecl(D);
2382 }
2383
2384 // Determine whether this name might be a candidate for
2385 // argument-dependent lookup.
2386 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2387
2388 if (R.empty() && !ADL) {
2389 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2390 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2391 TemplateKWLoc, TemplateArgs))
2392 return E;
2393 }
2394
2395 // Don't diagnose an empty lookup for inline assembly.
2396 if (IsInlineAsmIdentifier)
2397 return ExprError();
2398
2399 // If this name wasn't predeclared and if this is not a function
2400 // call, diagnose the problem.
2401 TypoExpr *TE = nullptr;
2402 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2403 : nullptr);
2404 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2405 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2406, __PRETTY_FUNCTION__))
2406 "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2406, __PRETTY_FUNCTION__))
;
2407 if (CCC) {
2408 // Make sure the callback knows what the typo being diagnosed is.
2409 CCC->setTypoName(II);
2410 if (SS.isValid())
2411 CCC->setTypoNNS(SS.getScopeRep());
2412 }
2413 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2414 // a template name, but we happen to have always already looked up the name
2415 // before we get here if it must be a template name.
2416 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2417 None, &TE)) {
2418 if (TE && KeywordReplacement) {
2419 auto &State = getTypoExprState(TE);
2420 auto BestTC = State.Consumer->getNextCorrection();
2421 if (BestTC.isKeyword()) {
2422 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2423 if (State.DiagHandler)
2424 State.DiagHandler(BestTC);
2425 KeywordReplacement->startToken();
2426 KeywordReplacement->setKind(II->getTokenID());
2427 KeywordReplacement->setIdentifierInfo(II);
2428 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2429 // Clean up the state associated with the TypoExpr, since it has
2430 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2431 clearDelayedTypo(TE);
2432 // Signal that a correction to a keyword was performed by returning a
2433 // valid-but-null ExprResult.
2434 return (Expr*)nullptr;
2435 }
2436 State.Consumer->resetCorrectionStream();
2437 }
2438 return TE ? TE : ExprError();
2439 }
2440
2441 assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2442, __PRETTY_FUNCTION__))
2442 "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2442, __PRETTY_FUNCTION__))
;
2443
2444 // If we found an Objective-C instance variable, let
2445 // LookupInObjCMethod build the appropriate expression to
2446 // reference the ivar.
2447 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2448 R.clear();
2449 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2450 // In a hopelessly buggy code, Objective-C instance variable
2451 // lookup fails and no expression will be built to reference it.
2452 if (!E.isInvalid() && !E.get())
2453 return ExprError();
2454 return E;
2455 }
2456 }
2457
2458 // This is guaranteed from this point on.
2459 assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail
("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2459, __PRETTY_FUNCTION__))
;
2460
2461 // Check whether this might be a C++ implicit instance member access.
2462 // C++ [class.mfct.non-static]p3:
2463 // When an id-expression that is not part of a class member access
2464 // syntax and not used to form a pointer to member is used in the
2465 // body of a non-static member function of class X, if name lookup
2466 // resolves the name in the id-expression to a non-static non-type
2467 // member of some class C, the id-expression is transformed into a
2468 // class member access expression using (*this) as the
2469 // postfix-expression to the left of the . operator.
2470 //
2471 // But we don't actually need to do this for '&' operands if R
2472 // resolved to a function or overloaded function set, because the
2473 // expression is ill-formed if it actually works out to be a
2474 // non-static member function:
2475 //
2476 // C++ [expr.ref]p4:
2477 // Otherwise, if E1.E2 refers to a non-static member function. . .
2478 // [t]he expression can be used only as the left-hand operand of a
2479 // member function call.
2480 //
2481 // There are other safeguards against such uses, but it's important
2482 // to get this right here so that we don't end up making a
2483 // spuriously dependent expression if we're inside a dependent
2484 // instance method.
2485 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2486 bool MightBeImplicitMember;
2487 if (!IsAddressOfOperand)
2488 MightBeImplicitMember = true;
2489 else if (!SS.isEmpty())
2490 MightBeImplicitMember = false;
2491 else if (R.isOverloadedResult())
2492 MightBeImplicitMember = false;
2493 else if (R.isUnresolvableResult())
2494 MightBeImplicitMember = true;
2495 else
2496 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2497 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2498 isa<MSPropertyDecl>(R.getFoundDecl());
2499
2500 if (MightBeImplicitMember)
2501 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2502 R, TemplateArgs, S);
2503 }
2504
2505 if (TemplateArgs || TemplateKWLoc.isValid()) {
2506
2507 // In C++1y, if this is a variable template id, then check it
2508 // in BuildTemplateIdExpr().
2509 // The single lookup result must be a variable template declaration.
2510 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2511 Id.TemplateId->Kind == TNK_Var_template) {
2512 assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2513, __PRETTY_FUNCTION__))
2513 "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2513, __PRETTY_FUNCTION__))
;
2514 }
2515
2516 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2517 }
2518
2519 return BuildDeclarationNameExpr(SS, R, ADL);
2520}
2521
2522/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2523/// declaration name, generally during template instantiation.
2524/// There's a large number of things which don't need to be done along
2525/// this path.
2526ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2527 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2528 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2529 DeclContext *DC = computeDeclContext(SS, false);
2530 if (!DC)
2531 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2532 NameInfo, /*TemplateArgs=*/nullptr);
2533
2534 if (RequireCompleteDeclContext(SS, DC))
2535 return ExprError();
2536
2537 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2538 LookupQualifiedName(R, DC);
2539
2540 if (R.isAmbiguous())
2541 return ExprError();
2542
2543 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2544 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2545 NameInfo, /*TemplateArgs=*/nullptr);
2546
2547 if (R.empty()) {
2548 Diag(NameInfo.getLoc(), diag::err_no_member)
2549 << NameInfo.getName() << DC << SS.getRange();
2550 return ExprError();
2551 }
2552
2553 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2554 // Diagnose a missing typename if this resolved unambiguously to a type in
2555 // a dependent context. If we can recover with a type, downgrade this to
2556 // a warning in Microsoft compatibility mode.
2557 unsigned DiagID = diag::err_typename_missing;
2558 if (RecoveryTSI && getLangOpts().MSVCCompat)
2559 DiagID = diag::ext_typename_missing;
2560 SourceLocation Loc = SS.getBeginLoc();
2561 auto D = Diag(Loc, DiagID);
2562 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2563 << SourceRange(Loc, NameInfo.getEndLoc());
2564
2565 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2566 // context.
2567 if (!RecoveryTSI)
2568 return ExprError();
2569
2570 // Only issue the fixit if we're prepared to recover.
2571 D << FixItHint::CreateInsertion(Loc, "typename ");
2572
2573 // Recover by pretending this was an elaborated type.
2574 QualType Ty = Context.getTypeDeclType(TD);
2575 TypeLocBuilder TLB;
2576 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2577
2578 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2579 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2580 QTL.setElaboratedKeywordLoc(SourceLocation());
2581 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2582
2583 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2584
2585 return ExprEmpty();
2586 }
2587
2588 // Defend against this resolving to an implicit member access. We usually
2589 // won't get here if this might be a legitimate a class member (we end up in
2590 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2591 // a pointer-to-member or in an unevaluated context in C++11.
2592 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2593 return BuildPossibleImplicitMemberExpr(SS,
2594 /*TemplateKWLoc=*/SourceLocation(),
2595 R, /*TemplateArgs=*/nullptr, S);
2596
2597 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2598}
2599
2600/// The parser has read a name in, and Sema has detected that we're currently
2601/// inside an ObjC method. Perform some additional checks and determine if we
2602/// should form a reference to an ivar.
2603///
2604/// Ideally, most of this would be done by lookup, but there's
2605/// actually quite a lot of extra work involved.
2606DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2607 IdentifierInfo *II) {
2608 SourceLocation Loc = Lookup.getNameLoc();
2609 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2610
2611 // Check for error condition which is already reported.
2612 if (!CurMethod)
2613 return DeclResult(true);
2614
2615 // There are two cases to handle here. 1) scoped lookup could have failed,
2616 // in which case we should look for an ivar. 2) scoped lookup could have
2617 // found a decl, but that decl is outside the current instance method (i.e.
2618 // a global variable). In these two cases, we do a lookup for an ivar with
2619 // this name, if the lookup sucedes, we replace it our current decl.
2620
2621 // If we're in a class method, we don't normally want to look for
2622 // ivars. But if we don't find anything else, and there's an
2623 // ivar, that's an error.
2624 bool IsClassMethod = CurMethod->isClassMethod();
2625
2626 bool LookForIvars;
2627 if (Lookup.empty())
2628 LookForIvars = true;
2629 else if (IsClassMethod)
2630 LookForIvars = false;
2631 else
2632 LookForIvars = (Lookup.isSingleResult() &&
2633 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2634 ObjCInterfaceDecl *IFace = nullptr;
2635 if (LookForIvars) {
2636 IFace = CurMethod->getClassInterface();
2637 ObjCInterfaceDecl *ClassDeclared;
2638 ObjCIvarDecl *IV = nullptr;
2639 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2640 // Diagnose using an ivar in a class method.
2641 if (IsClassMethod) {
2642 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2643 return DeclResult(true);
2644 }
2645
2646 // Diagnose the use of an ivar outside of the declaring class.
2647 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2648 !declaresSameEntity(ClassDeclared, IFace) &&
2649 !getLangOpts().DebuggerSupport)
2650 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2651
2652 // Success.
2653 return IV;
2654 }
2655 } else if (CurMethod->isInstanceMethod()) {
2656 // We should warn if a local variable hides an ivar.
2657 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2658 ObjCInterfaceDecl *ClassDeclared;
2659 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2660 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2661 declaresSameEntity(IFace, ClassDeclared))
2662 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2663 }
2664 }
2665 } else if (Lookup.isSingleResult() &&
2666 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2667 // If accessing a stand-alone ivar in a class method, this is an error.
2668 if (const ObjCIvarDecl *IV =
2669 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2670 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2671 return DeclResult(true);
2672 }
2673 }
2674
2675 // Didn't encounter an error, didn't find an ivar.
2676 return DeclResult(false);
2677}
2678
2679ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2680 ObjCIvarDecl *IV) {
2681 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2682 assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2683, __PRETTY_FUNCTION__))
2683 "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2683, __PRETTY_FUNCTION__))
;
2684
2685 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2686 assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context"
) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2686, __PRETTY_FUNCTION__))
;
2687
2688 // If we're referencing an invalid decl, just return this as a silent
2689 // error node. The error diagnostic was already emitted on the decl.
2690 if (IV->isInvalidDecl())
2691 return ExprError();
2692
2693 // Check if referencing a field with __attribute__((deprecated)).
2694 if (DiagnoseUseOfDecl(IV, Loc))
2695 return ExprError();
2696
2697 // FIXME: This should use a new expr for a direct reference, don't
2698 // turn this into Self->ivar, just return a BareIVarExpr or something.
2699 IdentifierInfo &II = Context.Idents.get("self");
2700 UnqualifiedId SelfName;
2701 SelfName.setIdentifier(&II, SourceLocation());
2702 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2703 CXXScopeSpec SelfScopeSpec;
2704 SourceLocation TemplateKWLoc;
2705 ExprResult SelfExpr =
2706 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2707 /*HasTrailingLParen=*/false,
2708 /*IsAddressOfOperand=*/false);
2709 if (SelfExpr.isInvalid())
2710 return ExprError();
2711
2712 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2713 if (SelfExpr.isInvalid())
2714 return ExprError();
2715
2716 MarkAnyDeclReferenced(Loc, IV, true);
2717
2718 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2719 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2720 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2721 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2722
2723 ObjCIvarRefExpr *Result = new (Context)
2724 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2725 IV->getLocation(), SelfExpr.get(), true, true);
2726
2727 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2728 if (!isUnevaluatedContext() &&
2729 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2730 getCurFunction()->recordUseOfWeak(Result);
2731 }
2732 if (getLangOpts().ObjCAutoRefCount)
2733 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2734 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2735
2736 return Result;
2737}
2738
2739/// The parser has read a name in, and Sema has detected that we're currently
2740/// inside an ObjC method. Perform some additional checks and determine if we
2741/// should form a reference to an ivar. If so, build an expression referencing
2742/// that ivar.
2743ExprResult
2744Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2745 IdentifierInfo *II, bool AllowBuiltinCreation) {
2746 // FIXME: Integrate this lookup step into LookupParsedName.
2747 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2748 if (Ivar.isInvalid())
2749 return ExprError();
2750 if (Ivar.isUsable())
2751 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2752 cast<ObjCIvarDecl>(Ivar.get()));
2753
2754 if (Lookup.empty() && II && AllowBuiltinCreation)
2755 LookupBuiltin(Lookup);
2756
2757 // Sentinel value saying that we didn't do anything special.
2758 return ExprResult(false);
2759}
2760
2761/// Cast a base object to a member's actual type.
2762///
2763/// Logically this happens in three phases:
2764///
2765/// * First we cast from the base type to the naming class.
2766/// The naming class is the class into which we were looking
2767/// when we found the member; it's the qualifier type if a
2768/// qualifier was provided, and otherwise it's the base type.
2769///
2770/// * Next we cast from the naming class to the declaring class.
2771/// If the member we found was brought into a class's scope by
2772/// a using declaration, this is that class; otherwise it's
2773/// the class declaring the member.
2774///
2775/// * Finally we cast from the declaring class to the "true"
2776/// declaring class of the member. This conversion does not
2777/// obey access control.
2778ExprResult
2779Sema::PerformObjectMemberConversion(Expr *From,
2780 NestedNameSpecifier *Qualifier,
2781 NamedDecl *FoundDecl,
2782 NamedDecl *Member) {
2783 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2784 if (!RD)
2785 return From;
2786
2787 QualType DestRecordType;
2788 QualType DestType;
2789 QualType FromRecordType;
2790 QualType FromType = From->getType();
2791 bool PointerConversions = false;
2792 if (isa<FieldDecl>(Member)) {
2793 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2794 auto FromPtrType = FromType->getAs<PointerType>();
2795 DestRecordType = Context.getAddrSpaceQualType(
2796 DestRecordType, FromPtrType
2797 ? FromType->getPointeeType().getAddressSpace()
2798 : FromType.getAddressSpace());
2799
2800 if (FromPtrType) {
2801 DestType = Context.getPointerType(DestRecordType);
2802 FromRecordType = FromPtrType->getPointeeType();
2803 PointerConversions = true;
2804 } else {
2805 DestType = DestRecordType;
2806 FromRecordType = FromType;
2807 }
2808 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2809 if (Method->isStatic())
2810 return From;
2811
2812 DestType = Method->getThisType();
2813 DestRecordType = DestType->getPointeeType();
2814
2815 if (FromType->getAs<PointerType>()) {
2816 FromRecordType = FromType->getPointeeType();
2817 PointerConversions = true;
2818 } else {
2819 FromRecordType = FromType;
2820 DestType = DestRecordType;
2821 }
2822
2823 LangAS FromAS = FromRecordType.getAddressSpace();
2824 LangAS DestAS = DestRecordType.getAddressSpace();
2825 if (FromAS != DestAS) {
2826 QualType FromRecordTypeWithoutAS =
2827 Context.removeAddrSpaceQualType(FromRecordType);
2828 QualType FromTypeWithDestAS =
2829 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2830 if (PointerConversions)
2831 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2832 From = ImpCastExprToType(From, FromTypeWithDestAS,
2833 CK_AddressSpaceConversion, From->getValueKind())
2834 .get();
2835 }
2836 } else {
2837 // No conversion necessary.
2838 return From;
2839 }
2840
2841 if (DestType->isDependentType() || FromType->isDependentType())
2842 return From;
2843
2844 // If the unqualified types are the same, no conversion is necessary.
2845 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2846 return From;
2847
2848 SourceRange FromRange = From->getSourceRange();
2849 SourceLocation FromLoc = FromRange.getBegin();
2850
2851 ExprValueKind VK = From->getValueKind();
2852
2853 // C++ [class.member.lookup]p8:
2854 // [...] Ambiguities can often be resolved by qualifying a name with its
2855 // class name.
2856 //
2857 // If the member was a qualified name and the qualified referred to a
2858 // specific base subobject type, we'll cast to that intermediate type
2859 // first and then to the object in which the member is declared. That allows
2860 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2861 //
2862 // class Base { public: int x; };
2863 // class Derived1 : public Base { };
2864 // class Derived2 : public Base { };
2865 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2866 //
2867 // void VeryDerived::f() {
2868 // x = 17; // error: ambiguous base subobjects
2869 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2870 // }
2871 if (Qualifier && Qualifier->getAsType()) {
2872 QualType QType = QualType(Qualifier->getAsType(), 0);
2873 assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type"
) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2873, __PRETTY_FUNCTION__))
;
2874
2875 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2876
2877 // In C++98, the qualifier type doesn't actually have to be a base
2878 // type of the object type, in which case we just ignore it.
2879 // Otherwise build the appropriate casts.
2880 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2881 CXXCastPath BasePath;
2882 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2883 FromLoc, FromRange, &BasePath))
2884 return ExprError();
2885
2886 if (PointerConversions)
2887 QType = Context.getPointerType(QType);
2888 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2889 VK, &BasePath).get();
2890
2891 FromType = QType;
2892 FromRecordType = QRecordType;
2893
2894 // If the qualifier type was the same as the destination type,
2895 // we're done.
2896 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2897 return From;
2898 }
2899 }
2900
2901 bool IgnoreAccess = false;
2902
2903 // If we actually found the member through a using declaration, cast
2904 // down to the using declaration's type.
2905 //
2906 // Pointer equality is fine here because only one declaration of a
2907 // class ever has member declarations.
2908 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2909 assert(isa<UsingShadowDecl>(FoundDecl))((isa<UsingShadowDecl>(FoundDecl)) ? static_cast<void
> (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2909, __PRETTY_FUNCTION__))
;
2910 QualType URecordType = Context.getTypeDeclType(
2911 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2912
2913 // We only need to do this if the naming-class to declaring-class
2914 // conversion is non-trivial.
2915 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2916 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))((IsDerivedFrom(FromLoc, FromRecordType, URecordType)) ? static_cast
<void> (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2916, __PRETTY_FUNCTION__))
;
2917 CXXCastPath BasePath;
2918 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2919 FromLoc, FromRange, &BasePath))
2920 return ExprError();
2921
2922 QualType UType = URecordType;
2923 if (PointerConversions)
2924 UType = Context.getPointerType(UType);
2925 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2926 VK, &BasePath).get();
2927 FromType = UType;
2928 FromRecordType = URecordType;
2929 }
2930
2931 // We don't do access control for the conversion from the
2932 // declaring class to the true declaring class.
2933 IgnoreAccess = true;
2934 }
2935
2936 CXXCastPath BasePath;
2937 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2938 FromLoc, FromRange, &BasePath,
2939 IgnoreAccess))
2940 return ExprError();
2941
2942 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2943 VK, &BasePath);
2944}
2945
2946bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2947 const LookupResult &R,
2948 bool HasTrailingLParen) {
2949 // Only when used directly as the postfix-expression of a call.
2950 if (!HasTrailingLParen)
2951 return false;
2952
2953 // Never if a scope specifier was provided.
2954 if (SS.isSet())
2955 return false;
2956
2957 // Only in C++ or ObjC++.
2958 if (!getLangOpts().CPlusPlus)
2959 return false;
2960
2961 // Turn off ADL when we find certain kinds of declarations during
2962 // normal lookup:
2963 for (NamedDecl *D : R) {
2964 // C++0x [basic.lookup.argdep]p3:
2965 // -- a declaration of a class member
2966 // Since using decls preserve this property, we check this on the
2967 // original decl.
2968 if (D->isCXXClassMember())
2969 return false;
2970
2971 // C++0x [basic.lookup.argdep]p3:
2972 // -- a block-scope function declaration that is not a
2973 // using-declaration
2974 // NOTE: we also trigger this for function templates (in fact, we
2975 // don't check the decl type at all, since all other decl types
2976 // turn off ADL anyway).
2977 if (isa<UsingShadowDecl>(D))
2978 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2979 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2980 return false;
2981
2982 // C++0x [basic.lookup.argdep]p3:
2983 // -- a declaration that is neither a function or a function
2984 // template
2985 // And also for builtin functions.
2986 if (isa<FunctionDecl>(D)) {
2987 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2988
2989 // But also builtin functions.
2990 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2991 return false;
2992 } else if (!isa<FunctionTemplateDecl>(D))
2993 return false;
2994 }
2995
2996 return true;
2997}
2998
2999
3000/// Diagnoses obvious problems with the use of the given declaration
3001/// as an expression. This is only actually called for lookups that
3002/// were not overloaded, and it doesn't promise that the declaration
3003/// will in fact be used.
3004static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3005 if (D->isInvalidDecl())
3006 return true;
3007
3008 if (isa<TypedefNameDecl>(D)) {
3009 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3010 return true;
3011 }
3012
3013 if (isa<ObjCInterfaceDecl>(D)) {
3014 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3015 return true;
3016 }
3017
3018 if (isa<NamespaceDecl>(D)) {
3019 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3020 return true;
3021 }
3022
3023 return false;
3024}
3025
3026// Certain multiversion types should be treated as overloaded even when there is
3027// only one result.
3028static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3029 assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result"
) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3029, __PRETTY_FUNCTION__))
;
3030 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3031 return FD &&
3032 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3033}
3034
3035ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3036 LookupResult &R, bool NeedsADL,
3037 bool AcceptInvalidDecl) {
3038 // If this is a single, fully-resolved result and we don't need ADL,
3039 // just build an ordinary singleton decl ref.
3040 if (!NeedsADL && R.isSingleResult() &&
3041 !R.getAsSingle<FunctionTemplateDecl>() &&
3042 !ShouldLookupResultBeMultiVersionOverload(R))
3043 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3044 R.getRepresentativeDecl(), nullptr,
3045 AcceptInvalidDecl);
3046
3047 // We only need to check the declaration if there's exactly one
3048 // result, because in the overloaded case the results can only be
3049 // functions and function templates.
3050 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3051 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3052 return ExprError();
3053
3054 // Otherwise, just build an unresolved lookup expression. Suppress
3055 // any lookup-related diagnostics; we'll hash these out later, when
3056 // we've picked a target.
3057 R.suppressDiagnostics();
3058
3059 UnresolvedLookupExpr *ULE
3060 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3061 SS.getWithLocInContext(Context),
3062 R.getLookupNameInfo(),
3063 NeedsADL, R.isOverloadedResult(),
3064 R.begin(), R.end());
3065
3066 return ULE;
3067}
3068
3069static void
3070diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3071 ValueDecl *var, DeclContext *DC);
3072
3073/// Complete semantic analysis for a reference to the given declaration.
3074ExprResult Sema::BuildDeclarationNameExpr(
3075 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3076 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3077 bool AcceptInvalidDecl) {
3078 assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast
<void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3078, __PRETTY_FUNCTION__))
;
3079 assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3080, __PRETTY_FUNCTION__))
3080 "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3080, __PRETTY_FUNCTION__))
;
3081
3082 SourceLocation Loc = NameInfo.getLoc();
3083 if (CheckDeclInExpr(*this, Loc, D))
3084 return ExprError();
3085
3086 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3087 // Specifically diagnose references to class templates that are missing
3088 // a template argument list.
3089 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3090 return ExprError();
3091 }
3092
3093 // Make sure that we're referring to a value.
3094 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3095 if (!VD) {
3096 Diag(Loc, diag::err_ref_non_value)
3097 << D << SS.getRange();
3098 Diag(D->getLocation(), diag::note_declared_at);
3099 return ExprError();
3100 }
3101
3102 // Check whether this declaration can be used. Note that we suppress
3103 // this check when we're going to perform argument-dependent lookup
3104 // on this function name, because this might not be the function
3105 // that overload resolution actually selects.
3106 if (DiagnoseUseOfDecl(VD, Loc))
3107 return ExprError();
3108
3109 // Only create DeclRefExpr's for valid Decl's.
3110 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3111 return ExprError();
3112
3113 // Handle members of anonymous structs and unions. If we got here,
3114 // and the reference is to a class member indirect field, then this
3115 // must be the subject of a pointer-to-member expression.
3116 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3117 if (!indirectField->isCXXClassMember())
3118 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3119 indirectField);
3120
3121 {
3122 QualType type = VD->getType();
3123 if (type.isNull())
3124 return ExprError();
3125 ExprValueKind valueKind = VK_RValue;
3126
3127 switch (D->getKind()) {
3128 // Ignore all the non-ValueDecl kinds.
3129#define ABSTRACT_DECL(kind)
3130#define VALUE(type, base)
3131#define DECL(type, base) \
3132 case Decl::type:
3133#include "clang/AST/DeclNodes.inc"
3134 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3134)
;
3135
3136 // These shouldn't make it here.
3137 case Decl::ObjCAtDefsField:
3138 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3138)
;
3139
3140 // Enum constants are always r-values and never references.
3141 // Unresolved using declarations are dependent.
3142 case Decl::EnumConstant:
3143 case Decl::UnresolvedUsingValue:
3144 case Decl::OMPDeclareReduction:
3145 case Decl::OMPDeclareMapper:
3146 valueKind = VK_RValue;
3147 break;
3148
3149 // Fields and indirect fields that got here must be for
3150 // pointer-to-member expressions; we just call them l-values for
3151 // internal consistency, because this subexpression doesn't really
3152 // exist in the high-level semantics.
3153 case Decl::Field:
3154 case Decl::IndirectField:
3155 case Decl::ObjCIvar:
3156 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3157, __PRETTY_FUNCTION__))
3157 "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3157, __PRETTY_FUNCTION__))
;
3158
3159 // These can't have reference type in well-formed programs, but
3160 // for internal consistency we do this anyway.
3161 type = type.getNonReferenceType();
3162 valueKind = VK_LValue;
3163 break;
3164
3165 // Non-type template parameters are either l-values or r-values
3166 // depending on the type.
3167 case Decl::NonTypeTemplateParm: {
3168 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3169 type = reftype->getPointeeType();
3170 valueKind = VK_LValue; // even if the parameter is an r-value reference
3171 break;
3172 }
3173
3174 // For non-references, we need to strip qualifiers just in case
3175 // the template parameter was declared as 'const int' or whatever.
3176 valueKind = VK_RValue;
3177 type = type.getUnqualifiedType();
3178 break;
3179 }
3180
3181 case Decl::Var:
3182 case Decl::VarTemplateSpecialization:
3183 case Decl::VarTemplatePartialSpecialization:
3184 case Decl::Decomposition:
3185 case Decl::OMPCapturedExpr:
3186 // In C, "extern void blah;" is valid and is an r-value.
3187 if (!getLangOpts().CPlusPlus &&
3188 !type.hasQualifiers() &&
3189 type->isVoidType()) {
3190 valueKind = VK_RValue;
3191 break;
3192 }
3193 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3194
3195 case Decl::ImplicitParam:
3196 case Decl::ParmVar: {
3197 // These are always l-values.
3198 valueKind = VK_LValue;
3199 type = type.getNonReferenceType();
3200
3201 // FIXME: Does the addition of const really only apply in
3202 // potentially-evaluated contexts? Since the variable isn't actually
3203 // captured in an unevaluated context, it seems that the answer is no.
3204 if (!isUnevaluatedContext()) {
3205 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3206 if (!CapturedType.isNull())
3207 type = CapturedType;
3208 }
3209
3210 break;
3211 }
3212
3213 case Decl::Binding: {
3214 // These are always lvalues.
3215 valueKind = VK_LValue;
3216 type = type.getNonReferenceType();
3217 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3218 // decides how that's supposed to work.
3219 auto *BD = cast<BindingDecl>(VD);
3220 if (BD->getDeclContext() != CurContext) {
3221 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3222 if (DD && DD->hasLocalStorage())
3223 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3224 }
3225 break;
3226 }
3227
3228 case Decl::Function: {
3229 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3230 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3231 type = Context.BuiltinFnTy;
3232 valueKind = VK_RValue;
3233 break;
3234 }
3235 }
3236
3237 const FunctionType *fty = type->castAs<FunctionType>();
3238
3239 // If we're referring to a function with an __unknown_anytype
3240 // result type, make the entire expression __unknown_anytype.
3241 if (fty->getReturnType() == Context.UnknownAnyTy) {
3242 type = Context.UnknownAnyTy;
3243 valueKind = VK_RValue;
3244 break;
3245 }
3246
3247 // Functions are l-values in C++.
3248 if (getLangOpts().CPlusPlus) {
3249 valueKind = VK_LValue;
3250 break;
3251 }
3252
3253 // C99 DR 316 says that, if a function type comes from a
3254 // function definition (without a prototype), that type is only
3255 // used for checking compatibility. Therefore, when referencing
3256 // the function, we pretend that we don't have the full function
3257 // type.
3258 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3259 isa<FunctionProtoType>(fty))
3260 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3261 fty->getExtInfo());
3262
3263 // Functions are r-values in C.
3264 valueKind = VK_RValue;
3265 break;
3266 }
3267
3268 case Decl::CXXDeductionGuide:
3269 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3269)
;
3270
3271 case Decl::MSProperty:
3272 valueKind = VK_LValue;
3273 break;
3274
3275 case Decl::CXXMethod:
3276 // If we're referring to a method with an __unknown_anytype
3277 // result type, make the entire expression __unknown_anytype.
3278 // This should only be possible with a type written directly.
3279 if (const FunctionProtoType *proto
3280 = dyn_cast<FunctionProtoType>(VD->getType()))
3281 if (proto->getReturnType() == Context.UnknownAnyTy) {
3282 type = Context.UnknownAnyTy;
3283 valueKind = VK_RValue;
3284 break;
3285 }
3286
3287 // C++ methods are l-values if static, r-values if non-static.
3288 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3289 valueKind = VK_LValue;
3290 break;
3291 }
3292 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3293
3294 case Decl::CXXConversion:
3295 case Decl::CXXDestructor:
3296 case Decl::CXXConstructor:
3297 valueKind = VK_RValue;
3298 break;
3299 }
3300
3301 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3302 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3303 TemplateArgs);
3304 }
3305}
3306
3307static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3308 SmallString<32> &Target) {
3309 Target.resize(CharByteWidth * (Source.size() + 1));
3310 char *ResultPtr = &Target[0];
3311 const llvm::UTF8 *ErrorPtr;
3312 bool success =
3313 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3314 (void)success;
3315 assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3315, __PRETTY_FUNCTION__))
;
3316 Target.resize(ResultPtr - &Target[0]);
3317}
3318
3319ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3320 PredefinedExpr::IdentKind IK) {
3321 // Pick the current block, lambda, captured statement or function.
3322 Decl *currentDecl = nullptr;
3323 if (const BlockScopeInfo *BSI = getCurBlock())
3324 currentDecl = BSI->TheDecl;
3325 else if (const LambdaScopeInfo *LSI = getCurLambda())
3326 currentDecl = LSI->CallOperator;
3327 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3328 currentDecl = CSI->TheCapturedDecl;
3329 else
3330 currentDecl = getCurFunctionOrMethodDecl();
3331
3332 if (!currentDecl) {
3333 Diag(Loc, diag::ext_predef_outside_function);
3334 currentDecl = Context.getTranslationUnitDecl();
3335 }
3336
3337 QualType ResTy;
3338 StringLiteral *SL = nullptr;
3339 if (cast<DeclContext>(currentDecl)->isDependentContext())
3340 ResTy = Context.DependentTy;
3341 else {
3342 // Pre-defined identifiers are of type char[x], where x is the length of
3343 // the string.
3344 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3345 unsigned Length = Str.length();
3346
3347 llvm::APInt LengthI(32, Length + 1);
3348 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3349 ResTy =
3350 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3351 SmallString<32> RawChars;
3352 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3353 Str, RawChars);
3354 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3355 ArrayType::Normal,
3356 /*IndexTypeQuals*/ 0);
3357 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3358 /*Pascal*/ false, ResTy, Loc);
3359 } else {
3360 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3361 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3362 ArrayType::Normal,
3363 /*IndexTypeQuals*/ 0);
3364 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3365 /*Pascal*/ false, ResTy, Loc);
3366 }
3367 }
3368
3369 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3370}
3371
3372ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3373 PredefinedExpr::IdentKind IK;
3374
3375 switch (Kind) {
3376 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3376)
;
3377 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3378 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3379 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3380 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3381 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3382 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3383 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3384 }
3385
3386 return BuildPredefinedExpr(Loc, IK);
3387}
3388
3389ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3390 SmallString<16> CharBuffer;
3391 bool Invalid = false;
3392 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3393 if (Invalid)
3394 return ExprError();
3395
3396 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3397 PP, Tok.getKind());
3398 if (Literal.hadError())
3399 return ExprError();
3400
3401 QualType Ty;
3402 if (Literal.isWide())
3403 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3404 else if (Literal.isUTF8() && getLangOpts().Char8)
3405 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3406 else if (Literal.isUTF16())
3407 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3408 else if (Literal.isUTF32())
3409 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3410 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3411 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3412 else
3413 Ty = Context.CharTy; // 'x' -> char in C++
3414
3415 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3416 if (Literal.isWide())
3417 Kind = CharacterLiteral::Wide;
3418 else if (Literal.isUTF16())
3419 Kind = CharacterLiteral::UTF16;
3420 else if (Literal.isUTF32())
3421 Kind = CharacterLiteral::UTF32;
3422 else if (Literal.isUTF8())
3423 Kind = CharacterLiteral::UTF8;
3424
3425 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3426 Tok.getLocation());
3427
3428 if (Literal.getUDSuffix().empty())
3429 return Lit;
3430
3431 // We're building a user-defined literal.
3432 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3433 SourceLocation UDSuffixLoc =
3434 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3435
3436 // Make sure we're allowed user-defined literals here.
3437 if (!UDLScope)
3438 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3439
3440 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3441 // operator "" X (ch)
3442 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3443 Lit, Tok.getLocation());
3444}
3445
3446ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3447 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3448 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3449 Context.IntTy, Loc);
3450}
3451
3452static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3453 QualType Ty, SourceLocation Loc) {
3454 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3455
3456 using llvm::APFloat;
3457 APFloat Val(Format);
3458
3459 APFloat::opStatus result = Literal.GetFloatValue(Val);
3460
3461 // Overflow is always an error, but underflow is only an error if
3462 // we underflowed to zero (APFloat reports denormals as underflow).
3463 if ((result & APFloat::opOverflow) ||
3464 ((result & APFloat::opUnderflow) && Val.isZero())) {
3465 unsigned diagnostic;
3466 SmallString<20> buffer;
3467 if (result & APFloat::opOverflow) {
3468 diagnostic = diag::warn_float_overflow;
3469 APFloat::getLargest(Format).toString(buffer);
3470 } else {
3471 diagnostic = diag::warn_float_underflow;
3472 APFloat::getSmallest(Format).toString(buffer);
3473 }
3474
3475 S.Diag(Loc, diagnostic)
3476 << Ty
3477 << StringRef(buffer.data(), buffer.size());
3478 }
3479
3480 bool isExact = (result == APFloat::opOK);
3481 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3482}
3483
3484bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3485 assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void>
(0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3485, __PRETTY_FUNCTION__))
;
3486
3487 if (E->isValueDependent())
3488 return false;
3489
3490 QualType QT = E->getType();
3491 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3492 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3493 return true;
3494 }
3495
3496 llvm::APSInt ValueAPS;
3497 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3498
3499 if (R.isInvalid())
3500 return true;
3501
3502 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3503 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3504 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3505 << ValueAPS.toString(10) << ValueIsPositive;
3506 return true;
3507 }
3508
3509 return false;
3510}
3511
3512ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3513 // Fast path for a single digit (which is quite common). A single digit
3514 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3515 if (Tok.getLength() == 1) {
3516 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3517 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3518 }
3519
3520 SmallString<128> SpellingBuffer;
3521 // NumericLiteralParser wants to overread by one character. Add padding to
3522 // the buffer in case the token is copied to the buffer. If getSpelling()
3523 // returns a StringRef to the memory buffer, it should have a null char at
3524 // the EOF, so it is also safe.
3525 SpellingBuffer.resize(Tok.getLength() + 1);
3526
3527 // Get the spelling of the token, which eliminates trigraphs, etc.
3528 bool Invalid = false;
3529 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3530 if (Invalid)
3531 return ExprError();
3532
3533 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3534 if (Literal.hadError)
3535 return ExprError();
3536
3537 if (Literal.hasUDSuffix()) {
3538 // We're building a user-defined literal.
3539 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3540 SourceLocation UDSuffixLoc =
3541 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3542
3543 // Make sure we're allowed user-defined literals here.
3544 if (!UDLScope)
3545 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3546
3547 QualType CookedTy;
3548 if (Literal.isFloatingLiteral()) {
3549 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3550 // long double, the literal is treated as a call of the form
3551 // operator "" X (f L)
3552 CookedTy = Context.LongDoubleTy;
3553 } else {
3554 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3555 // unsigned long long, the literal is treated as a call of the form
3556 // operator "" X (n ULL)
3557 CookedTy = Context.UnsignedLongLongTy;
3558 }
3559
3560 DeclarationName OpName =
3561 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3562 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3563 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3564
3565 SourceLocation TokLoc = Tok.getLocation();
3566
3567 // Perform literal operator lookup to determine if we're building a raw
3568 // literal or a cooked one.
3569 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3570 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3571 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3572 /*AllowStringTemplate*/ false,
3573 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3574 case LOLR_ErrorNoDiagnostic:
3575 // Lookup failure for imaginary constants isn't fatal, there's still the
3576 // GNU extension producing _Complex types.
3577 break;
3578 case LOLR_Error:
3579 return ExprError();
3580 case LOLR_Cooked: {
3581 Expr *Lit;
3582 if (Literal.isFloatingLiteral()) {
3583 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3584 } else {
3585 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3586 if (Literal.GetIntegerValue(ResultVal))
3587 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3588 << /* Unsigned */ 1;
3589 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3590 Tok.getLocation());
3591 }
3592 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3593 }
3594
3595 case LOLR_Raw: {
3596 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3597 // literal is treated as a call of the form
3598 // operator "" X ("n")
3599 unsigned Length = Literal.getUDSuffixOffset();
3600 QualType StrTy = Context.getConstantArrayType(
3601 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3602 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3603 Expr *Lit = StringLiteral::Create(
3604 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3605 /*Pascal*/false, StrTy, &TokLoc, 1);
3606 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3607 }
3608
3609 case LOLR_Template: {
3610 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3611 // template), L is treated as a call fo the form
3612 // operator "" X <'c1', 'c2', ... 'ck'>()
3613 // where n is the source character sequence c1 c2 ... ck.
3614 TemplateArgumentListInfo ExplicitArgs;
3615 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3616 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3617 llvm::APSInt Value(CharBits, CharIsUnsigned);
3618 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3619 Value = TokSpelling[I];
3620 TemplateArgument Arg(Context, Value, Context.CharTy);
3621 TemplateArgumentLocInfo ArgInfo;
3622 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3623 }
3624 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3625 &ExplicitArgs);
3626 }
3627 case LOLR_StringTemplate:
3628 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3628)
;
3629 }
3630 }
3631
3632 Expr *Res;
3633
3634 if (Literal.isFixedPointLiteral()) {
3635 QualType Ty;
3636
3637 if (Literal.isAccum) {
3638 if (Literal.isHalf) {
3639 Ty = Context.ShortAccumTy;
3640 } else if (Literal.isLong) {
3641 Ty = Context.LongAccumTy;
3642 } else {
3643 Ty = Context.AccumTy;
3644 }
3645 } else if (Literal.isFract) {
3646 if (Literal.isHalf) {
3647 Ty = Context.ShortFractTy;
3648 } else if (Literal.isLong) {
3649 Ty = Context.LongFractTy;
3650 } else {
3651 Ty = Context.FractTy;
3652 }
3653 }
3654
3655 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3656
3657 bool isSigned = !Literal.isUnsigned;
3658 unsigned scale = Context.getFixedPointScale(Ty);
3659 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3660
3661 llvm::APInt Val(bit_width, 0, isSigned);
3662 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3663 bool ValIsZero = Val.isNullValue() && !Overflowed;
3664
3665 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3666 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3667 // Clause 6.4.4 - The value of a constant shall be in the range of
3668 // representable values for its type, with exception for constants of a
3669 // fract type with a value of exactly 1; such a constant shall denote
3670 // the maximal value for the type.
3671 --Val;
3672 else if (Val.ugt(MaxVal) || Overflowed)
3673 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3674
3675 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3676 Tok.getLocation(), scale);
3677 } else if (Literal.isFloatingLiteral()) {
3678 QualType Ty;
3679 if (Literal.isHalf){
3680 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3681 Ty = Context.HalfTy;
3682 else {
3683 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3684 return ExprError();
3685 }
3686 } else if (Literal.isFloat)
3687 Ty = Context.FloatTy;
3688 else if (Literal.isLong)
3689 Ty = Context.LongDoubleTy;
3690 else if (Literal.isFloat16)
3691 Ty = Context.Float16Ty;
3692 else if (Literal.isFloat128)
3693 Ty = Context.Float128Ty;
3694 else
3695 Ty = Context.DoubleTy;
3696
3697 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3698
3699 if (Ty == Context.DoubleTy) {
3700 if (getLangOpts().SinglePrecisionConstants) {
3701 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3702 if (BTy->getKind() != BuiltinType::Float) {
3703 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3704 }
3705 } else if (getLangOpts().OpenCL &&
3706 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3707 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3708 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3709 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3710 }
3711 }
3712 } else if (!Literal.isIntegerLiteral()) {
3713 return ExprError();
3714 } else {
3715 QualType Ty;
3716
3717 // 'long long' is a C99 or C++11 feature.
3718 if (!getLangOpts().C99 && Literal.isLongLong) {
3719 if (getLangOpts().CPlusPlus)
3720 Diag(Tok.getLocation(),
3721 getLangOpts().CPlusPlus11 ?
3722 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3723 else
3724 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3725 }
3726
3727 // Get the value in the widest-possible width.
3728 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3729 llvm::APInt ResultVal(MaxWidth, 0);
3730
3731 if (Literal.GetIntegerValue(ResultVal)) {
3732 // If this value didn't fit into uintmax_t, error and force to ull.
3733 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3734 << /* Unsigned */ 1;
3735 Ty = Context.UnsignedLongLongTy;
3736 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3737, __PRETTY_FUNCTION__))
3737 "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3737, __PRETTY_FUNCTION__))
;
3738 } else {
3739 // If this value fits into a ULL, try to figure out what else it fits into
3740 // according to the rules of C99 6.4.4.1p5.
3741
3742 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3743 // be an unsigned int.
3744 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3745
3746 // Check from smallest to largest, picking the smallest type we can.
3747 unsigned Width = 0;
3748
3749 // Microsoft specific integer suffixes are explicitly sized.
3750 if (Literal.MicrosoftInteger) {
3751 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3752 Width = 8;
3753 Ty = Context.CharTy;
3754 } else {
3755 Width = Literal.MicrosoftInteger;
3756 Ty = Context.getIntTypeForBitwidth(Width,
3757 /*Signed=*/!Literal.isUnsigned);
3758 }
3759 }
3760
3761 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3762 // Are int/unsigned possibilities?
3763 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3764
3765 // Does it fit in a unsigned int?
3766 if (ResultVal.isIntN(IntSize)) {
3767 // Does it fit in a signed int?
3768 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3769 Ty = Context.IntTy;
3770 else if (AllowUnsigned)
3771 Ty = Context.UnsignedIntTy;
3772 Width = IntSize;
3773 }
3774 }
3775
3776 // Are long/unsigned long possibilities?
3777 if (Ty.isNull() && !Literal.isLongLong) {
3778 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3779
3780 // Does it fit in a unsigned long?
3781 if (ResultVal.isIntN(LongSize)) {
3782 // Does it fit in a signed long?
3783 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3784 Ty = Context.LongTy;
3785 else if (AllowUnsigned)
3786 Ty = Context.UnsignedLongTy;
3787 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3788 // is compatible.
3789 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3790 const unsigned LongLongSize =
3791 Context.getTargetInfo().getLongLongWidth();
3792 Diag(Tok.getLocation(),
3793 getLangOpts().CPlusPlus
3794 ? Literal.isLong
3795 ? diag::warn_old_implicitly_unsigned_long_cxx
3796 : /*C++98 UB*/ diag::
3797 ext_old_implicitly_unsigned_long_cxx
3798 : diag::warn_old_implicitly_unsigned_long)
3799 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3800 : /*will be ill-formed*/ 1);
3801 Ty = Context.UnsignedLongTy;
3802 }
3803 Width = LongSize;
3804 }
3805 }
3806
3807 // Check long long if needed.
3808 if (Ty.isNull()) {
3809 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3810
3811 // Does it fit in a unsigned long long?
3812 if (ResultVal.isIntN(LongLongSize)) {
3813 // Does it fit in a signed long long?
3814 // To be compatible with MSVC, hex integer literals ending with the
3815 // LL or i64 suffix are always signed in Microsoft mode.
3816 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3817 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3818 Ty = Context.LongLongTy;
3819 else if (AllowUnsigned)
3820 Ty = Context.UnsignedLongLongTy;
3821 Width = LongLongSize;
3822 }
3823 }
3824
3825 // If we still couldn't decide a type, we probably have something that
3826 // does not fit in a signed long long, but has no U suffix.
3827 if (Ty.isNull()) {
3828 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3829 Ty = Context.UnsignedLongLongTy;
3830 Width = Context.getTargetInfo().getLongLongWidth();
3831 }
3832
3833 if (ResultVal.getBitWidth() != Width)
3834 ResultVal = ResultVal.trunc(Width);
3835 }
3836 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3837 }
3838
3839 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3840 if (Literal.isImaginary) {
3841 Res = new (Context) ImaginaryLiteral(Res,
3842 Context.getComplexType(Res->getType()));
3843
3844 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3845 }
3846 return Res;
3847}
3848
3849ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3850 assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast
<void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3850, __PRETTY_FUNCTION__))
;
3851 return new (Context) ParenExpr(L, R, E);
3852}
3853
3854static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3855 SourceLocation Loc,
3856 SourceRange ArgRange) {
3857 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3858 // scalar or vector data type argument..."
3859 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3860 // type (C99 6.2.5p18) or void.
3861 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3862 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3863 << T << ArgRange;
3864 return true;
3865 }
3866
3867 assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3868, __PRETTY_FUNCTION__))
3868 "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3868, __PRETTY_FUNCTION__))
;
3869 return false;
3870}
3871
3872static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3873 SourceLocation Loc,
3874 SourceRange ArgRange,
3875 UnaryExprOrTypeTrait TraitKind) {
3876 // Invalid types must be hard errors for SFINAE in C++.
3877 if (S.LangOpts.CPlusPlus)
3878 return true;
3879
3880 // C99 6.5.3.4p1:
3881 if (T->isFunctionType() &&
3882 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3883 TraitKind == UETT_PreferredAlignOf)) {
3884 // sizeof(function)/alignof(function) is allowed as an extension.
3885 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3886 << TraitKind << ArgRange;
3887 return false;
3888 }
3889
3890 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3891 // this is an error (OpenCL v1.1 s6.3.k)
3892 if (T->isVoidType()) {
3893 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3894 : diag::ext_sizeof_alignof_void_type;
3895 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3896 return false;
3897 }
3898
3899 return true;
3900}
3901
3902static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3903 SourceLocation Loc,
3904 SourceRange ArgRange,
3905 UnaryExprOrTypeTrait TraitKind) {
3906 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3907 // runtime doesn't allow it.
3908 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3909 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3910 << T << (TraitKind == UETT_SizeOf)
3911 << ArgRange;
3912 return true;
3913 }
3914
3915 return false;
3916}
3917
3918/// Check whether E is a pointer from a decayed array type (the decayed
3919/// pointer type is equal to T) and emit a warning if it is.
3920static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3921 Expr *E) {
3922 // Don't warn if the operation changed the type.
3923 if (T != E->getType())
3924 return;
3925
3926 // Now look for array decays.
3927 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3928 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3929 return;
3930
3931 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3932 << ICE->getType()
3933 << ICE->getSubExpr()->getType();
3934}
3935
3936/// Check the constraints on expression operands to unary type expression
3937/// and type traits.
3938///
3939/// Completes any types necessary and validates the constraints on the operand
3940/// expression. The logic mostly mirrors the type-based overload, but may modify
3941/// the expression as it completes the type for that expression through template
3942/// instantiation, etc.
3943bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3944 UnaryExprOrTypeTrait ExprKind) {
3945 QualType ExprTy = E->getType();
3946 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3946, __PRETTY_FUNCTION__))
;
3947
3948 bool IsUnevaluatedOperand =
3949 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3950 ExprKind == UETT_PreferredAlignOf);
3951 if (IsUnevaluatedOperand) {
3952 ExprResult Result = CheckUnevaluatedOperand(E);
3953 if (Result.isInvalid())
3954 return true;
3955 E = Result.get();
3956 }
3957
3958 if (ExprKind == UETT_VecStep)
3959 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3960 E->getSourceRange());
3961
3962 // Whitelist some types as extensions
3963 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3964 E->getSourceRange(), ExprKind))
3965 return false;
3966
3967 // 'alignof' applied to an expression only requires the base element type of
3968 // the expression to be complete. 'sizeof' requires the expression's type to
3969 // be complete (and will attempt to complete it if it's an array of unknown
3970 // bound).
3971 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3972 if (RequireCompleteType(E->getExprLoc(),
3973 Context.getBaseElementType(E->getType()),
3974 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3975 E->getSourceRange()))
3976 return true;
3977 } else {
3978 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3979 ExprKind, E->getSourceRange()))
3980 return true;
3981 }
3982
3983 // Completing the expression's type may have changed it.
3984 ExprTy = E->getType();
3985 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3985, __PRETTY_FUNCTION__))
;
3986
3987 if (ExprTy->isFunctionType()) {
3988 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3989 << ExprKind << E->getSourceRange();
3990 return true;
3991 }
3992
3993 // The operand for sizeof and alignof is in an unevaluated expression context,
3994 // so side effects could result in unintended consequences.
3995 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
3996 E->HasSideEffects(Context, false))
3997 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3998
3999 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4000 E->getSourceRange(), ExprKind))
4001 return true;
4002
4003 if (ExprKind == UETT_SizeOf) {
4004 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4005 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4006 QualType OType = PVD->getOriginalType();
4007 QualType Type = PVD->getType();
4008 if (Type->isPointerType() && OType->isArrayType()) {
4009 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4010 << Type << OType;
4011 Diag(PVD->getLocation(), diag::note_declared_at);
4012 }
4013 }
4014 }
4015
4016 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4017 // decays into a pointer and returns an unintended result. This is most
4018 // likely a typo for "sizeof(array) op x".
4019 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4020 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4021 BO->getLHS());
4022 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4023 BO->getRHS());
4024 }
4025 }
4026
4027 return false;
4028}
4029
4030/// Check the constraints on operands to unary expression and type
4031/// traits.
4032///
4033/// This will complete any types necessary, and validate the various constraints
4034/// on those operands.
4035///
4036/// The UsualUnaryConversions() function is *not* called by this routine.
4037/// C99 6.3.2.1p[2-4] all state:
4038/// Except when it is the operand of the sizeof operator ...
4039///
4040/// C++ [expr.sizeof]p4
4041/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4042/// standard conversions are not applied to the operand of sizeof.
4043///
4044/// This policy is followed for all of the unary trait expressions.
4045bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4046 SourceLocation OpLoc,
4047 SourceRange ExprRange,
4048 UnaryExprOrTypeTrait ExprKind) {
4049 if (ExprType->isDependentType())
4050 return false;
4051
4052 // C++ [expr.sizeof]p2:
4053 // When applied to a reference or a reference type, the result
4054 // is the size of the referenced type.
4055 // C++11 [expr.alignof]p3:
4056 // When alignof is applied to a reference type, the result
4057 // shall be the alignment of the referenced type.
4058 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4059 ExprType = Ref->getPointeeType();
4060
4061 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4062 // When alignof or _Alignof is applied to an array type, the result
4063 // is the alignment of the element type.
4064 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4065 ExprKind == UETT_OpenMPRequiredSimdAlign)
4066 ExprType = Context.getBaseElementType(ExprType);
4067
4068 if (ExprKind == UETT_VecStep)
4069 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4070
4071 // Whitelist some types as extensions
4072 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4073 ExprKind))
4074 return false;
4075
4076 if (RequireCompleteType(OpLoc, ExprType,
4077 diag::err_sizeof_alignof_incomplete_type,
4078 ExprKind, ExprRange))
4079 return true;
4080
4081 if (ExprType->isFunctionType()) {
4082 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4083 << ExprKind << ExprRange;
4084 return true;
4085 }
4086
4087 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4088 ExprKind))
4089 return true;
4090
4091 return false;
4092}
4093
4094static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4095 // Cannot know anything else if the expression is dependent.
4096 if (E->isTypeDependent())
4097 return false;
4098
4099 if (E->getObjectKind() == OK_BitField) {
4100 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4101 << 1 << E->getSourceRange();
4102 return true;
4103 }
4104
4105 ValueDecl *D = nullptr;
4106 Expr *Inner = E->IgnoreParens();
4107 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4108 D = DRE->getDecl();
4109 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4110 D = ME->getMemberDecl();
4111 }
4112
4113 // If it's a field, require the containing struct to have a
4114 // complete definition so that we can compute the layout.
4115 //
4116 // This can happen in C++11 onwards, either by naming the member
4117 // in a way that is not transformed into a member access expression
4118 // (in an unevaluated operand, for instance), or by naming the member
4119 // in a trailing-return-type.
4120 //
4121 // For the record, since __alignof__ on expressions is a GCC
4122 // extension, GCC seems to permit this but always gives the
4123 // nonsensical answer 0.
4124 //
4125 // We don't really need the layout here --- we could instead just
4126 // directly check for all the appropriate alignment-lowing
4127 // attributes --- but that would require duplicating a lot of
4128 // logic that just isn't worth duplicating for such a marginal
4129 // use-case.
4130 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4131 // Fast path this check, since we at least know the record has a
4132 // definition if we can find a member of it.
4133 if (!FD->getParent()->isCompleteDefinition()) {
4134 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4135 << E->getSourceRange();
4136 return true;
4137 }
4138
4139 // Otherwise, if it's a field, and the field doesn't have
4140 // reference type, then it must have a complete type (or be a
4141 // flexible array member, which we explicitly want to
4142 // white-list anyway), which makes the following checks trivial.
4143 if (!FD->getType()->isReferenceType())
4144 return false;
4145 }
4146
4147 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4148}
4149
4150bool Sema::CheckVecStepExpr(Expr *E) {
4151 E = E->IgnoreParens();
4152
4153 // Cannot know anything else if the expression is dependent.
4154 if (E->isTypeDependent())
4155 return false;
4156
4157 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4158}
4159
4160static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4161 CapturingScopeInfo *CSI) {
4162 assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> (
0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4162, __PRETTY_FUNCTION__))
;
4163 assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail
("CSI != nullptr", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4163, __PRETTY_FUNCTION__))
;
4164
4165 // We're going to walk down into the type and look for VLA expressions.
4166 do {
4167 const Type *Ty = T.getTypePtr();
4168 switch (Ty->getTypeClass()) {
4169#define TYPE(Class, Base)
4170#define ABSTRACT_TYPE(Class, Base)
4171#define NON_CANONICAL_TYPE(Class, Base)
4172#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4173#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4174#include "clang/AST/TypeNodes.inc"
4175 T = QualType();
4176 break;
4177 // These types are never variably-modified.
4178 case Type::Builtin:
4179 case Type::Complex:
4180 case Type::Vector:
4181 case Type::ExtVector:
4182 case Type::Record:
4183 case Type::Enum:
4184 case Type::Elaborated:
4185 case Type::TemplateSpecialization:
4186 case Type::ObjCObject:
4187 case Type::ObjCInterface:
4188 case Type::ObjCObjectPointer:
4189 case Type::ObjCTypeParam:
4190 case Type::Pipe:
4191 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4191)
;
4192 case Type::Adjusted:
4193 T = cast<AdjustedType>(Ty)->getOriginalType();
4194 break;
4195 case Type::Decayed:
4196 T = cast<DecayedType>(Ty)->getPointeeType();
4197 break;
4198 case Type::Pointer:
4199 T = cast<PointerType>(Ty)->getPointeeType();
4200 break;
4201 case Type::BlockPointer:
4202 T = cast<BlockPointerType>(Ty)->getPointeeType();
4203 break;
4204 case Type::LValueReference:
4205 case Type::RValueReference:
4206 T = cast<ReferenceType>(Ty)->getPointeeType();
4207 break;
4208 case Type::MemberPointer:
4209 T = cast<MemberPointerType>(Ty)->getPointeeType();
4210 break;
4211 case Type::ConstantArray:
4212 case Type::IncompleteArray:
4213 // Losing element qualification here is fine.
4214 T = cast<ArrayType>(Ty)->getElementType();
4215 break;
4216 case Type::VariableArray: {
4217 // Losing element qualification here is fine.
4218 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4219
4220 // Unknown size indication requires no size computation.
4221 // Otherwise, evaluate and record it.
4222 auto Size = VAT->getSizeExpr();
4223 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4224 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4225 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4226
4227 T = VAT->getElementType();
4228 break;
4229 }
4230 case Type::FunctionProto:
4231 case Type::FunctionNoProto:
4232 T = cast<FunctionType>(Ty)->getReturnType();
4233 break;
4234 case Type::Paren:
4235 case Type::TypeOf:
4236 case Type::UnaryTransform:
4237 case Type::Attributed:
4238 case Type::SubstTemplateTypeParm:
4239 case Type::PackExpansion:
4240 case Type::MacroQualified:
4241 // Keep walking after single level desugaring.
4242 T = T.getSingleStepDesugaredType(Context);
4243 break;
4244 case Type::Typedef:
4245 T = cast<TypedefType>(Ty)->desugar();
4246 break;
4247 case Type::Decltype:
4248 T = cast<DecltypeType>(Ty)->desugar();
4249 break;
4250 case Type::Auto:
4251 case Type::DeducedTemplateSpecialization:
4252 T = cast<DeducedType>(Ty)->getDeducedType();
4253 break;
4254 case Type::TypeOfExpr:
4255 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4256 break;
4257 case Type::Atomic:
4258 T = cast<AtomicType>(Ty)->getValueType();
4259 break;
4260 }
4261 } while (!T.isNull() && T->isVariablyModifiedType());
4262}
4263
4264/// Build a sizeof or alignof expression given a type operand.
4265ExprResult
4266Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4267 SourceLocation OpLoc,
4268 UnaryExprOrTypeTrait ExprKind,
4269 SourceRange R) {
4270 if (!TInfo)
4271 return ExprError();
4272
4273 QualType T = TInfo->getType();
4274
4275 if (!T->isDependentType() &&
4276 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4277 return ExprError();
4278
4279 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4280 if (auto *TT = T->getAs<TypedefType>()) {
4281 for (auto I = FunctionScopes.rbegin(),
4282 E = std::prev(FunctionScopes.rend());
4283 I != E; ++I) {
4284 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4285 if (CSI == nullptr)
4286 break;
4287 DeclContext *DC = nullptr;
4288 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4289 DC = LSI->CallOperator;
4290 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4291 DC = CRSI->TheCapturedDecl;
4292 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4293 DC = BSI->TheDecl;
4294 if (DC) {
4295 if (DC->containsDecl(TT->getDecl()))
4296 break;
4297 captureVariablyModifiedType(Context, T, CSI);
4298 }
4299 }
4300 }
4301 }
4302
4303 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4304 return new (Context) UnaryExprOrTypeTraitExpr(
4305 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4306}
4307
4308/// Build a sizeof or alignof expression given an expression
4309/// operand.
4310ExprResult
4311Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4312 UnaryExprOrTypeTrait ExprKind) {
4313 ExprResult PE = CheckPlaceholderExpr(E);
4314 if (PE.isInvalid())
4315 return ExprError();
4316
4317 E = PE.get();
4318
4319 // Verify that the operand is valid.
4320 bool isInvalid = false;
4321 if (E->isTypeDependent()) {
4322 // Delay type-checking for type-dependent expressions.
4323 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4324 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4325 } else if (ExprKind == UETT_VecStep) {
4326 isInvalid = CheckVecStepExpr(E);
4327 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4328 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4329 isInvalid = true;
4330 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4331 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4332 isInvalid = true;
4333 } else {
4334 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4335 }
4336
4337 if (isInvalid)
4338 return ExprError();
4339
4340 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4341 PE = TransformToPotentiallyEvaluated(E);
4342 if (PE.isInvalid()) return ExprError();
4343 E = PE.get();
4344 }
4345
4346 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4347 return new (Context) UnaryExprOrTypeTraitExpr(
4348 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4349}
4350
4351/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4352/// expr and the same for @c alignof and @c __alignof
4353/// Note that the ArgRange is invalid if isType is false.
4354ExprResult
4355Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4356 UnaryExprOrTypeTrait ExprKind, bool IsType,
4357 void *TyOrEx, SourceRange ArgRange) {
4358 // If error parsing type, ignore.
4359 if (!TyOrEx) return ExprError();
4360
4361 if (IsType) {
4362 TypeSourceInfo *TInfo;
4363 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4364 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4365 }
4366
4367 Expr *ArgEx = (Expr *)TyOrEx;
4368 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4369 return Result;
4370}
4371
4372static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4373 bool IsReal) {
4374 if (V.get()->isTypeDependent())
4375 return S.Context.DependentTy;
4376
4377 // _Real and _Imag are only l-values for normal l-values.
4378 if (V.get()->getObjectKind() != OK_Ordinary) {
4379 V = S.DefaultLvalueConversion(V.get());
4380 if (V.isInvalid())
4381 return QualType();
4382 }
4383
4384 // These operators return the element type of a complex type.
4385 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4386 return CT->getElementType();
4387
4388 // Otherwise they pass through real integer and floating point types here.
4389 if (V.get()->getType()->isArithmeticType())
4390 return V.get()->getType();
4391
4392 // Test for placeholders.
4393 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4394 if (PR.isInvalid()) return QualType();
4395 if (PR.get() != V.get()) {
4396 V = PR;
4397 return CheckRealImagOperand(S, V, Loc, IsReal);
4398 }
4399
4400 // Reject anything else.
4401 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4402 << (IsReal ? "__real" : "__imag");
4403 return QualType();
4404}
4405
4406
4407
4408ExprResult
4409Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4410 tok::TokenKind Kind, Expr *Input) {
4411 UnaryOperatorKind Opc;
4412 switch (Kind) {
4413 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4413)
;
4414 case tok::plusplus: Opc = UO_PostInc; break;
4415 case tok::minusminus: Opc = UO_PostDec; break;
4416 }
4417
4418 // Since this might is a postfix expression, get rid of ParenListExprs.
4419 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4420 if (Result.isInvalid()) return ExprError();
4421 Input = Result.get();
4422
4423 return BuildUnaryOp(S, OpLoc, Opc, Input);
4424}
4425
4426/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4427///
4428/// \return true on error
4429static bool checkArithmeticOnObjCPointer(Sema &S,
4430 SourceLocation opLoc,
4431 Expr *op) {
4432 assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast
<void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4432, __PRETTY_FUNCTION__))
;
4433 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4434 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4435 return false;
4436
4437 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4438 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4439 << op->getSourceRange();
4440 return true;
4441}
4442
4443static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4444 auto *BaseNoParens = Base->IgnoreParens();
4445 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4446 return MSProp->getPropertyDecl()->getType()->isArrayType();
4447 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4448}
4449
4450ExprResult
4451Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4452 Expr *idx, SourceLocation rbLoc) {
4453 if (base
8.1
'base' is non-null
8.1
'base' is non-null
&& !base->getType().isNull() &&
9
Taking false branch
4454 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4455 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4456 /*Length=*/nullptr, rbLoc);
4457
4458 // Since this might be a postfix expression, get rid of ParenListExprs.
4459 if (isa<ParenListExpr>(base)) {
10
Assuming 'base' is not a 'ParenListExpr'
11
Taking false branch
4460 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4461 if (result.isInvalid()) return ExprError();
4462 base = result.get();
4463 }
4464
4465 // A comma-expression as the index is deprecated in C++2a onwards.
4466 if (getLangOpts().CPlusPlus2a &&
12
Assuming field 'CPlusPlus2a' is 0
4467 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4468 (isa<CXXOperatorCallExpr>(idx) &&
4469 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4470 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4471 << SourceRange(base->getBeginLoc(), rbLoc);
4472 }
4473
4474 // Handle any non-overload placeholder types in the base and index
4475 // expressions. We can't handle overloads here because the other
4476 // operand might be an overloadable type, in which case the overload
4477 // resolution for the operator overload should get the first crack
4478 // at the overload.
4479 bool IsMSPropertySubscript = false;
4480 if (base->getType()->isNonOverloadPlaceholderType()) {
13
Taking false branch
4481 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4482 if (!IsMSPropertySubscript) {
4483 ExprResult result = CheckPlaceholderExpr(base);
4484 if (result.isInvalid())
4485 return ExprError();
4486 base = result.get();
4487 }
4488 }
4489 if (idx->getType()->isNonOverloadPlaceholderType()) {
14
Taking false branch
4490 ExprResult result = CheckPlaceholderExpr(idx);
4491 if (result.isInvalid()) return ExprError();
4492 idx = result.get();
4493 }
4494
4495 // Build an unanalyzed expression if either operand is type-dependent.
4496 if (getLangOpts().CPlusPlus &&
15
Assuming field 'CPlusPlus' is 0
4497 (base->isTypeDependent() || idx->isTypeDependent())) {
4498 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4499 VK_LValue, OK_Ordinary, rbLoc);
4500 }
4501
4502 // MSDN, property (C++)
4503 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4504 // This attribute can also be used in the declaration of an empty array in a
4505 // class or structure definition. For example:
4506 // __declspec(property(get=GetX, put=PutX)) int x[];
4507 // The above statement indicates that x[] can be used with one or more array
4508 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4509 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4510 if (IsMSPropertySubscript
15.1
'IsMSPropertySubscript' is false
15.1
'IsMSPropertySubscript' is false
) {
16
Taking false branch
4511 // Build MS property subscript expression if base is MS property reference
4512 // or MS property subscript.
4513 return new (Context) MSPropertySubscriptExpr(
4514 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4515 }
4516
4517 // Use C++ overloaded-operator rules if either operand has record
4518 // type. The spec says to do this if either type is *overloadable*,
4519 // but enum types can't declare subscript operators or conversion
4520 // operators, so there's nothing interesting for overload resolution
4521 // to do if there aren't any record types involved.
4522 //
4523 // ObjC pointers have their own subscripting logic that is not tied
4524 // to overload resolution and so should not take this path.
4525 if (getLangOpts().CPlusPlus
16.1
Field 'CPlusPlus' is 0
16.1
Field 'CPlusPlus' is 0
&&
17
Taking false branch
4526 (base->getType()->isRecordType() ||
4527 (!base->getType()->isObjCObjectPointerType() &&
4528 idx->getType()->isRecordType()))) {
4529 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4530 }
4531
4532 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
18
Calling 'Sema::CreateBuiltinArraySubscriptExpr'
4533
4534 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4535 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4536
4537 return Res;
4538}
4539
4540void Sema::CheckAddressOfNoDeref(const Expr *E) {
4541 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4542 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4543
4544 // For expressions like `&(*s).b`, the base is recorded and what should be
4545 // checked.
4546 const MemberExpr *Member = nullptr;
4547 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4548 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4549
4550 LastRecord.PossibleDerefs.erase(StrippedExpr);
4551}
4552
4553void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4554 QualType ResultTy = E->getType();
4555 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4556
4557 // Bail if the element is an array since it is not memory access.
4558 if (isa<ArrayType>(ResultTy))
4559 return;
4560
4561 if (ResultTy->hasAttr(attr::NoDeref)) {
4562 LastRecord.PossibleDerefs.insert(E);
4563 return;
4564 }
4565
4566 // Check if the base type is a pointer to a member access of a struct
4567 // marked with noderef.
4568 const Expr *Base = E->getBase();
4569 QualType BaseTy = Base->getType();
4570 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4571 // Not a pointer access
4572 return;
4573
4574 const MemberExpr *Member = nullptr;
4575 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4576 Member->isArrow())
4577 Base = Member->getBase();
4578
4579 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4580 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4581 LastRecord.PossibleDerefs.insert(E);
4582 }
4583}
4584
4585ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4586 Expr *LowerBound,
4587 SourceLocation ColonLoc, Expr *Length,
4588 SourceLocation RBLoc) {
4589 if (Base->getType()->isPlaceholderType() &&
4590 !Base->getType()->isSpecificPlaceholderType(
4591 BuiltinType::OMPArraySection)) {
4592 ExprResult Result = CheckPlaceholderExpr(Base);
4593 if (Result.isInvalid())
4594 return ExprError();
4595 Base = Result.get();
4596 }
4597 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4598 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4599 if (Result.isInvalid())
4600 return ExprError();
4601 Result = DefaultLvalueConversion(Result.get());
4602 if (Result.isInvalid())
4603 return ExprError();
4604 LowerBound = Result.get();
4605 }
4606 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4607 ExprResult Result = CheckPlaceholderExpr(Length);
4608 if (Result.isInvalid())
4609 return ExprError();
4610 Result = DefaultLvalueConversion(Result.get());
4611 if (Result.isInvalid())
4612 return ExprError();
4613 Length = Result.get();
4614 }
4615
4616 // Build an unanalyzed expression if either operand is type-dependent.
4617 if (Base->isTypeDependent() ||
4618 (LowerBound &&
4619 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4620 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4621 return new (Context)
4622 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4623 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4624 }
4625
4626 // Perform default conversions.
4627 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4628 QualType ResultTy;
4629 if (OriginalTy->isAnyPointerType()) {
4630 ResultTy = OriginalTy->getPointeeType();
4631 } else if (OriginalTy->isArrayType()) {
4632 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4633 } else {
4634 return ExprError(
4635 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4636 << Base->getSourceRange());
4637 }
4638 // C99 6.5.2.1p1
4639 if (LowerBound) {
4640 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4641 LowerBound);
4642 if (Res.isInvalid())
4643 return ExprError(Diag(LowerBound->getExprLoc(),
4644 diag::err_omp_typecheck_section_not_integer)
4645 << 0 << LowerBound->getSourceRange());
4646 LowerBound = Res.get();
4647
4648 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4649 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4650 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4651 << 0 << LowerBound->getSourceRange();
4652 }
4653 if (Length) {
4654 auto Res =
4655 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4656 if (Res.isInvalid())
4657 return ExprError(Diag(Length->getExprLoc(),
4658 diag::err_omp_typecheck_section_not_integer)
4659 << 1 << Length->getSourceRange());
4660 Length = Res.get();
4661
4662 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4663 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4664 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4665 << 1 << Length->getSourceRange();
4666 }
4667
4668 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4669 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4670 // type. Note that functions are not objects, and that (in C99 parlance)
4671 // incomplete types are not object types.
4672 if (ResultTy->isFunctionType()) {
4673 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4674 << ResultTy << Base->getSourceRange();
4675 return ExprError();
4676 }
4677
4678 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4679 diag::err_omp_section_incomplete_type, Base))
4680 return ExprError();
4681
4682 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4683 Expr::EvalResult Result;
4684 if (LowerBound->EvaluateAsInt(Result, Context)) {
4685 // OpenMP 4.5, [2.4 Array Sections]
4686 // The array section must be a subset of the original array.
4687 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4688 if (LowerBoundValue.isNegative()) {
4689 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4690 << LowerBound->getSourceRange();
4691 return ExprError();
4692 }
4693 }
4694 }
4695
4696 if (Length) {
4697 Expr::EvalResult Result;
4698 if (Length->EvaluateAsInt(Result, Context)) {
4699 // OpenMP 4.5, [2.4 Array Sections]
4700 // The length must evaluate to non-negative integers.
4701 llvm::APSInt LengthValue = Result.Val.getInt();
4702 if (LengthValue.isNegative()) {
4703 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4704 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4705 << Length->getSourceRange();
4706 return ExprError();
4707 }
4708 }
4709 } else if (ColonLoc.isValid() &&
4710 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4711 !OriginalTy->isVariableArrayType()))) {
4712 // OpenMP 4.5, [2.4 Array Sections]
4713 // When the size of the array dimension is not known, the length must be
4714 // specified explicitly.
4715 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4716 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4717 return ExprError();
4718 }
4719
4720 if (!Base->getType()->isSpecificPlaceholderType(
4721 BuiltinType::OMPArraySection)) {
4722 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4723 if (Result.isInvalid())
4724 return ExprError();
4725 Base = Result.get();
4726 }
4727 return new (Context)
4728 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4729 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4730}
4731
4732ExprResult
4733Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4734 Expr *Idx, SourceLocation RLoc) {
4735 Expr *LHSExp = Base;
4736 Expr *RHSExp = Idx;
4737
4738 ExprValueKind VK = VK_LValue;
4739 ExprObjectKind OK = OK_Ordinary;
4740
4741 // Per C++ core issue 1213, the result is an xvalue if either operand is
4742 // a non-lvalue array, and an lvalue otherwise.
4743 if (getLangOpts().CPlusPlus11) {
19
Assuming field 'CPlusPlus11' is 0
20
Taking false branch
4744 for (auto *Op : {LHSExp, RHSExp}) {
4745 Op = Op->IgnoreImplicit();
4746 if (Op->getType()->isArrayType() && !Op->isLValue())
4747 VK = VK_XValue;
4748 }
4749 }
4750
4751 // Perform default conversions.
4752 if (!LHSExp->getType()->getAs<VectorType>()) {
21
Assuming the object is not a 'VectorType'
22
Taking true branch
4753 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4754 if (Result.isInvalid())
23
Taking false branch
4755 return ExprError();
4756 LHSExp = Result.get();
4757 }
4758 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4759 if (Result.isInvalid())
24
Taking false branch
4760 return ExprError();
4761 RHSExp = Result.get();
4762
4763 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4764
4765 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4766 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4767 // in the subscript position. As a result, we need to derive the array base
4768 // and index from the expression types.
4769 Expr *BaseExpr, *IndexExpr;
4770 QualType ResultType;
4771 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
25
Assuming the condition is false
26
Assuming the condition is false
27
Taking false branch
4772 BaseExpr = LHSExp;
4773 IndexExpr = RHSExp;
4774 ResultType = Context.DependentTy;
4775 } else if (const PointerType *PTy
28.1
'PTy' is null
28.1
'PTy' is null
= LHSTy->getAs<PointerType>()) {
28
Assuming the object is not a 'PointerType'
29
Taking false branch
4776 BaseExpr = LHSExp;
4777 IndexExpr = RHSExp;
4778 ResultType = PTy->getPointeeType();
4779 } else if (const ObjCObjectPointerType *PTy
30.1
'PTy' is null
30.1
'PTy' is null
=
31
Taking false branch
4780 LHSTy->getAs<ObjCObjectPointerType>()) {
30
Assuming the object is not a 'ObjCObjectPointerType'
4781 BaseExpr = LHSExp;
4782 IndexExpr = RHSExp;
4783
4784 // Use custom logic if this should be the pseudo-object subscript
4785 // expression.
4786 if (!LangOpts.isSubscriptPointerArithmetic())
4787 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4788 nullptr);
4789
4790 ResultType = PTy->getPointeeType();
4791 } else if (const PointerType *PTy
32.1
'PTy' is null
32.1
'PTy' is null
= RHSTy->getAs<PointerType>()) {
32
Assuming the object is not a 'PointerType'
33
Taking false branch
4792 // Handle the uncommon case of "123[Ptr]".
4793 BaseExpr = RHSExp;
4794 IndexExpr = LHSExp;
4795 ResultType = PTy->getPointeeType();
4796 } else if (const ObjCObjectPointerType *PTy
34.1
'PTy' is null
34.1
'PTy' is null
=
35
Taking false branch
4797 RHSTy->getAs<ObjCObjectPointerType>()) {
34
Assuming the object is not a 'ObjCObjectPointerType'
4798 // Handle the uncommon case of "123[Ptr]".
4799 BaseExpr = RHSExp;
4800 IndexExpr = LHSExp;
4801 ResultType = PTy->getPointeeType();
4802 if (!LangOpts.isSubscriptPointerArithmetic()) {
4803 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4804 << ResultType << BaseExpr->getSourceRange();
4805 return ExprError();
4806 }
4807 } else if (const VectorType *VTy
36.1
'VTy' is null
36.1
'VTy' is null
= LHSTy->getAs<VectorType>()) {
36
Assuming the object is not a 'VectorType'
37
Taking false branch
4808 BaseExpr = LHSExp; // vectors: V[123]
4809 IndexExpr = RHSExp;
4810 // We apply C++ DR1213 to vector subscripting too.
4811 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4812 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4813 if (Materialized.isInvalid())
4814 return ExprError();
4815 LHSExp = Materialized.get();
4816 }
4817 VK = LHSExp->getValueKind();
4818 if (VK != VK_RValue)
4819 OK = OK_VectorComponent;
4820
4821 ResultType = VTy->getElementType();
4822 QualType BaseType = BaseExpr->getType();
4823 Qualifiers BaseQuals = BaseType.getQualifiers();
4824 Qualifiers MemberQuals = ResultType.getQualifiers();
4825 Qualifiers Combined = BaseQuals + MemberQuals;
4826 if (Combined != MemberQuals)
4827 ResultType = Context.getQualifiedType(ResultType, Combined);
4828 } else if (LHSTy->isArrayType()) {
38
Calling 'Type::isArrayType'
41
Returning from 'Type::isArrayType'
42
Taking false branch
4829 // If we see an array that wasn't promoted by
4830 // DefaultFunctionArrayLvalueConversion, it must be an array that
4831 // wasn't promoted because of the C90 rule that doesn't
4832 // allow promoting non-lvalue arrays. Warn, then
4833 // force the promotion here.
4834 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4835 << LHSExp->getSourceRange();
4836 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4837 CK_ArrayToPointerDecay).get();
4838 LHSTy = LHSExp->getType();
4839
4840 BaseExpr = LHSExp;
4841 IndexExpr = RHSExp;
4842 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4843 } else if (RHSTy->isArrayType()) {
43
Calling 'Type::isArrayType'
46
Returning from 'Type::isArrayType'
47
Taking true branch
4844 // Same as previous, except for 123[f().a] case
4845 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4846 << RHSExp->getSourceRange();
4847 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4848 CK_ArrayToPointerDecay).get();
4849 RHSTy = RHSExp->getType();
4850
4851 BaseExpr = RHSExp;
4852 IndexExpr = LHSExp;
4853 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
48
Assuming the object is not a 'PointerType'
49
Called C++ object pointer is null
4854 } else {
4855 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4856 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4857 }
4858 // C99 6.5.2.1p1
4859 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4860 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4861 << IndexExpr->getSourceRange());
4862
4863 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4864 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4865 && !IndexExpr->isTypeDependent())
4866 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4867
4868 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4869 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4870 // type. Note that Functions are not objects, and that (in C99 parlance)
4871 // incomplete types are not object types.
4872 if (ResultType->isFunctionType()) {
4873 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4874 << ResultType << BaseExpr->getSourceRange();
4875 return ExprError();
4876 }
4877
4878 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4879 // GNU extension: subscripting on pointer to void
4880 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4881 << BaseExpr->getSourceRange();
4882
4883 // C forbids expressions of unqualified void type from being l-values.
4884 // See IsCForbiddenLValueType.
4885 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4886 } else if (!ResultType->isDependentType() &&
4887 RequireCompleteType(LLoc, ResultType,
4888 diag::err_subscript_incomplete_type, BaseExpr))
4889 return ExprError();
4890
4891 assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4892, __PRETTY_FUNCTION__))
4892 !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4892, __PRETTY_FUNCTION__))
;
4893
4894 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4895 FunctionScopes.size() > 1) {
4896 if (auto *TT =
4897 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4898 for (auto I = FunctionScopes.rbegin(),
4899 E = std::prev(FunctionScopes.rend());
4900 I != E; ++I) {
4901 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4902 if (CSI == nullptr)
4903 break;
4904 DeclContext *DC = nullptr;
4905 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4906 DC = LSI->CallOperator;
4907 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4908 DC = CRSI->TheCapturedDecl;
4909 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4910 DC = BSI->TheDecl;
4911 if (DC) {
4912 if (DC->containsDecl(TT->getDecl()))
4913 break;
4914 captureVariablyModifiedType(
4915 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4916 }
4917 }
4918 }
4919 }
4920
4921 return new (Context)
4922 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4923}
4924
4925bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4926 ParmVarDecl *Param) {
4927 if (Param->hasUnparsedDefaultArg()) {
4928 Diag(CallLoc,
4929 diag::err_use_of_default_argument_to_function_declared_later) <<
4930 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4931 Diag(UnparsedDefaultArgLocs[Param],
4932 diag::note_default_argument_declared_here);
4933 return true;
4934 }
4935
4936 if (Param->hasUninstantiatedDefaultArg()) {
4937 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4938
4939 EnterExpressionEvaluationContext EvalContext(
4940 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4941
4942 // Instantiate the expression.
4943 //
4944 // FIXME: Pass in a correct Pattern argument, otherwise
4945 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4946 //
4947 // template<typename T>
4948 // struct A {
4949 // static int FooImpl();
4950 //
4951 // template<typename Tp>
4952 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4953 // // template argument list [[T], [Tp]], should be [[Tp]].
4954 // friend A<Tp> Foo(int a);
4955 // };
4956 //
4957 // template<typename T>
4958 // A<T> Foo(int a = A<T>::FooImpl());
4959 MultiLevelTemplateArgumentList MutiLevelArgList
4960 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4961
4962 InstantiatingTemplate Inst(*this, CallLoc, Param,
4963 MutiLevelArgList.getInnermost());
4964 if (Inst.isInvalid())
4965 return true;
4966 if (Inst.isAlreadyInstantiating()) {
4967 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4968 Param->setInvalidDecl();
4969 return true;
4970 }
4971
4972 ExprResult Result;
4973 {
4974 // C++ [dcl.fct.default]p5:
4975 // The names in the [default argument] expression are bound, and
4976 // the semantic constraints are checked, at the point where the
4977 // default argument expression appears.
4978 ContextRAII SavedContext(*this, FD);
4979 LocalInstantiationScope Local(*this);
4980 runWithSufficientStackSpace(CallLoc, [&] {
4981 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4982 /*DirectInit*/false);
4983 });
4984 }
4985 if (Result.isInvalid())
4986 return true;
4987
4988 // Check the expression as an initializer for the parameter.
4989 InitializedEntity Entity
4990 = InitializedEntity::InitializeParameter(Context, Param);
4991 InitializationKind Kind = InitializationKind::CreateCopy(
4992 Param->getLocation(),
4993 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4994 Expr *ResultE = Result.getAs<Expr>();
4995
4996 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4997 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4998 if (Result.isInvalid())
4999 return true;
5000
5001 Result =
5002 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5003 /*DiscardedValue*/ false);
5004 if (Result.isInvalid())
5005 return true;
5006
5007 // Remember the instantiated default argument.
5008 Param->setDefaultArg(Result.getAs<Expr>());
5009 if (ASTMutationListener *L = getASTMutationListener()) {
5010 L->DefaultArgumentInstantiated(Param);
5011 }
5012 }
5013
5014 // If the default argument expression is not set yet, we are building it now.
5015 if (!Param->hasInit()) {
5016 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5017 Param->setInvalidDecl();
5018 return true;
5019 }
5020
5021 // If the default expression creates temporaries, we need to
5022 // push them to the current stack of expression temporaries so they'll
5023 // be properly destroyed.
5024 // FIXME: We should really be rebuilding the default argument with new
5025 // bound temporaries; see the comment in PR5810.
5026 // We don't need to do that with block decls, though, because
5027 // blocks in default argument expression can never capture anything.
5028 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5029 // Set the "needs cleanups" bit regardless of whether there are
5030 // any explicit objects.
5031 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5032
5033 // Append all the objects to the cleanup list. Right now, this
5034 // should always be a no-op, because blocks in default argument
5035 // expressions should never be able to capture anything.
5036 assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5037, __PRETTY_FUNCTION__))
5037 "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5037, __PRETTY_FUNCTION__))
;
5038 }
5039
5040 // We already type-checked the argument, so we know it works.
5041 // Just mark all of the declarations in this potentially-evaluated expression
5042 // as being "referenced".
5043 EnterExpressionEvaluationContext EvalContext(
5044 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5045 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5046 /*SkipLocalVariables=*/true);
5047 return false;
5048}
5049
5050ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5051 FunctionDecl *FD, ParmVarDecl *Param) {
5052 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5053 return ExprError();
5054 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5055}
5056
5057Sema::VariadicCallType
5058Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5059 Expr *Fn) {
5060 if (Proto && Proto->isVariadic()) {
5061 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5062 return VariadicConstructor;
5063 else if (Fn && Fn->getType()->isBlockPointerType())
5064 return VariadicBlock;
5065 else if (FDecl) {
5066 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5067 if (Method->isInstance())
5068 return VariadicMethod;
5069 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5070 return VariadicMethod;
5071 return VariadicFunction;
5072 }
5073 return VariadicDoesNotApply;
5074}
5075
5076namespace {
5077class FunctionCallCCC final : public FunctionCallFilterCCC {
5078public:
5079 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5080 unsigned NumArgs, MemberExpr *ME)
5081 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5082 FunctionName(FuncName) {}
5083
5084 bool ValidateCandidate(const TypoCorrection &candidate) override {
5085 if (!candidate.getCorrectionSpecifier() ||
5086 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5087 return false;
5088 }
5089
5090 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5091 }
5092
5093 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5094 return std::make_unique<FunctionCallCCC>(*this);
5095 }
5096
5097private:
5098 const IdentifierInfo *const FunctionName;
5099};
5100}
5101
5102static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5103 FunctionDecl *FDecl,
5104 ArrayRef<Expr *> Args) {
5105 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5106 DeclarationName FuncName = FDecl->getDeclName();
5107 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5108
5109 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5110 if (TypoCorrection Corrected = S.CorrectTypo(
5111 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5112 S.getScopeForContext(S.CurContext), nullptr, CCC,
5113 Sema::CTK_ErrorRecovery)) {
5114 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5115 if (Corrected.isOverloaded()) {
5116 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5117 OverloadCandidateSet::iterator Best;
5118 for (NamedDecl *CD : Corrected) {
5119 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5120 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5121 OCS);
5122 }
5123 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5124 case OR_Success:
5125 ND = Best->FoundDecl;
5126 Corrected.setCorrectionDecl(ND);
5127 break;
5128 default:
5129 break;
5130 }
5131 }
5132 ND = ND->getUnderlyingDecl();
5133 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5134 return Corrected;
5135 }
5136 }
5137 return TypoCorrection();
5138}
5139
5140/// ConvertArgumentsForCall - Converts the arguments specified in
5141/// Args/NumArgs to the parameter types of the function FDecl with
5142/// function prototype Proto. Call is the call expression itself, and
5143/// Fn is the function expression. For a C++ member function, this
5144/// routine does not attempt to convert the object argument. Returns
5145/// true if the call is ill-formed.
5146bool
5147Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5148 FunctionDecl *FDecl,
5149 const FunctionProtoType *Proto,
5150 ArrayRef<Expr *> Args,
5151 SourceLocation RParenLoc,
5152 bool IsExecConfig) {
5153 // Bail out early if calling a builtin with custom typechecking.
5154 if (FDecl)
5155 if (unsigned ID = FDecl->getBuiltinID())
5156 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5157 return false;
5158
5159 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5160 // assignment, to the types of the corresponding parameter, ...
5161 unsigned NumParams = Proto->getNumParams();
5162 bool Invalid = false;
5163 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5164 unsigned FnKind = Fn->getType()->isBlockPointerType()
5165 ? 1 /* block */
5166 : (IsExecConfig ? 3 /* kernel function (exec config) */
5167 : 0 /* function */);
5168
5169 // If too few arguments are available (and we don't have default
5170 // arguments for the remaining parameters), don't make the call.
5171 if (Args.size() < NumParams) {
5172 if (Args.size() < MinArgs) {
5173 TypoCorrection TC;
5174 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5175 unsigned diag_id =
5176 MinArgs == NumParams && !Proto->isVariadic()
5177 ? diag::err_typecheck_call_too_few_args_suggest
5178 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5179 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5180 << static_cast<unsigned>(Args.size())
5181 << TC.getCorrectionRange());
5182 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5183 Diag(RParenLoc,
5184 MinArgs == NumParams && !Proto->isVariadic()
5185 ? diag::err_typecheck_call_too_few_args_one
5186 : diag::err_typecheck_call_too_few_args_at_least_one)
5187 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5188 else
5189 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5190 ? diag::err_typecheck_call_too_few_args
5191 : diag::err_typecheck_call_too_few_args_at_least)
5192 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5193 << Fn->getSourceRange();
5194
5195 // Emit the location of the prototype.
5196 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5197 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5198
5199 return true;
5200 }
5201 // We reserve space for the default arguments when we create
5202 // the call expression, before calling ConvertArgumentsForCall.
5203 assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5204, __PRETTY_FUNCTION__))
5204 "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5204, __PRETTY_FUNCTION__))
;
5205 }
5206
5207 // If too many are passed and not variadic, error on the extras and drop
5208 // them.
5209 if (Args.size() > NumParams) {
5210 if (!Proto->isVariadic()) {
5211 TypoCorrection TC;
5212 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5213 unsigned diag_id =
5214 MinArgs == NumParams && !Proto->isVariadic()
5215 ? diag::err_typecheck_call_too_many_args_suggest
5216 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5217 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5218 << static_cast<unsigned>(Args.size())
5219 << TC.getCorrectionRange());
5220 } else if (NumParams == 1 && FDecl &&
5221 FDecl->getParamDecl(0)->getDeclName())
5222 Diag(Args[NumParams]->getBeginLoc(),
5223 MinArgs == NumParams
5224 ? diag::err_typecheck_call_too_many_args_one
5225 : diag::err_typecheck_call_too_many_args_at_most_one)
5226 << FnKind << FDecl->getParamDecl(0)
5227 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5228 << SourceRange(Args[NumParams]->getBeginLoc(),
5229 Args.back()->getEndLoc());
5230 else
5231 Diag(Args[NumParams]->getBeginLoc(),
5232 MinArgs == NumParams
5233 ? diag::err_typecheck_call_too_many_args
5234 : diag::err_typecheck_call_too_many_args_at_most)
5235 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5236 << Fn->getSourceRange()
5237 << SourceRange(Args[NumParams]->getBeginLoc(),
5238 Args.back()->getEndLoc());
5239
5240 // Emit the location of the prototype.
5241 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5242 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5243
5244 // This deletes the extra arguments.
5245 Call->shrinkNumArgs(NumParams);
5246 return true;
5247 }
5248 }
5249 SmallVector<Expr *, 8> AllArgs;
5250 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5251
5252 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5253 AllArgs, CallType);
5254 if (Invalid)
5255 return true;
5256 unsigned TotalNumArgs = AllArgs.size();
5257 for (unsigned i = 0; i < TotalNumArgs; ++i)
5258 Call->setArg(i, AllArgs[i]);
5259
5260 return false;
5261}
5262
5263bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5264 const FunctionProtoType *Proto,
5265 unsigned FirstParam, ArrayRef<Expr *> Args,
5266 SmallVectorImpl<Expr *> &AllArgs,
5267 VariadicCallType CallType, bool AllowExplicit,
5268 bool IsListInitialization) {
5269 unsigned NumParams = Proto->getNumParams();
5270 bool Invalid = false;
5271 size_t ArgIx = 0;
5272 // Continue to check argument types (even if we have too few/many args).
5273 for (unsigned i = FirstParam; i < NumParams; i++) {
5274 QualType ProtoArgType = Proto->getParamType(i);
5275
5276 Expr *Arg;
5277 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5278 if (ArgIx < Args.size()) {
5279 Arg = Args[ArgIx++];
5280
5281 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5282 diag::err_call_incomplete_argument, Arg))
5283 return true;
5284
5285 // Strip the unbridged-cast placeholder expression off, if applicable.
5286 bool CFAudited = false;
5287 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5288 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5289 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5290 Arg = stripARCUnbridgedCast(Arg);
5291 else if (getLangOpts().ObjCAutoRefCount &&
5292 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5293 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5294 CFAudited = true;
5295
5296 if (Proto->getExtParameterInfo(i).isNoEscape())
5297 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5298 BE->getBlockDecl()->setDoesNotEscape();
5299
5300 InitializedEntity Entity =
5301 Param ? InitializedEntity::InitializeParameter(Context, Param,
5302 ProtoArgType)
5303 : InitializedEntity::InitializeParameter(
5304 Context, ProtoArgType, Proto->isParamConsumed(i));
5305
5306 // Remember that parameter belongs to a CF audited API.
5307 if (CFAudited)
5308 Entity.setParameterCFAudited();
5309
5310 ExprResult ArgE = PerformCopyInitialization(
5311 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5312 if (ArgE.isInvalid())
5313 return true;
5314
5315 Arg = ArgE.getAs<Expr>();
5316 } else {
5317 assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee"
) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5317, __PRETTY_FUNCTION__))
;
5318
5319 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5320 if (ArgExpr.isInvalid())
5321 return true;
5322
5323 Arg = ArgExpr.getAs<Expr>();
5324 }
5325
5326 // Check for array bounds violations for each argument to the call. This
5327 // check only triggers warnings when the argument isn't a more complex Expr
5328 // with its own checking, such as a BinaryOperator.
5329 CheckArrayAccess(Arg);
5330
5331 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5332 CheckStaticArrayArgument(CallLoc, Param, Arg);
5333
5334 AllArgs.push_back(Arg);
5335 }
5336
5337 // If this is a variadic call, handle args passed through "...".
5338 if (CallType != VariadicDoesNotApply) {
5339 // Assume that extern "C" functions with variadic arguments that
5340 // return __unknown_anytype aren't *really* variadic.
5341 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5342 FDecl->isExternC()) {
5343 for (Expr *A : Args.slice(ArgIx)) {
5344 QualType paramType; // ignored
5345 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5346 Invalid |= arg.isInvalid();
5347 AllArgs.push_back(arg.get());
5348 }
5349
5350 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5351 } else {
5352 for (Expr *A : Args.slice(ArgIx)) {
5353 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5354 Invalid |= Arg.isInvalid();
5355 // Copy blocks to the heap.
5356 if (A->getType()->isBlockPointerType())
5357 maybeExtendBlockObject(Arg);
5358 AllArgs.push_back(Arg.get());
5359 }
5360 }
5361
5362 // Check for array bounds violations.
5363 for (Expr *A : Args.slice(ArgIx))
5364 CheckArrayAccess(A);
5365 }
5366 return Invalid;
5367}
5368
5369static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5370 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5371 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5372 TL = DTL.getOriginalLoc();
5373 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5374 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5375 << ATL.getLocalSourceRange();
5376}
5377
5378/// CheckStaticArrayArgument - If the given argument corresponds to a static
5379/// array parameter, check that it is non-null, and that if it is formed by
5380/// array-to-pointer decay, the underlying array is sufficiently large.
5381///
5382/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5383/// array type derivation, then for each call to the function, the value of the
5384/// corresponding actual argument shall provide access to the first element of
5385/// an array with at least as many elements as specified by the size expression.
5386void
5387Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5388 ParmVarDecl *Param,
5389 const Expr *ArgExpr) {
5390 // Static array parameters are not supported in C++.
5391 if (!Param || getLangOpts().CPlusPlus)
5392 return;
5393
5394 QualType OrigTy = Param->getOriginalType();
5395
5396 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5397 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5398 return;
5399
5400 if (ArgExpr->isNullPointerConstant(Context,
5401 Expr::NPC_NeverValueDependent)) {
5402 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5403 DiagnoseCalleeStaticArrayParam(*this, Param);
5404 return;
5405 }
5406
5407 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5408 if (!CAT)
5409 return;
5410
5411 const ConstantArrayType *ArgCAT =
5412 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5413 if (!ArgCAT)
5414 return;
5415
5416 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5417 ArgCAT->getElementType())) {
5418 if (ArgCAT->getSize().ult(CAT->getSize())) {
5419 Diag(CallLoc, diag::warn_static_array_too_small)
5420 << ArgExpr->getSourceRange()
5421 << (unsigned)ArgCAT->getSize().getZExtValue()
5422 << (unsigned)CAT->getSize().getZExtValue() << 0;
5423 DiagnoseCalleeStaticArrayParam(*this, Param);
5424 }
5425 return;
5426 }
5427
5428 Optional<CharUnits> ArgSize =
5429 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5430 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5431 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5432 Diag(CallLoc, diag::warn_static_array_too_small)
5433 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5434 << (unsigned)ParmSize->getQuantity() << 1;
5435 DiagnoseCalleeStaticArrayParam(*this, Param);
5436 }
5437}
5438
5439/// Given a function expression of unknown-any type, try to rebuild it
5440/// to have a function type.
5441static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5442
5443/// Is the given type a placeholder that we need to lower out
5444/// immediately during argument processing?
5445static bool isPlaceholderToRemoveAsArg(QualType type) {
5446 // Placeholders are never sugared.
5447 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5448 if (!placeholder) return false;
5449
5450 switch (placeholder->getKind()) {
5451 // Ignore all the non-placeholder types.
5452#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5453 case BuiltinType::Id:
5454#include "clang/Basic/OpenCLImageTypes.def"
5455#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5456 case BuiltinType::Id:
5457#include "clang/Basic/OpenCLExtensionTypes.def"
5458 // In practice we'll never use this, since all SVE types are sugared
5459 // via TypedefTypes rather than exposed directly as BuiltinTypes.
5460#define SVE_TYPE(Name, Id, SingletonId) \
5461 case BuiltinType::Id:
5462#include "clang/Basic/AArch64SVEACLETypes.def"
5463#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5464#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5465#include "clang/AST/BuiltinTypes.def"
5466 return false;
5467
5468 // We cannot lower out overload sets; they might validly be resolved
5469 // by the call machinery.
5470 case BuiltinType::Overload:
5471 return false;
5472
5473 // Unbridged casts in ARC can be handled in some call positions and
5474 // should be left in place.
5475 case BuiltinType::ARCUnbridgedCast:
5476 return false;
5477
5478 // Pseudo-objects should be converted as soon as possible.
5479 case BuiltinType::PseudoObject:
5480 return true;
5481
5482 // The debugger mode could theoretically but currently does not try
5483 // to resolve unknown-typed arguments based on known parameter types.
5484 case BuiltinType::UnknownAny:
5485 return true;
5486
5487 // These are always invalid as call arguments and should be reported.
5488 case BuiltinType::BoundMember:
5489 case BuiltinType::BuiltinFn:
5490 case BuiltinType::OMPArraySection:
5491 return true;
5492
5493 }
5494 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5494)
;
5495}
5496
5497/// Check an argument list for placeholders that we won't try to
5498/// handle later.
5499static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5500 // Apply this processing to all the arguments at once instead of
5501 // dying at the first failure.
5502 bool hasInvalid = false;
5503 for (size_t i = 0, e = args.size(); i != e; i++) {
5504 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5505 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5506 if (result.isInvalid()) hasInvalid = true;
5507 else args[i] = result.get();
5508 } else if (hasInvalid) {
5509 (void)S.CorrectDelayedTyposInExpr(args[i]);
5510 }
5511 }
5512 return hasInvalid;
5513}
5514
5515/// If a builtin function has a pointer argument with no explicit address
5516/// space, then it should be able to accept a pointer to any address
5517/// space as input. In order to do this, we need to replace the
5518/// standard builtin declaration with one that uses the same address space
5519/// as the call.
5520///
5521/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5522/// it does not contain any pointer arguments without
5523/// an address space qualifer. Otherwise the rewritten
5524/// FunctionDecl is returned.
5525/// TODO: Handle pointer return types.
5526static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5527 FunctionDecl *FDecl,
5528 MultiExprArg ArgExprs) {
5529
5530 QualType DeclType = FDecl->getType();
5531 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5532
5533 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5534 ArgExprs.size() < FT->getNumParams())
5535 return nullptr;
5536
5537 bool NeedsNewDecl = false;
5538 unsigned i = 0;
5539 SmallVector<QualType, 8> OverloadParams;
5540
5541 for (QualType ParamType : FT->param_types()) {
5542
5543 // Convert array arguments to pointer to simplify type lookup.
5544 ExprResult ArgRes =
5545 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5546 if (ArgRes.isInvalid())
5547 return nullptr;
5548 Expr *Arg = ArgRes.get();
5549 QualType ArgType = Arg->getType();
5550 if (!ParamType->isPointerType() ||
5551 ParamType.hasAddressSpace() ||
5552 !ArgType->isPointerType() ||
5553 !ArgType->getPointeeType().hasAddressSpace()) {
5554 OverloadParams.push_back(ParamType);
5555 continue;
5556 }
5557
5558 QualType PointeeType = ParamType->getPointeeType();
5559 if (PointeeType.hasAddressSpace())
5560 continue;
5561
5562 NeedsNewDecl = true;
5563 LangAS AS = ArgType->getPointeeType().getAddressSpace();
5564
5565 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5566 OverloadParams.push_back(Context.getPointerType(PointeeType));
5567 }
5568
5569 if (!NeedsNewDecl)
5570 return nullptr;
5571
5572 FunctionProtoType::ExtProtoInfo EPI;
5573 EPI.Variadic = FT->isVariadic();
5574 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5575 OverloadParams, EPI);
5576 DeclContext *Parent = FDecl->getParent();
5577 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5578 FDecl->getLocation(),
5579 FDecl->getLocation(),
5580 FDecl->getIdentifier(),
5581 OverloadTy,
5582 /*TInfo=*/nullptr,
5583 SC_Extern, false,
5584 /*hasPrototype=*/true);
5585 SmallVector<ParmVarDecl*, 16> Params;
5586 FT = cast<FunctionProtoType>(OverloadTy);
5587 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5588 QualType ParamType = FT->getParamType(i);
5589 ParmVarDecl *Parm =
5590 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5591 SourceLocation(), nullptr, ParamType,
5592 /*TInfo=*/nullptr, SC_None, nullptr);
5593 Parm->setScopeInfo(0, i);
5594 Params.push_back(Parm);
5595 }
5596 OverloadDecl->setParams(Params);
5597 return OverloadDecl;
5598}
5599
5600static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5601 FunctionDecl *Callee,
5602 MultiExprArg ArgExprs) {
5603 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5604 // similar attributes) really don't like it when functions are called with an
5605 // invalid number of args.
5606 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5607 /*PartialOverloading=*/false) &&
5608 !Callee->isVariadic())
5609 return;
5610 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5611 return;
5612
5613 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5614 S.Diag(Fn->getBeginLoc(),
5615 isa<CXXMethodDecl>(Callee)
5616 ? diag::err_ovl_no_viable_member_function_in_call
5617 : diag::err_ovl_no_viable_function_in_call)
5618 << Callee << Callee->getSourceRange();
5619 S.Diag(Callee->getLocation(),
5620 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5621 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5622 return;
5623 }
5624}
5625
5626static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5627 const UnresolvedMemberExpr *const UME, Sema &S) {
5628
5629 const auto GetFunctionLevelDCIfCXXClass =
5630 [](Sema &S) -> const CXXRecordDecl * {
5631 const DeclContext *const DC = S.getFunctionLevelDeclContext();
5632 if (!DC || !DC->getParent())
5633 return nullptr;
5634
5635 // If the call to some member function was made from within a member
5636 // function body 'M' return return 'M's parent.
5637 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5638 return MD->getParent()->getCanonicalDecl();
5639 // else the call was made from within a default member initializer of a
5640 // class, so return the class.
5641 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5642 return RD->getCanonicalDecl();
5643 return nullptr;
5644 };
5645 // If our DeclContext is neither a member function nor a class (in the
5646 // case of a lambda in a default member initializer), we can't have an
5647 // enclosing 'this'.
5648
5649 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5650 if (!CurParentClass)
5651 return false;
5652
5653 // The naming class for implicit member functions call is the class in which
5654 // name lookup starts.
5655 const CXXRecordDecl *const NamingClass =
5656 UME->getNamingClass()->getCanonicalDecl();
5657 assert(NamingClass && "Must have naming class even for implicit access")((NamingClass && "Must have naming class even for implicit access"
) ? static_cast<void> (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5657, __PRETTY_FUNCTION__))
;
5658
5659 // If the unresolved member functions were found in a 'naming class' that is
5660 // related (either the same or derived from) to the class that contains the
5661 // member function that itself contained the implicit member access.
5662
5663 return CurParentClass == NamingClass ||
5664 CurParentClass->isDerivedFrom(NamingClass);
5665}
5666
5667static void
5668tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5669 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5670
5671 if (!UME)
5672 return;
5673
5674 LambdaScopeInfo *const CurLSI = S.getCurLambda();
5675 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5676 // already been captured, or if this is an implicit member function call (if
5677 // it isn't, an attempt to capture 'this' should already have been made).
5678 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5679 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5680 return;
5681
5682 // Check if the naming class in which the unresolved members were found is
5683 // related (same as or is a base of) to the enclosing class.
5684
5685 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5686 return;
5687
5688
5689 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5690 // If the enclosing function is not dependent, then this lambda is
5691 // capture ready, so if we can capture this, do so.
5692 if (!EnclosingFunctionCtx->isDependentContext()) {
5693 // If the current lambda and all enclosing lambdas can capture 'this' -
5694 // then go ahead and capture 'this' (since our unresolved overload set
5695 // contains at least one non-static member function).
5696 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5697 S.CheckCXXThisCapture(CallLoc);
5698 } else if (S.CurContext->isDependentContext()) {
5699 // ... since this is an implicit member reference, that might potentially
5700 // involve a 'this' capture, mark 'this' for potential capture in
5701 // enclosing lambdas.
5702 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5703 CurLSI->addPotentialThisCapture(CallLoc);
5704 }
5705}
5706
5707ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5708 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5709 Expr *ExecConfig) {
5710 ExprResult Call =
5711 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5712 if (Call.isInvalid())
5713 return Call;
5714
5715 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5716 // language modes.
5717 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5718 if (ULE->hasExplicitTemplateArgs() &&
5719 ULE->decls_begin() == ULE->decls_end()) {
5720 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5721 ? diag::warn_cxx17_compat_adl_only_template_id
5722 : diag::ext_adl_only_template_id)
5723 << ULE->getName();
5724 }
5725 }
5726
5727 return Call;
5728}
5729
5730/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5731/// This provides the location of the left/right parens and a list of comma
5732/// locations.
5733ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5734 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5735 Expr *ExecConfig, bool IsExecConfig) {
5736 // Since this might be a postfix expression, get rid of ParenListExprs.
5737 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5738 if (Result.isInvalid()) return ExprError();
5739 Fn = Result.get();
5740
5741 if (checkArgsForPlaceholders(*this, ArgExprs))
5742 return ExprError();
5743
5744 if (getLangOpts().CPlusPlus) {
5745 // If this is a pseudo-destructor expression, build the call immediately.
5746 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5747 if (!ArgExprs.empty()) {
5748 // Pseudo-destructor calls should not have any arguments.
5749 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5750 << FixItHint::CreateRemoval(
5751 SourceRange(ArgExprs.front()->getBeginLoc(),
5752 ArgExprs.back()->getEndLoc()));
5753 }
5754
5755 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5756 VK_RValue, RParenLoc);
5757 }
5758 if (Fn->getType() == Context.PseudoObjectTy) {
5759 ExprResult result = CheckPlaceholderExpr(Fn);
5760 if (result.isInvalid()) return ExprError();
5761 Fn = result.get();
5762 }
5763
5764 // Determine whether this is a dependent call inside a C++ template,
5765 // in which case we won't do any semantic analysis now.
5766 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5767 if (ExecConfig) {
5768 return CUDAKernelCallExpr::Create(
5769 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5770 Context.DependentTy, VK_RValue, RParenLoc);
5771 } else {
5772
5773 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5774 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5775 Fn->getBeginLoc());
5776
5777 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5778 VK_RValue, RParenLoc);
5779 }
5780 }
5781
5782 // Determine whether this is a call to an object (C++ [over.call.object]).
5783 if (Fn->getType()->isRecordType())
5784 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5785 RParenLoc);
5786
5787 if (Fn->getType() == Context.UnknownAnyTy) {
5788 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5789 if (result.isInvalid()) return ExprError();
5790 Fn = result.get();
5791 }
5792
5793 if (Fn->getType() == Context.BoundMemberTy) {
5794 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5795 RParenLoc);
5796 }
5797 }
5798
5799 // Check for overloaded calls. This can happen even in C due to extensions.
5800 if (Fn->getType() == Context.OverloadTy) {
5801 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5802
5803 // We aren't supposed to apply this logic if there's an '&' involved.
5804 if (!find.HasFormOfMemberPointer) {
5805 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5806 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5807 VK_RValue, RParenLoc);
5808 OverloadExpr *ovl = find.Expression;
5809 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5810 return BuildOverloadedCallExpr(
5811 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5812 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5813 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5814 RParenLoc);
5815 }
5816 }
5817
5818 // If we're directly calling a function, get the appropriate declaration.
5819 if (Fn->getType() == Context.UnknownAnyTy) {
5820 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5821 if (result.isInvalid()) return ExprError();
5822 Fn = result.get();
5823 }
5824
5825 Expr *NakedFn = Fn->IgnoreParens();
5826
5827 bool CallingNDeclIndirectly = false;
5828 NamedDecl *NDecl = nullptr;
5829 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5830 if (UnOp->getOpcode() == UO_AddrOf) {
5831 CallingNDeclIndirectly = true;
5832 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5833 }
5834 }
5835
5836 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5837 NDecl = DRE->getDecl();
5838
5839 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5840 if (FDecl && FDecl->getBuiltinID()) {
5841 // Rewrite the function decl for this builtin by replacing parameters
5842 // with no explicit address space with the address space of the arguments
5843 // in ArgExprs.
5844 if ((FDecl =
5845 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5846 NDecl = FDecl;
5847 Fn = DeclRefExpr::Create(
5848 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5849 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5850 nullptr, DRE->isNonOdrUse());
5851 }
5852 }
5853 } else if (isa<MemberExpr>(NakedFn))
5854 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5855
5856 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5857 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5858 FD, /*Complain=*/true, Fn->getBeginLoc()))
5859 return ExprError();
5860
5861 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5862 return ExprError();
5863
5864 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5865 }
5866
5867 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5868 ExecConfig, IsExecConfig);
5869}
5870
5871/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5872///
5873/// __builtin_astype( value, dst type )
5874///
5875ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5876 SourceLocation BuiltinLoc,
5877 SourceLocation RParenLoc) {
5878 ExprValueKind VK = VK_RValue;
5879 ExprObjectKind OK = OK_Ordinary;
5880 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5881 QualType SrcTy = E->getType();
5882 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5883 return ExprError(Diag