Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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