Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 4842, 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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -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-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaExpr.cpp

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