clang 19.0.0git
SemaExpr.cpp
Go to the documentation of this file.
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"
17#include "clang/AST/ASTLambda.h"
20#include "clang/AST/DeclObjC.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
42#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Overload.h"
50#include "clang/Sema/Scope.h"
52#include "clang/Sema/SemaCUDA.h"
56#include "clang/Sema/Template.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/STLForwardCompat.h"
59#include "llvm/ADT/StringExtras.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/ConvertUTF.h"
62#include "llvm/Support/SaveAndRestore.h"
63#include "llvm/Support/TypeSize.h"
64#include <optional>
65
66using namespace clang;
67using namespace sema;
68
69/// Determine whether the use of this declaration is valid, without
70/// emitting diagnostics.
71bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
72 // See if this is an auto-typed variable whose initializer we are parsing.
73 if (ParsingInitForAutoVars.count(D))
74 return false;
75
76 // See if this is a deleted function.
77 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
78 if (FD->isDeleted())
79 return false;
80
81 // If the function has a deduced return type, and we can't deduce it,
82 // then we can't use it either.
83 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
84 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
85 return false;
86
87 // See if this is an aligned allocation/deallocation function that is
88 // unavailable.
89 if (TreatUnavailableAsInvalid &&
91 return false;
92 }
93
94 // See if this function is unavailable.
95 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
96 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
97 return false;
98
99 if (isa<UnresolvedUsingIfExistsDecl>(D))
100 return false;
101
102 return true;
103}
104
106 // Warn if this is used but marked unused.
107 if (const auto *A = D->getAttr<UnusedAttr>()) {
108 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
109 // should diagnose them.
110 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
111 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
112 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
113 if (DC && !DC->hasAttr<UnusedAttr>())
114 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
115 }
116 }
117}
118
119/// Emit a note explaining that this function is deleted.
121 assert(Decl && Decl->isDeleted());
122
123 if (Decl->isDefaulted()) {
124 // If the method was explicitly defaulted, point at that declaration.
125 if (!Decl->isImplicit())
126 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
127
128 // Try to diagnose why this special member function was implicitly
129 // deleted. This might fail, if that reason no longer applies.
131 return;
132 }
133
134 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
135 if (Ctor && Ctor->isInheritingConstructor())
137
138 Diag(Decl->getLocation(), diag::note_availability_specified_here)
139 << Decl << 1;
140}
141
142/// Determine whether a FunctionDecl was ever declared with an
143/// explicit storage class.
145 for (auto *I : D->redecls()) {
146 if (I->getStorageClass() != SC_None)
147 return true;
148 }
149 return false;
150}
151
152/// Check whether we're in an extern inline function and referring to a
153/// variable or function with internal linkage (C11 6.7.4p3).
154///
155/// This is only a warning because we used to silently accept this code, but
156/// in many cases it will not behave correctly. This is not enabled in C++ mode
157/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
158/// and so while there may still be user mistakes, most of the time we can't
159/// prove that there are errors.
161 const NamedDecl *D,
162 SourceLocation Loc) {
163 // This is disabled under C++; there are too many ways for this to fire in
164 // contexts where the warning is a false positive, or where it is technically
165 // correct but benign.
166 if (S.getLangOpts().CPlusPlus)
167 return;
168
169 // Check if this is an inlined function or method.
170 FunctionDecl *Current = S.getCurFunctionDecl();
171 if (!Current)
172 return;
173 if (!Current->isInlined())
174 return;
175 if (!Current->isExternallyVisible())
176 return;
177
178 // Check if the decl has internal linkage.
180 return;
181
182 // Downgrade from ExtWarn to Extension if
183 // (1) the supposedly external inline function is in the main file,
184 // and probably won't be included anywhere else.
185 // (2) the thing we're referencing is a pure function.
186 // (3) the thing we're referencing is another inline function.
187 // This last can give us false negatives, but it's better than warning on
188 // wrappers for simple C library functions.
189 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
190 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
191 if (!DowngradeWarning && UsedFn)
192 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
193
194 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
195 : diag::ext_internal_in_extern_inline)
196 << /*IsVar=*/!UsedFn << D;
197
199
200 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
201 << D;
202}
203
205 const FunctionDecl *First = Cur->getFirstDecl();
206
207 // Suggest "static" on the function, if possible.
209 SourceLocation DeclBegin = First->getSourceRange().getBegin();
210 Diag(DeclBegin, diag::note_convert_inline_to_static)
211 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
212 }
213}
214
215/// Determine whether the use of this declaration is valid, and
216/// emit any corresponding diagnostics.
217///
218/// This routine diagnoses various problems with referencing
219/// declarations that can occur when using a declaration. For example,
220/// it might warn if a deprecated or unavailable declaration is being
221/// used, or produce an error (and return true) if a C++0x deleted
222/// function is being used.
223///
224/// \returns true if there was an error (this declaration cannot be
225/// referenced), false otherwise.
226///
228 const ObjCInterfaceDecl *UnknownObjCClass,
229 bool ObjCPropertyAccess,
230 bool AvoidPartialAvailabilityChecks,
231 ObjCInterfaceDecl *ClassReceiver,
232 bool SkipTrailingRequiresClause) {
233 SourceLocation Loc = Locs.front();
234 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
235 // If there were any diagnostics suppressed by template argument deduction,
236 // emit them now.
237 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
238 if (Pos != SuppressedDiagnostics.end()) {
239 for (const PartialDiagnosticAt &Suppressed : Pos->second)
240 Diag(Suppressed.first, Suppressed.second);
241
242 // Clear out the list of suppressed diagnostics, so that we don't emit
243 // them again for this specialization. However, we don't obsolete this
244 // entry from the table, because we want to avoid ever emitting these
245 // diagnostics again.
246 Pos->second.clear();
247 }
248
249 // C++ [basic.start.main]p3:
250 // The function 'main' shall not be used within a program.
251 if (cast<FunctionDecl>(D)->isMain())
252 Diag(Loc, diag::ext_main_used);
253
254 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
255 }
256
257 // See if this is an auto-typed variable whose initializer we are parsing.
258 if (ParsingInitForAutoVars.count(D)) {
259 if (isa<BindingDecl>(D)) {
260 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
261 << D->getDeclName();
262 } else {
263 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
264 << D->getDeclName() << cast<VarDecl>(D)->getType();
265 }
266 return true;
267 }
268
269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
270 // See if this is a deleted function.
271 if (FD->isDeleted()) {
272 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
273 if (Ctor && Ctor->isInheritingConstructor())
274 Diag(Loc, diag::err_deleted_inherited_ctor_use)
275 << Ctor->getParent()
276 << Ctor->getInheritedConstructor().getConstructor()->getParent();
277 else {
278 StringLiteral *Msg = FD->getDeletedMessage();
279 Diag(Loc, diag::err_deleted_function_use)
280 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
281 }
283 return true;
284 }
285
286 // [expr.prim.id]p4
287 // A program that refers explicitly or implicitly to a function with a
288 // trailing requires-clause whose constraint-expression is not satisfied,
289 // other than to declare it, is ill-formed. [...]
290 //
291 // See if this is a function with constraints that need to be satisfied.
292 // Check this before deducing the return type, as it might instantiate the
293 // definition.
294 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
295 ConstraintSatisfaction Satisfaction;
296 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
297 /*ForOverloadResolution*/ true))
298 // A diagnostic will have already been generated (non-constant
299 // constraint expression, for example)
300 return true;
301 if (!Satisfaction.IsSatisfied) {
302 Diag(Loc,
303 diag::err_reference_to_function_with_unsatisfied_constraints)
304 << D;
305 DiagnoseUnsatisfiedConstraint(Satisfaction);
306 return true;
307 }
308 }
309
310 // If the function has a deduced return type, and we can't deduce it,
311 // then we can't use it either.
312 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
313 DeduceReturnType(FD, Loc))
314 return true;
315
316 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
317 return true;
318
319 }
320
321 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
322 // Lambdas are only default-constructible or assignable in C++2a onwards.
323 if (MD->getParent()->isLambda() &&
324 ((isa<CXXConstructorDecl>(MD) &&
325 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
326 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
327 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
328 << !isa<CXXConstructorDecl>(MD);
329 }
330 }
331
332 auto getReferencedObjCProp = [](const NamedDecl *D) ->
333 const ObjCPropertyDecl * {
334 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
335 return MD->findPropertyDecl();
336 return nullptr;
337 };
338 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
339 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
340 return true;
341 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
342 return true;
343 }
344
345 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
346 // Only the variables omp_in and omp_out are allowed in the combiner.
347 // Only the variables omp_priv and omp_orig are allowed in the
348 // initializer-clause.
349 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
350 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
351 isa<VarDecl>(D)) {
352 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
354 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
355 return true;
356 }
357
358 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
359 // List-items in map clauses on this construct may only refer to the declared
360 // variable var and entities that could be referenced by a procedure defined
361 // at the same location.
362 // [OpenMP 5.2] Also allow iterator declared variables.
363 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
364 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
365 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
367 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
368 return true;
369 }
370
371 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
372 Diag(Loc, diag::err_use_of_empty_using_if_exists);
373 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
374 return true;
375 }
376
377 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
378 AvoidPartialAvailabilityChecks, ClassReceiver);
379
380 DiagnoseUnusedOfDecl(*this, D, Loc);
381
383
384 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
385 if (getLangOpts().getFPEvalMethod() !=
388 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
389 Diag(D->getLocation(),
390 diag::err_type_available_only_in_default_eval_method)
391 << D->getName();
392 }
393
394 if (auto *VD = dyn_cast<ValueDecl>(D))
395 checkTypeSupport(VD->getType(), Loc, VD);
396
397 if (LangOpts.SYCLIsDevice ||
398 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
400 if (const auto *VD = dyn_cast<VarDecl>(D))
401 if (VD->getTLSKind() != VarDecl::TLS_None)
402 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
403 }
404
405 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
407 // C++ [expr.prim.req.nested] p3
408 // A local parameter shall only appear as an unevaluated operand
409 // (Clause 8) within the constraint-expression.
410 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
411 << D;
412 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
413 return true;
414 }
415
416 return false;
417}
418
419/// DiagnoseSentinelCalls - This routine checks whether a call or
420/// message-send is to a declaration with the sentinel attribute, and
421/// if so, it checks that the requirements of the sentinel are
422/// satisfied.
424 ArrayRef<Expr *> Args) {
425 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
426 if (!Attr)
427 return;
428
429 // The number of formal parameters of the declaration.
430 unsigned NumFormalParams;
431
432 // The kind of declaration. This is also an index into a %select in
433 // the diagnostic.
434 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
435
436 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
437 NumFormalParams = MD->param_size();
438 CalleeKind = CK_Method;
439 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
440 NumFormalParams = FD->param_size();
441 CalleeKind = CK_Function;
442 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
443 QualType Ty = VD->getType();
444 const FunctionType *Fn = nullptr;
445 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
446 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
447 if (!Fn)
448 return;
449 CalleeKind = CK_Function;
450 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
451 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
452 CalleeKind = CK_Block;
453 } else {
454 return;
455 }
456
457 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
458 NumFormalParams = proto->getNumParams();
459 else
460 NumFormalParams = 0;
461 } else {
462 return;
463 }
464
465 // "NullPos" is the number of formal parameters at the end which
466 // effectively count as part of the variadic arguments. This is
467 // useful if you would prefer to not have *any* formal parameters,
468 // but the language forces you to have at least one.
469 unsigned NullPos = Attr->getNullPos();
470 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
471 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
472
473 // The number of arguments which should follow the sentinel.
474 unsigned NumArgsAfterSentinel = Attr->getSentinel();
475
476 // If there aren't enough arguments for all the formal parameters,
477 // the sentinel, and the args after the sentinel, complain.
478 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
479 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
480 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
481 return;
482 }
483
484 // Otherwise, find the sentinel expression.
485 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
486 if (!SentinelExpr)
487 return;
488 if (SentinelExpr->isValueDependent())
489 return;
490 if (Context.isSentinelNullExpr(SentinelExpr))
491 return;
492
493 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
494 // or 'NULL' if those are actually defined in the context. Only use
495 // 'nil' for ObjC methods, where it's much more likely that the
496 // variadic arguments form a list of object pointers.
497 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
498 std::string NullValue;
499 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
500 NullValue = "nil";
501 else if (getLangOpts().CPlusPlus11)
502 NullValue = "nullptr";
503 else if (PP.isMacroDefined("NULL"))
504 NullValue = "NULL";
505 else
506 NullValue = "(void*) 0";
507
508 if (MissingNilLoc.isInvalid())
509 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
510 else
511 Diag(MissingNilLoc, diag::warn_missing_sentinel)
512 << int(CalleeKind)
513 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
514 Diag(D->getLocation(), diag::note_sentinel_here)
515 << int(CalleeKind) << Attr->getRange();
516}
517
519 return E ? E->getSourceRange() : SourceRange();
520}
521
522//===----------------------------------------------------------------------===//
523// Standard Promotions and Conversions
524//===----------------------------------------------------------------------===//
525
526/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
528 // Handle any placeholder expressions which made it here.
529 if (E->hasPlaceholderType()) {
531 if (result.isInvalid()) return ExprError();
532 E = result.get();
533 }
534
535 QualType Ty = E->getType();
536 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
537
538 if (Ty->isFunctionType()) {
539 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
540 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
542 return ExprError();
543
545 CK_FunctionToPointerDecay).get();
546 } else if (Ty->isArrayType()) {
547 // In C90 mode, arrays only promote to pointers if the array expression is
548 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
549 // type 'array of type' is converted to an expression that has type 'pointer
550 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
551 // that has type 'array of type' ...". The relevant change is "an lvalue"
552 // (C90) to "an expression" (C99).
553 //
554 // C++ 4.2p1:
555 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
556 // T" can be converted to an rvalue of type "pointer to T".
557 //
558 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
560 CK_ArrayToPointerDecay);
561 if (Res.isInvalid())
562 return ExprError();
563 E = Res.get();
564 }
565 }
566 return E;
567}
568
570 // Check to see if we are dereferencing a null pointer. If so,
571 // and if not volatile-qualified, this is undefined behavior that the
572 // optimizer will delete, so warn about it. People sometimes try to use this
573 // to get a deterministic trap and are surprised by clang's behavior. This
574 // only handles the pattern "*null", which is a very syntactic check.
575 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
576 if (UO && UO->getOpcode() == UO_Deref &&
577 UO->getSubExpr()->getType()->isPointerType()) {
578 const LangAS AS =
579 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
580 if ((!isTargetAddressSpace(AS) ||
581 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
582 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
584 !UO->getType().isVolatileQualified()) {
585 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
586 S.PDiag(diag::warn_indirection_through_null)
587 << UO->getSubExpr()->getSourceRange());
588 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
589 S.PDiag(diag::note_indirection_through_null));
590 }
591 }
592}
593
594static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
595 SourceLocation AssignLoc,
596 const Expr* RHS) {
597 const ObjCIvarDecl *IV = OIRE->getDecl();
598 if (!IV)
599 return;
600
601 DeclarationName MemberName = IV->getDeclName();
603 if (!Member || !Member->isStr("isa"))
604 return;
605
606 const Expr *Base = OIRE->getBase();
607 QualType BaseType = Base->getType();
608 if (OIRE->isArrow())
609 BaseType = BaseType->getPointeeType();
610 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
611 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
612 ObjCInterfaceDecl *ClassDeclared = nullptr;
613 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
614 if (!ClassDeclared->getSuperClass()
615 && (*ClassDeclared->ivar_begin()) == IV) {
616 if (RHS) {
617 NamedDecl *ObjectSetClass =
619 &S.Context.Idents.get("object_setClass"),
621 if (ObjectSetClass) {
622 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
623 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
625 "object_setClass(")
627 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
628 << FixItHint::CreateInsertion(RHSLocEnd, ")");
629 }
630 else
631 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
632 } else {
633 NamedDecl *ObjectGetClass =
635 &S.Context.Idents.get("object_getClass"),
637 if (ObjectGetClass)
638 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
640 "object_getClass(")
642 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
643 else
644 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
645 }
646 S.Diag(IV->getLocation(), diag::note_ivar_decl);
647 }
648 }
649}
650
652 // Handle any placeholder expressions which made it here.
653 if (E->hasPlaceholderType()) {
655 if (result.isInvalid()) return ExprError();
656 E = result.get();
657 }
658
659 // C++ [conv.lval]p1:
660 // A glvalue of a non-function, non-array type T can be
661 // converted to a prvalue.
662 if (!E->isGLValue()) return E;
663
664 QualType T = E->getType();
665 assert(!T.isNull() && "r-value conversion on typeless expression?");
666
667 // lvalue-to-rvalue conversion cannot be applied to types that decay to
668 // pointers (i.e. function or array types).
670 return E;
671
672 // We don't want to throw lvalue-to-rvalue casts on top of
673 // expressions of certain types in C++.
674 if (getLangOpts().CPlusPlus &&
675 (E->getType() == Context.OverloadTy ||
676 T->isDependentType() ||
677 T->isRecordType()))
678 return E;
679
680 // The C standard is actually really unclear on this point, and
681 // DR106 tells us what the result should be but not why. It's
682 // generally best to say that void types just doesn't undergo
683 // lvalue-to-rvalue at all. Note that expressions of unqualified
684 // 'void' type are never l-values, but qualified void can be.
685 if (T->isVoidType())
686 return E;
687
688 // OpenCL usually rejects direct accesses to values of 'half' type.
689 if (getLangOpts().OpenCL &&
690 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
691 T->isHalfType()) {
692 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
693 << 0 << T;
694 return ExprError();
695 }
696
698 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
699 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
700 &Context.Idents.get("object_getClass"),
702 if (ObjectGetClass)
703 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
704 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
706 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
707 else
708 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
709 }
710 else if (const ObjCIvarRefExpr *OIRE =
711 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
712 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
713
714 // C++ [conv.lval]p1:
715 // [...] If T is a non-class type, the type of the prvalue is the
716 // cv-unqualified version of T. Otherwise, the type of the
717 // rvalue is T.
718 //
719 // C99 6.3.2.1p2:
720 // If the lvalue has qualified type, the value has the unqualified
721 // version of the type of the lvalue; otherwise, the value has the
722 // type of the lvalue.
723 if (T.hasQualifiers())
724 T = T.getUnqualifiedType();
725
726 // Under the MS ABI, lock down the inheritance model now.
727 if (T->isMemberPointerType() &&
729 (void)isCompleteType(E->getExprLoc(), T);
730
732 if (Res.isInvalid())
733 return Res;
734 E = Res.get();
735
736 // Loading a __weak object implicitly retains the value, so we need a cleanup to
737 // balance that.
740
743
744 // C++ [conv.lval]p3:
745 // If T is cv std::nullptr_t, the result is a null pointer constant.
746 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
747 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
749
750 // C11 6.3.2.1p2:
751 // ... if the lvalue has atomic type, the value has the non-atomic version
752 // of the type of the lvalue ...
753 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
754 T = Atomic->getValueType().getUnqualifiedType();
755 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
756 nullptr, VK_PRValue, FPOptionsOverride());
757 }
758
759 return Res;
760}
761
764 if (Res.isInvalid())
765 return ExprError();
766 Res = DefaultLvalueConversion(Res.get());
767 if (Res.isInvalid())
768 return ExprError();
769 return Res;
770}
771
772/// CallExprUnaryConversions - a special case of an unary conversion
773/// performed on a function designator of a call expression.
775 QualType Ty = E->getType();
776 ExprResult Res = E;
777 // Only do implicit cast for a function type, but not for a pointer
778 // to function type.
779 if (Ty->isFunctionType()) {
781 CK_FunctionToPointerDecay);
782 if (Res.isInvalid())
783 return ExprError();
784 }
785 Res = DefaultLvalueConversion(Res.get());
786 if (Res.isInvalid())
787 return ExprError();
788 return Res.get();
789}
790
791/// UsualUnaryConversions - Performs various conversions that are common to most
792/// operators (C99 6.3). The conversions of array and function types are
793/// sometimes suppressed. For example, the array->pointer conversion doesn't
794/// apply if the array is an argument to the sizeof or address (&) operators.
795/// In these instances, this routine should *not* be called.
797 // First, convert to an r-value.
799 if (Res.isInvalid())
800 return ExprError();
801 E = Res.get();
802
803 QualType Ty = E->getType();
804 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
805
806 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
807 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
808 (getLangOpts().getFPEvalMethod() !=
811 switch (EvalMethod) {
812 default:
813 llvm_unreachable("Unrecognized float evaluation method");
814 break;
816 llvm_unreachable("Float evaluation method should be set by now");
817 break;
820 // Widen the expression to double.
821 return Ty->isComplexType()
824 CK_FloatingComplexCast)
825 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
826 break;
829 // Widen the expression to long double.
830 return Ty->isComplexType()
833 CK_FloatingComplexCast)
835 CK_FloatingCast);
836 break;
837 }
838 }
839
840 // Half FP have to be promoted to float unless it is natively supported
841 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
842 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
843
844 // Try to perform integral promotions if the object has a theoretically
845 // promotable type.
847 // C99 6.3.1.1p2:
848 //
849 // The following may be used in an expression wherever an int or
850 // unsigned int may be used:
851 // - an object or expression with an integer type whose integer
852 // conversion rank is less than or equal to the rank of int
853 // and unsigned int.
854 // - A bit-field of type _Bool, int, signed int, or unsigned int.
855 //
856 // If an int can represent all values of the original type, the
857 // value is converted to an int; otherwise, it is converted to an
858 // unsigned int. These are called the integer promotions. All
859 // other types are unchanged by the integer promotions.
860
862 if (!PTy.isNull()) {
863 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
864 return E;
865 }
868 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
869 return E;
870 }
871 }
872 return E;
873}
874
875/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
876/// do not have a prototype. Arguments that have type float or __fp16
877/// are promoted to double. All other argument types are converted by
878/// UsualUnaryConversions().
880 QualType Ty = E->getType();
881 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
882
884 if (Res.isInvalid())
885 return ExprError();
886 E = Res.get();
887
888 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
889 // promote to double.
890 // Note that default argument promotion applies only to float (and
891 // half/fp16); it does not apply to _Float16.
892 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
893 if (BTy && (BTy->getKind() == BuiltinType::Half ||
894 BTy->getKind() == BuiltinType::Float)) {
895 if (getLangOpts().OpenCL &&
896 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
897 if (BTy->getKind() == BuiltinType::Half) {
898 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
899 }
900 } else {
901 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
902 }
903 }
904 if (BTy &&
905 getLangOpts().getExtendIntArgs() ==
910 E = (Ty->isUnsignedIntegerType())
911 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
912 .get()
913 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
915 "Unexpected typesize for LongLongTy");
916 }
917
918 // C++ performs lvalue-to-rvalue conversion as a default argument
919 // promotion, even on class types, but note:
920 // C++11 [conv.lval]p2:
921 // When an lvalue-to-rvalue conversion occurs in an unevaluated
922 // operand or a subexpression thereof the value contained in the
923 // referenced object is not accessed. Otherwise, if the glvalue
924 // has a class type, the conversion copy-initializes a temporary
925 // of type T from the glvalue and the result of the conversion
926 // is a prvalue for the temporary.
927 // FIXME: add some way to gate this entire thing for correctness in
928 // potentially potentially evaluated contexts.
932 E->getExprLoc(), E);
933 if (Temp.isInvalid())
934 return ExprError();
935 E = Temp.get();
936 }
937
938 return E;
939}
940
941/// Determine the degree of POD-ness for an expression.
942/// Incomplete types are considered POD, since this check can be performed
943/// when we're in an unevaluated context.
945 if (Ty->isIncompleteType()) {
946 // C++11 [expr.call]p7:
947 // After these conversions, if the argument does not have arithmetic,
948 // enumeration, pointer, pointer to member, or class type, the program
949 // is ill-formed.
950 //
951 // Since we've already performed array-to-pointer and function-to-pointer
952 // decay, the only such type in C++ is cv void. This also handles
953 // initializer lists as variadic arguments.
954 if (Ty->isVoidType())
955 return VAK_Invalid;
956
957 if (Ty->isObjCObjectType())
958 return VAK_Invalid;
959 return VAK_Valid;
960 }
961
963 return VAK_Invalid;
964
965 if (Context.getTargetInfo().getTriple().isWasm() &&
967 return VAK_Invalid;
968 }
969
970 if (Ty.isCXX98PODType(Context))
971 return VAK_Valid;
972
973 // C++11 [expr.call]p7:
974 // Passing a potentially-evaluated argument of class type (Clause 9)
975 // having a non-trivial copy constructor, a non-trivial move constructor,
976 // or a non-trivial destructor, with no corresponding parameter,
977 // is conditionally-supported with implementation-defined semantics.
980 if (!Record->hasNonTrivialCopyConstructor() &&
981 !Record->hasNonTrivialMoveConstructor() &&
982 !Record->hasNonTrivialDestructor())
983 return VAK_ValidInCXX11;
984
985 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
986 return VAK_Valid;
987
988 if (Ty->isObjCObjectType())
989 return VAK_Invalid;
990
991 if (getLangOpts().MSVCCompat)
992 return VAK_MSVCUndefined;
993
994 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
995 // permitted to reject them. We should consider doing so.
996 return VAK_Undefined;
997}
998
1000 // Don't allow one to pass an Objective-C interface to a vararg.
1001 const QualType &Ty = E->getType();
1002 VarArgKind VAK = isValidVarArgType(Ty);
1003
1004 // Complain about passing non-POD types through varargs.
1005 switch (VAK) {
1006 case VAK_ValidInCXX11:
1008 E->getBeginLoc(), nullptr,
1009 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1010 [[fallthrough]];
1011 case VAK_Valid:
1012 if (Ty->isRecordType()) {
1013 // This is unlikely to be what the user intended. If the class has a
1014 // 'c_str' member function, the user probably meant to call that.
1015 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1016 PDiag(diag::warn_pass_class_arg_to_vararg)
1017 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1018 }
1019 break;
1020
1021 case VAK_Undefined:
1022 case VAK_MSVCUndefined:
1023 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1024 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1025 << getLangOpts().CPlusPlus11 << Ty << CT);
1026 break;
1027
1028 case VAK_Invalid:
1030 Diag(E->getBeginLoc(),
1031 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1032 << Ty << CT;
1033 else if (Ty->isObjCObjectType())
1034 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1035 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1036 << Ty << CT);
1037 else
1038 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1039 << isa<InitListExpr>(E) << Ty << CT;
1040 break;
1041 }
1042}
1043
1044/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1045/// will create a trap if the resulting type is not a POD type.
1047 FunctionDecl *FDecl) {
1048 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1049 // Strip the unbridged-cast placeholder expression off, if applicable.
1050 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1051 (CT == VariadicMethod ||
1052 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1053 E = stripARCUnbridgedCast(E);
1054
1055 // Otherwise, do normal placeholder checking.
1056 } else {
1057 ExprResult ExprRes = CheckPlaceholderExpr(E);
1058 if (ExprRes.isInvalid())
1059 return ExprError();
1060 E = ExprRes.get();
1061 }
1062 }
1063
1065 if (ExprRes.isInvalid())
1066 return ExprError();
1067
1068 // Copy blocks to the heap.
1069 if (ExprRes.get()->getType()->isBlockPointerType())
1070 maybeExtendBlockObject(ExprRes);
1071
1072 E = ExprRes.get();
1073
1074 // Diagnostics regarding non-POD argument types are
1075 // emitted along with format string checking in Sema::CheckFunctionCall().
1077 // Turn this into a trap.
1078 CXXScopeSpec SS;
1079 SourceLocation TemplateKWLoc;
1080 UnqualifiedId Name;
1081 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1082 E->getBeginLoc());
1083 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1084 /*HasTrailingLParen=*/true,
1085 /*IsAddressOfOperand=*/false);
1086 if (TrapFn.isInvalid())
1087 return ExprError();
1088
1090 std::nullopt, E->getEndLoc());
1091 if (Call.isInvalid())
1092 return ExprError();
1093
1094 ExprResult Comma =
1095 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1096 if (Comma.isInvalid())
1097 return ExprError();
1098 return Comma.get();
1099 }
1100
1101 if (!getLangOpts().CPlusPlus &&
1103 diag::err_call_incomplete_argument))
1104 return ExprError();
1105
1106 return E;
1107}
1108
1109/// Convert complex integers to complex floats and real integers to
1110/// real floats as required for complex arithmetic. Helper function of
1111/// UsualArithmeticConversions()
1112///
1113/// \return false if the integer expression is an integer type and is
1114/// successfully converted to the (complex) float type.
1116 ExprResult &ComplexExpr,
1117 QualType IntTy,
1118 QualType ComplexTy,
1119 bool SkipCast) {
1120 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1121 if (SkipCast) return false;
1122 if (IntTy->isIntegerType()) {
1123 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1124 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1125 } else {
1126 assert(IntTy->isComplexIntegerType());
1127 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1128 CK_IntegralComplexToFloatingComplex);
1129 }
1130 return false;
1131}
1132
1133// This handles complex/complex, complex/float, or float/complex.
1134// When both operands are complex, the shorter operand is converted to the
1135// type of the longer, and that is the type of the result. This corresponds
1136// to what is done when combining two real floating-point operands.
1137// The fun begins when size promotion occur across type domains.
1138// From H&S 6.3.4: When one operand is complex and the other is a real
1139// floating-point type, the less precise type is converted, within it's
1140// real or complex domain, to the precision of the other type. For example,
1141// when combining a "long double" with a "double _Complex", the
1142// "double _Complex" is promoted to "long double _Complex".
1144 QualType ShorterType,
1145 QualType LongerType,
1146 bool PromotePrecision) {
1147 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1149 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1150
1151 if (PromotePrecision) {
1152 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1153 Shorter =
1154 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1155 } else {
1156 if (LongerIsComplex)
1157 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1158 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1159 }
1160 }
1161 return Result;
1162}
1163
1164/// Handle arithmetic conversion with complex types. Helper function of
1165/// UsualArithmeticConversions()
1167 ExprResult &RHS, QualType LHSType,
1168 QualType RHSType, bool IsCompAssign) {
1169 // Handle (complex) integer types.
1170 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1171 /*SkipCast=*/false))
1172 return LHSType;
1173 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1174 /*SkipCast=*/IsCompAssign))
1175 return RHSType;
1176
1177 // Compute the rank of the two types, regardless of whether they are complex.
1178 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1179 if (Order < 0)
1180 // Promote the precision of the LHS if not an assignment.
1181 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1182 /*PromotePrecision=*/!IsCompAssign);
1183 // Promote the precision of the RHS unless it is already the same as the LHS.
1184 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1185 /*PromotePrecision=*/Order > 0);
1186}
1187
1188/// Handle arithmetic conversion from integer to float. Helper function
1189/// of UsualArithmeticConversions()
1191 ExprResult &IntExpr,
1192 QualType FloatTy, QualType IntTy,
1193 bool ConvertFloat, bool ConvertInt) {
1194 if (IntTy->isIntegerType()) {
1195 if (ConvertInt)
1196 // Convert intExpr to the lhs floating point type.
1197 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1198 CK_IntegralToFloating);
1199 return FloatTy;
1200 }
1201
1202 // Convert both sides to the appropriate complex float.
1203 assert(IntTy->isComplexIntegerType());
1204 QualType result = S.Context.getComplexType(FloatTy);
1205
1206 // _Complex int -> _Complex float
1207 if (ConvertInt)
1208 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1209 CK_IntegralComplexToFloatingComplex);
1210
1211 // float -> _Complex float
1212 if (ConvertFloat)
1213 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1214 CK_FloatingRealToComplex);
1215
1216 return result;
1217}
1218
1219/// Handle arithmethic conversion with floating point types. Helper
1220/// function of UsualArithmeticConversions()
1222 ExprResult &RHS, QualType LHSType,
1223 QualType RHSType, bool IsCompAssign) {
1224 bool LHSFloat = LHSType->isRealFloatingType();
1225 bool RHSFloat = RHSType->isRealFloatingType();
1226
1227 // N1169 4.1.4: If one of the operands has a floating type and the other
1228 // operand has a fixed-point type, the fixed-point operand
1229 // is converted to the floating type [...]
1230 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1231 if (LHSFloat)
1232 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1233 else if (!IsCompAssign)
1234 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1235 return LHSFloat ? LHSType : RHSType;
1236 }
1237
1238 // If we have two real floating types, convert the smaller operand
1239 // to the bigger result.
1240 if (LHSFloat && RHSFloat) {
1241 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1242 if (order > 0) {
1243 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1244 return LHSType;
1245 }
1246
1247 assert(order < 0 && "illegal float comparison");
1248 if (!IsCompAssign)
1249 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1250 return RHSType;
1251 }
1252
1253 if (LHSFloat) {
1254 // Half FP has to be promoted to float unless it is natively supported
1255 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1256 LHSType = S.Context.FloatTy;
1257
1258 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1259 /*ConvertFloat=*/!IsCompAssign,
1260 /*ConvertInt=*/ true);
1261 }
1262 assert(RHSFloat);
1263 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1264 /*ConvertFloat=*/ true,
1265 /*ConvertInt=*/!IsCompAssign);
1266}
1267
1268/// Diagnose attempts to convert between __float128, __ibm128 and
1269/// long double if there is no support for such conversion.
1270/// Helper function of UsualArithmeticConversions().
1271static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1272 QualType RHSType) {
1273 // No issue if either is not a floating point type.
1274 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1275 return false;
1276
1277 // No issue if both have the same 128-bit float semantics.
1278 auto *LHSComplex = LHSType->getAs<ComplexType>();
1279 auto *RHSComplex = RHSType->getAs<ComplexType>();
1280
1281 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1282 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1283
1284 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1285 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1286
1287 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1288 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1289 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1290 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1291 return false;
1292
1293 return true;
1294}
1295
1296typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1297
1298namespace {
1299/// These helper callbacks are placed in an anonymous namespace to
1300/// permit their use as function template parameters.
1301ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1302 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1303}
1304
1305ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1306 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1307 CK_IntegralComplexCast);
1308}
1309}
1310
1311/// Handle integer arithmetic conversions. Helper function of
1312/// UsualArithmeticConversions()
1313template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1315 ExprResult &RHS, QualType LHSType,
1316 QualType RHSType, bool IsCompAssign) {
1317 // The rules for this case are in C99 6.3.1.8
1318 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1319 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1320 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1321 if (LHSSigned == RHSSigned) {
1322 // Same signedness; use the higher-ranked type
1323 if (order >= 0) {
1324 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1325 return LHSType;
1326 } else if (!IsCompAssign)
1327 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1328 return RHSType;
1329 } else if (order != (LHSSigned ? 1 : -1)) {
1330 // The unsigned type has greater than or equal rank to the
1331 // signed type, so use the unsigned type
1332 if (RHSSigned) {
1333 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1334 return LHSType;
1335 } else if (!IsCompAssign)
1336 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1337 return RHSType;
1338 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1339 // The two types are different widths; if we are here, that
1340 // means the signed type is larger than the unsigned type, so
1341 // use the signed type.
1342 if (LHSSigned) {
1343 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1344 return LHSType;
1345 } else if (!IsCompAssign)
1346 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1347 return RHSType;
1348 } else {
1349 // The signed type is higher-ranked than the unsigned type,
1350 // but isn't actually any bigger (like unsigned int and long
1351 // on most 32-bit systems). Use the unsigned type corresponding
1352 // to the signed type.
1353 QualType result =
1354 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1355 RHS = (*doRHSCast)(S, RHS.get(), result);
1356 if (!IsCompAssign)
1357 LHS = (*doLHSCast)(S, LHS.get(), result);
1358 return result;
1359 }
1360}
1361
1362/// Handle conversions with GCC complex int extension. Helper function
1363/// of UsualArithmeticConversions()
1365 ExprResult &RHS, QualType LHSType,
1366 QualType RHSType,
1367 bool IsCompAssign) {
1368 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1369 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1370
1371 if (LHSComplexInt && RHSComplexInt) {
1372 QualType LHSEltType = LHSComplexInt->getElementType();
1373 QualType RHSEltType = RHSComplexInt->getElementType();
1374 QualType ScalarType =
1375 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1376 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1377
1378 return S.Context.getComplexType(ScalarType);
1379 }
1380
1381 if (LHSComplexInt) {
1382 QualType LHSEltType = LHSComplexInt->getElementType();
1383 QualType ScalarType =
1384 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1385 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1387 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1388 CK_IntegralRealToComplex);
1389
1390 return ComplexType;
1391 }
1392
1393 assert(RHSComplexInt);
1394
1395 QualType RHSEltType = RHSComplexInt->getElementType();
1396 QualType ScalarType =
1397 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1398 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1400
1401 if (!IsCompAssign)
1402 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1403 CK_IntegralRealToComplex);
1404 return ComplexType;
1405}
1406
1407/// Return the rank of a given fixed point or integer type. The value itself
1408/// doesn't matter, but the values must be increasing with proper increasing
1409/// rank as described in N1169 4.1.1.
1410static unsigned GetFixedPointRank(QualType Ty) {
1411 const auto *BTy = Ty->getAs<BuiltinType>();
1412 assert(BTy && "Expected a builtin type.");
1413
1414 switch (BTy->getKind()) {
1415 case BuiltinType::ShortFract:
1416 case BuiltinType::UShortFract:
1417 case BuiltinType::SatShortFract:
1418 case BuiltinType::SatUShortFract:
1419 return 1;
1420 case BuiltinType::Fract:
1421 case BuiltinType::UFract:
1422 case BuiltinType::SatFract:
1423 case BuiltinType::SatUFract:
1424 return 2;
1425 case BuiltinType::LongFract:
1426 case BuiltinType::ULongFract:
1427 case BuiltinType::SatLongFract:
1428 case BuiltinType::SatULongFract:
1429 return 3;
1430 case BuiltinType::ShortAccum:
1431 case BuiltinType::UShortAccum:
1432 case BuiltinType::SatShortAccum:
1433 case BuiltinType::SatUShortAccum:
1434 return 4;
1435 case BuiltinType::Accum:
1436 case BuiltinType::UAccum:
1437 case BuiltinType::SatAccum:
1438 case BuiltinType::SatUAccum:
1439 return 5;
1440 case BuiltinType::LongAccum:
1441 case BuiltinType::ULongAccum:
1442 case BuiltinType::SatLongAccum:
1443 case BuiltinType::SatULongAccum:
1444 return 6;
1445 default:
1446 if (BTy->isInteger())
1447 return 0;
1448 llvm_unreachable("Unexpected fixed point or integer type");
1449 }
1450}
1451
1452/// handleFixedPointConversion - Fixed point operations between fixed
1453/// point types and integers or other fixed point types do not fall under
1454/// usual arithmetic conversion since these conversions could result in loss
1455/// of precsision (N1169 4.1.4). These operations should be calculated with
1456/// the full precision of their result type (N1169 4.1.6.2.1).
1458 QualType RHSTy) {
1459 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1460 "Expected at least one of the operands to be a fixed point type");
1461 assert((LHSTy->isFixedPointOrIntegerType() ||
1462 RHSTy->isFixedPointOrIntegerType()) &&
1463 "Special fixed point arithmetic operation conversions are only "
1464 "applied to ints or other fixed point types");
1465
1466 // If one operand has signed fixed-point type and the other operand has
1467 // unsigned fixed-point type, then the unsigned fixed-point operand is
1468 // converted to its corresponding signed fixed-point type and the resulting
1469 // type is the type of the converted operand.
1470 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1472 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1474
1475 // The result type is the type with the highest rank, whereby a fixed-point
1476 // conversion rank is always greater than an integer conversion rank; if the
1477 // type of either of the operands is a saturating fixedpoint type, the result
1478 // type shall be the saturating fixed-point type corresponding to the type
1479 // with the highest rank; the resulting value is converted (taking into
1480 // account rounding and overflow) to the precision of the resulting type.
1481 // Same ranks between signed and unsigned types are resolved earlier, so both
1482 // types are either signed or both unsigned at this point.
1483 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1484 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1485
1486 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1487
1489 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1490
1491 return ResultTy;
1492}
1493
1494/// Check that the usual arithmetic conversions can be performed on this pair of
1495/// expressions that might be of enumeration type.
1497 SourceLocation Loc,
1498 Sema::ArithConvKind ACK) {
1499 // C++2a [expr.arith.conv]p1:
1500 // If one operand is of enumeration type and the other operand is of a
1501 // different enumeration type or a floating-point type, this behavior is
1502 // deprecated ([depr.arith.conv.enum]).
1503 //
1504 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1505 // Eventually we will presumably reject these cases (in C++23 onwards?).
1507 R = RHS->getEnumCoercedType(S.Context);
1508 bool LEnum = L->isUnscopedEnumerationType(),
1509 REnum = R->isUnscopedEnumerationType();
1510 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1511 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1512 (REnum && L->isFloatingType())) {
1513 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1514 ? diag::err_arith_conv_enum_float_cxx26
1515 : S.getLangOpts().CPlusPlus20
1516 ? diag::warn_arith_conv_enum_float_cxx20
1517 : diag::warn_arith_conv_enum_float)
1518 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1519 << L << R;
1520 } else if (!IsCompAssign && LEnum && REnum &&
1522 unsigned DiagID;
1523 // In C++ 26, usual arithmetic conversions between 2 different enum types
1524 // are ill-formed.
1525 if (S.getLangOpts().CPlusPlus26)
1526 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1527 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1528 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1529 // If either enumeration type is unnamed, it's less likely that the
1530 // user cares about this, but this situation is still deprecated in
1531 // C++2a. Use a different warning group.
1532 DiagID = S.getLangOpts().CPlusPlus20
1533 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1534 : diag::warn_arith_conv_mixed_anon_enum_types;
1535 } else if (ACK == Sema::ACK_Conditional) {
1536 // Conditional expressions are separated out because they have
1537 // historically had a different warning flag.
1538 DiagID = S.getLangOpts().CPlusPlus20
1539 ? diag::warn_conditional_mixed_enum_types_cxx20
1540 : diag::warn_conditional_mixed_enum_types;
1541 } else if (ACK == Sema::ACK_Comparison) {
1542 // Comparison expressions are separated out because they have
1543 // historically had a different warning flag.
1544 DiagID = S.getLangOpts().CPlusPlus20
1545 ? diag::warn_comparison_mixed_enum_types_cxx20
1546 : diag::warn_comparison_mixed_enum_types;
1547 } else {
1548 DiagID = S.getLangOpts().CPlusPlus20
1549 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1550 : diag::warn_arith_conv_mixed_enum_types;
1551 }
1552 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1553 << (int)ACK << L << R;
1554 }
1555}
1556
1557/// UsualArithmeticConversions - Performs various conversions that are common to
1558/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1559/// routine returns the first non-arithmetic type found. The client is
1560/// responsible for emitting appropriate error diagnostics.
1562 SourceLocation Loc,
1563 ArithConvKind ACK) {
1564 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1565
1566 if (ACK != ACK_CompAssign) {
1567 LHS = UsualUnaryConversions(LHS.get());
1568 if (LHS.isInvalid())
1569 return QualType();
1570 }
1571
1572 RHS = UsualUnaryConversions(RHS.get());
1573 if (RHS.isInvalid())
1574 return QualType();
1575
1576 // For conversion purposes, we ignore any qualifiers.
1577 // For example, "const float" and "float" are equivalent.
1578 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1579 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1580
1581 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1582 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1583 LHSType = AtomicLHS->getValueType();
1584
1585 // If both types are identical, no conversion is needed.
1586 if (Context.hasSameType(LHSType, RHSType))
1587 return Context.getCommonSugaredType(LHSType, RHSType);
1588
1589 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1590 // The caller can deal with this (e.g. pointer + int).
1591 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1592 return QualType();
1593
1594 // Apply unary and bitfield promotions to the LHS's type.
1595 QualType LHSUnpromotedType = LHSType;
1596 if (Context.isPromotableIntegerType(LHSType))
1597 LHSType = Context.getPromotedIntegerType(LHSType);
1598 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1599 if (!LHSBitfieldPromoteTy.isNull())
1600 LHSType = LHSBitfieldPromoteTy;
1601 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1602 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1603
1604 // If both types are identical, no conversion is needed.
1605 if (Context.hasSameType(LHSType, RHSType))
1606 return Context.getCommonSugaredType(LHSType, RHSType);
1607
1608 // At this point, we have two different arithmetic types.
1609
1610 // Diagnose attempts to convert between __ibm128, __float128 and long double
1611 // where such conversions currently can't be handled.
1612 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1613 return QualType();
1614
1615 // Handle complex types first (C99 6.3.1.8p1).
1616 if (LHSType->isComplexType() || RHSType->isComplexType())
1617 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1618 ACK == ACK_CompAssign);
1619
1620 // Now handle "real" floating types (i.e. float, double, long double).
1621 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1622 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1623 ACK == ACK_CompAssign);
1624
1625 // Handle GCC complex int extension.
1626 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1627 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1628 ACK == ACK_CompAssign);
1629
1630 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1631 return handleFixedPointConversion(*this, LHSType, RHSType);
1632
1633 // Finally, we have two differing integer types.
1634 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1635 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1636}
1637
1638//===----------------------------------------------------------------------===//
1639// Semantic Analysis for various Expression Types
1640//===----------------------------------------------------------------------===//
1641
1642
1644 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1645 bool PredicateIsExpr, void *ControllingExprOrType,
1646 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1647 unsigned NumAssocs = ArgTypes.size();
1648 assert(NumAssocs == ArgExprs.size());
1649
1650 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1651 for (unsigned i = 0; i < NumAssocs; ++i) {
1652 if (ArgTypes[i])
1653 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1654 else
1655 Types[i] = nullptr;
1656 }
1657
1658 // If we have a controlling type, we need to convert it from a parsed type
1659 // into a semantic type and then pass that along.
1660 if (!PredicateIsExpr) {
1661 TypeSourceInfo *ControllingType;
1662 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1663 &ControllingType);
1664 assert(ControllingType && "couldn't get the type out of the parser");
1665 ControllingExprOrType = ControllingType;
1666 }
1667
1669 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1670 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1671 delete [] Types;
1672 return ER;
1673}
1674
1676 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1677 bool PredicateIsExpr, void *ControllingExprOrType,
1679 unsigned NumAssocs = Types.size();
1680 assert(NumAssocs == Exprs.size());
1681 assert(ControllingExprOrType &&
1682 "Must have either a controlling expression or a controlling type");
1683
1684 Expr *ControllingExpr = nullptr;
1685 TypeSourceInfo *ControllingType = nullptr;
1686 if (PredicateIsExpr) {
1687 // Decay and strip qualifiers for the controlling expression type, and
1688 // handle placeholder type replacement. See committee discussion from WG14
1689 // DR423.
1693 reinterpret_cast<Expr *>(ControllingExprOrType));
1694 if (R.isInvalid())
1695 return ExprError();
1696 ControllingExpr = R.get();
1697 } else {
1698 // The extension form uses the type directly rather than converting it.
1699 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1700 if (!ControllingType)
1701 return ExprError();
1702 }
1703
1704 bool TypeErrorFound = false,
1705 IsResultDependent = ControllingExpr
1706 ? ControllingExpr->isTypeDependent()
1707 : ControllingType->getType()->isDependentType(),
1708 ContainsUnexpandedParameterPack =
1709 ControllingExpr
1710 ? ControllingExpr->containsUnexpandedParameterPack()
1711 : ControllingType->getType()->containsUnexpandedParameterPack();
1712
1713 // The controlling expression is an unevaluated operand, so side effects are
1714 // likely unintended.
1715 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1716 ControllingExpr->HasSideEffects(Context, false))
1717 Diag(ControllingExpr->getExprLoc(),
1718 diag::warn_side_effects_unevaluated_context);
1719
1720 for (unsigned i = 0; i < NumAssocs; ++i) {
1721 if (Exprs[i]->containsUnexpandedParameterPack())
1722 ContainsUnexpandedParameterPack = true;
1723
1724 if (Types[i]) {
1725 if (Types[i]->getType()->containsUnexpandedParameterPack())
1726 ContainsUnexpandedParameterPack = true;
1727
1728 if (Types[i]->getType()->isDependentType()) {
1729 IsResultDependent = true;
1730 } else {
1731 // We relax the restriction on use of incomplete types and non-object
1732 // types with the type-based extension of _Generic. Allowing incomplete
1733 // objects means those can be used as "tags" for a type-safe way to map
1734 // to a value. Similarly, matching on function types rather than
1735 // function pointer types can be useful. However, the restriction on VM
1736 // types makes sense to retain as there are open questions about how
1737 // the selection can be made at compile time.
1738 //
1739 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1740 // complete object type other than a variably modified type."
1741 unsigned D = 0;
1742 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1743 D = diag::err_assoc_type_incomplete;
1744 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1745 D = diag::err_assoc_type_nonobject;
1746 else if (Types[i]->getType()->isVariablyModifiedType())
1747 D = diag::err_assoc_type_variably_modified;
1748 else if (ControllingExpr) {
1749 // Because the controlling expression undergoes lvalue conversion,
1750 // array conversion, and function conversion, an association which is
1751 // of array type, function type, or is qualified can never be
1752 // reached. We will warn about this so users are less surprised by
1753 // the unreachable association. However, we don't have to handle
1754 // function types; that's not an object type, so it's handled above.
1755 //
1756 // The logic is somewhat different for C++ because C++ has different
1757 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1758 // If T is a non-class type, the type of the prvalue is the cv-
1759 // unqualified version of T. Otherwise, the type of the prvalue is T.
1760 // The result of these rules is that all qualified types in an
1761 // association in C are unreachable, and in C++, only qualified non-
1762 // class types are unreachable.
1763 //
1764 // NB: this does not apply when the first operand is a type rather
1765 // than an expression, because the type form does not undergo
1766 // conversion.
1767 unsigned Reason = 0;
1768 QualType QT = Types[i]->getType();
1769 if (QT->isArrayType())
1770 Reason = 1;
1771 else if (QT.hasQualifiers() &&
1772 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1773 Reason = 2;
1774
1775 if (Reason)
1776 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1777 diag::warn_unreachable_association)
1778 << QT << (Reason - 1);
1779 }
1780
1781 if (D != 0) {
1782 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1783 << Types[i]->getTypeLoc().getSourceRange()
1784 << Types[i]->getType();
1785 TypeErrorFound = true;
1786 }
1787
1788 // C11 6.5.1.1p2 "No two generic associations in the same generic
1789 // selection shall specify compatible types."
1790 for (unsigned j = i+1; j < NumAssocs; ++j)
1791 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1792 Context.typesAreCompatible(Types[i]->getType(),
1793 Types[j]->getType())) {
1794 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1795 diag::err_assoc_compatible_types)
1796 << Types[j]->getTypeLoc().getSourceRange()
1797 << Types[j]->getType()
1798 << Types[i]->getType();
1799 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1800 diag::note_compat_assoc)
1801 << Types[i]->getTypeLoc().getSourceRange()
1802 << Types[i]->getType();
1803 TypeErrorFound = true;
1804 }
1805 }
1806 }
1807 }
1808 if (TypeErrorFound)
1809 return ExprError();
1810
1811 // If we determined that the generic selection is result-dependent, don't
1812 // try to compute the result expression.
1813 if (IsResultDependent) {
1814 if (ControllingExpr)
1815 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1816 Types, Exprs, DefaultLoc, RParenLoc,
1817 ContainsUnexpandedParameterPack);
1818 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1819 Exprs, DefaultLoc, RParenLoc,
1820 ContainsUnexpandedParameterPack);
1821 }
1822
1823 SmallVector<unsigned, 1> CompatIndices;
1824 unsigned DefaultIndex = -1U;
1825 // Look at the canonical type of the controlling expression in case it was a
1826 // deduced type like __auto_type. However, when issuing diagnostics, use the
1827 // type the user wrote in source rather than the canonical one.
1828 for (unsigned i = 0; i < NumAssocs; ++i) {
1829 if (!Types[i])
1830 DefaultIndex = i;
1831 else if (ControllingExpr &&
1833 ControllingExpr->getType().getCanonicalType(),
1834 Types[i]->getType()))
1835 CompatIndices.push_back(i);
1836 else if (ControllingType &&
1838 ControllingType->getType().getCanonicalType(),
1839 Types[i]->getType()))
1840 CompatIndices.push_back(i);
1841 }
1842
1843 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1844 TypeSourceInfo *ControllingType) {
1845 // We strip parens here because the controlling expression is typically
1846 // parenthesized in macro definitions.
1847 if (ControllingExpr)
1848 ControllingExpr = ControllingExpr->IgnoreParens();
1849
1850 SourceRange SR = ControllingExpr
1851 ? ControllingExpr->getSourceRange()
1852 : ControllingType->getTypeLoc().getSourceRange();
1853 QualType QT = ControllingExpr ? ControllingExpr->getType()
1854 : ControllingType->getType();
1855
1856 return std::make_pair(SR, QT);
1857 };
1858
1859 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1860 // type compatible with at most one of the types named in its generic
1861 // association list."
1862 if (CompatIndices.size() > 1) {
1863 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1864 SourceRange SR = P.first;
1865 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1866 << SR << P.second << (unsigned)CompatIndices.size();
1867 for (unsigned I : CompatIndices) {
1868 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1869 diag::note_compat_assoc)
1870 << Types[I]->getTypeLoc().getSourceRange()
1871 << Types[I]->getType();
1872 }
1873 return ExprError();
1874 }
1875
1876 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1877 // its controlling expression shall have type compatible with exactly one of
1878 // the types named in its generic association list."
1879 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1880 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1881 SourceRange SR = P.first;
1882 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1883 return ExprError();
1884 }
1885
1886 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1887 // type name that is compatible with the type of the controlling expression,
1888 // then the result expression of the generic selection is the expression
1889 // in that generic association. Otherwise, the result expression of the
1890 // generic selection is the expression in the default generic association."
1891 unsigned ResultIndex =
1892 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1893
1894 if (ControllingExpr) {
1896 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1897 ContainsUnexpandedParameterPack, ResultIndex);
1898 }
1900 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1901 ContainsUnexpandedParameterPack, ResultIndex);
1902}
1903
1905 switch (Kind) {
1906 default:
1907 llvm_unreachable("unexpected TokenKind");
1908 case tok::kw___func__:
1909 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1910 case tok::kw___FUNCTION__:
1912 case tok::kw___FUNCDNAME__:
1913 return PredefinedIdentKind::FuncDName; // [MS]
1914 case tok::kw___FUNCSIG__:
1915 return PredefinedIdentKind::FuncSig; // [MS]
1916 case tok::kw_L__FUNCTION__:
1917 return PredefinedIdentKind::LFunction; // [MS]
1918 case tok::kw_L__FUNCSIG__:
1919 return PredefinedIdentKind::LFuncSig; // [MS]
1920 case tok::kw___PRETTY_FUNCTION__:
1922 }
1923}
1924
1925/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1926/// to determine the value of a PredefinedExpr. This can be either a
1927/// block, lambda, captured statement, function, otherwise a nullptr.
1929 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1930 DC = DC->getParent();
1931 return cast_or_null<Decl>(DC);
1932}
1933
1934/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1935/// location of the token and the offset of the ud-suffix within it.
1937 unsigned Offset) {
1938 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1939 S.getLangOpts());
1940}
1941
1942/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1943/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1945 IdentifierInfo *UDSuffix,
1946 SourceLocation UDSuffixLoc,
1947 ArrayRef<Expr*> Args,
1948 SourceLocation LitEndLoc) {
1949 assert(Args.size() <= 2 && "too many arguments for literal operator");
1950
1951 QualType ArgTy[2];
1952 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1953 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1954 if (ArgTy[ArgIdx]->isArrayType())
1955 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1956 }
1957
1958 DeclarationName OpName =
1960 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1961 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1962
1963 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1964 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1965 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1966 /*AllowStringTemplatePack*/ false,
1967 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1968 return ExprError();
1969
1970 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1971}
1972
1974 // StringToks needs backing storage as it doesn't hold array elements itself
1975 std::vector<Token> ExpandedToks;
1976 if (getLangOpts().MicrosoftExt)
1977 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1978
1979 StringLiteralParser Literal(StringToks, PP,
1981 if (Literal.hadError)
1982 return ExprError();
1983
1984 SmallVector<SourceLocation, 4> StringTokLocs;
1985 for (const Token &Tok : StringToks)
1986 StringTokLocs.push_back(Tok.getLocation());
1987
1989 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1990 &StringTokLocs[0], StringTokLocs.size());
1991
1992 if (!Literal.getUDSuffix().empty()) {
1993 SourceLocation UDSuffixLoc =
1994 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1995 Literal.getUDSuffixOffset());
1996 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1997 }
1998
1999 return Lit;
2000}
2001
2002std::vector<Token>
2004 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2005 // local macros that expand to string literals that may be concatenated.
2006 // These macros are expanded here (in Sema), because StringLiteralParser
2007 // (in Lex) doesn't know the enclosing function (because it hasn't been
2008 // parsed yet).
2009 assert(getLangOpts().MicrosoftExt);
2010
2011 // Note: Although function local macros are defined only inside functions,
2012 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2013 // expansion of macros into empty string literals without additional checks.
2014 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2015 if (!CurrentDecl)
2016 CurrentDecl = Context.getTranslationUnitDecl();
2017
2018 std::vector<Token> ExpandedToks;
2019 ExpandedToks.reserve(Toks.size());
2020 for (const Token &Tok : Toks) {
2021 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2022 assert(tok::isStringLiteral(Tok.getKind()));
2023 ExpandedToks.emplace_back(Tok);
2024 continue;
2025 }
2026 if (isa<TranslationUnitDecl>(CurrentDecl))
2027 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2028 // Stringify predefined expression
2029 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2030 << Tok.getKind();
2031 SmallString<64> Str;
2032 llvm::raw_svector_ostream OS(Str);
2033 Token &Exp = ExpandedToks.emplace_back();
2034 Exp.startToken();
2035 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2036 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2037 OS << 'L';
2038 Exp.setKind(tok::wide_string_literal);
2039 } else {
2040 Exp.setKind(tok::string_literal);
2041 }
2042 OS << '"'
2044 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2045 << '"';
2046 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2047 }
2048 return ExpandedToks;
2049}
2050
2051/// ActOnStringLiteral - The specified tokens were lexed as pasted string
2052/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2053/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2054/// multiple tokens. However, the common case is that StringToks points to one
2055/// string.
2056///
2059 assert(!StringToks.empty() && "Must have at least one string!");
2060
2061 // StringToks needs backing storage as it doesn't hold array elements itself
2062 std::vector<Token> ExpandedToks;
2063 if (getLangOpts().MicrosoftExt)
2064 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2065
2066 StringLiteralParser Literal(StringToks, PP);
2067 if (Literal.hadError)
2068 return ExprError();
2069
2070 SmallVector<SourceLocation, 4> StringTokLocs;
2071 for (const Token &Tok : StringToks)
2072 StringTokLocs.push_back(Tok.getLocation());
2073
2074 QualType CharTy = Context.CharTy;
2076 if (Literal.isWide()) {
2077 CharTy = Context.getWideCharType();
2079 } else if (Literal.isUTF8()) {
2080 if (getLangOpts().Char8)
2081 CharTy = Context.Char8Ty;
2083 } else if (Literal.isUTF16()) {
2084 CharTy = Context.Char16Ty;
2086 } else if (Literal.isUTF32()) {
2087 CharTy = Context.Char32Ty;
2089 } else if (Literal.isPascal()) {
2090 CharTy = Context.UnsignedCharTy;
2091 }
2092
2093 // Warn on initializing an array of char from a u8 string literal; this
2094 // becomes ill-formed in C++2a.
2096 !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2097 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2098
2099 // Create removals for all 'u8' prefixes in the string literal(s). This
2100 // ensures C++2a compatibility (but may change the program behavior when
2101 // built by non-Clang compilers for which the execution character set is
2102 // not always UTF-8).
2103 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2104 SourceLocation RemovalDiagLoc;
2105 for (const Token &Tok : StringToks) {
2106 if (Tok.getKind() == tok::utf8_string_literal) {
2107 if (RemovalDiagLoc.isInvalid())
2108 RemovalDiagLoc = Tok.getLocation();
2110 Tok.getLocation(),
2111 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2113 }
2114 }
2115 Diag(RemovalDiagLoc, RemovalDiag);
2116 }
2117
2118 QualType StrTy =
2119 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2120
2121 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2122 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2123 Kind, Literal.Pascal, StrTy,
2124 &StringTokLocs[0],
2125 StringTokLocs.size());
2126 if (Literal.getUDSuffix().empty())
2127 return Lit;
2128
2129 // We're building a user-defined literal.
2130 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2131 SourceLocation UDSuffixLoc =
2132 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2133 Literal.getUDSuffixOffset());
2134
2135 // Make sure we're allowed user-defined literals here.
2136 if (!UDLScope)
2137 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2138
2139 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2140 // operator "" X (str, len)
2141 QualType SizeType = Context.getSizeType();
2142
2143 DeclarationName OpName =
2145 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2146 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2147
2148 QualType ArgTy[] = {
2149 Context.getArrayDecayedType(StrTy), SizeType
2150 };
2151
2152 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2153 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2154 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2155 /*AllowStringTemplatePack*/ true,
2156 /*DiagnoseMissing*/ true, Lit)) {
2157
2158 case LOLR_Cooked: {
2159 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2160 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2161 StringTokLocs[0]);
2162 Expr *Args[] = { Lit, LenArg };
2163
2164 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2165 }
2166
2167 case LOLR_Template: {
2168 TemplateArgumentListInfo ExplicitArgs;
2169 TemplateArgument Arg(Lit);
2170 TemplateArgumentLocInfo ArgInfo(Lit);
2171 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2172 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2173 StringTokLocs.back(), &ExplicitArgs);
2174 }
2175
2177 TemplateArgumentListInfo ExplicitArgs;
2178
2179 unsigned CharBits = Context.getIntWidth(CharTy);
2180 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2181 llvm::APSInt Value(CharBits, CharIsUnsigned);
2182
2183 TemplateArgument TypeArg(CharTy);
2185 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2186
2187 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2188 Value = Lit->getCodeUnit(I);
2189 TemplateArgument Arg(Context, Value, CharTy);
2191 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2192 }
2193 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2194 StringTokLocs.back(), &ExplicitArgs);
2195 }
2196 case LOLR_Raw:
2198 llvm_unreachable("unexpected literal operator lookup result");
2199 case LOLR_Error:
2200 return ExprError();
2201 }
2202 llvm_unreachable("unexpected literal operator lookup result");
2203}
2204
2207 SourceLocation Loc,
2208 const CXXScopeSpec *SS) {
2209 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2210 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2211}
2212
2215 const DeclarationNameInfo &NameInfo,
2216 const CXXScopeSpec *SS, NamedDecl *FoundD,
2217 SourceLocation TemplateKWLoc,
2218 const TemplateArgumentListInfo *TemplateArgs) {
2221 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2222 TemplateArgs);
2223}
2224
2225// CUDA/HIP: Check whether a captured reference variable is referencing a
2226// host variable in a device or host device lambda.
2228 VarDecl *VD) {
2229 if (!S.getLangOpts().CUDA || !VD->hasInit())
2230 return false;
2231 assert(VD->getType()->isReferenceType());
2232
2233 // Check whether the reference variable is referencing a host variable.
2234 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2235 if (!DRE)
2236 return false;
2237 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2238 if (!Referee || !Referee->hasGlobalStorage() ||
2239 Referee->hasAttr<CUDADeviceAttr>())
2240 return false;
2241
2242 // Check whether the current function is a device or host device lambda.
2243 // Check whether the reference variable is a capture by getDeclContext()
2244 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2245 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2246 if (MD && MD->getParent()->isLambda() &&
2247 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2248 VD->getDeclContext() != MD)
2249 return true;
2250
2251 return false;
2252}
2253
2255 // A declaration named in an unevaluated operand never constitutes an odr-use.
2257 return NOUR_Unevaluated;
2258
2259 // C++2a [basic.def.odr]p4:
2260 // A variable x whose name appears as a potentially-evaluated expression e
2261 // is odr-used by e unless [...] x is a reference that is usable in
2262 // constant expressions.
2263 // CUDA/HIP:
2264 // If a reference variable referencing a host variable is captured in a
2265 // device or host device lambda, the value of the referee must be copied
2266 // to the capture and the reference variable must be treated as odr-use
2267 // since the value of the referee is not known at compile time and must
2268 // be loaded from the captured.
2269 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2270 if (VD->getType()->isReferenceType() &&
2271 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2273 VD->isUsableInConstantExpressions(Context))
2274 return NOUR_Constant;
2275 }
2276
2277 // All remaining non-variable cases constitute an odr-use. For variables, we
2278 // need to wait and see how the expression is used.
2279 return NOUR_None;
2280}
2281
2282/// BuildDeclRefExpr - Build an expression that references a
2283/// declaration that does not require a closure capture.
2286 const DeclarationNameInfo &NameInfo,
2287 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2288 SourceLocation TemplateKWLoc,
2289 const TemplateArgumentListInfo *TemplateArgs) {
2290 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2291 NeedToCaptureVariable(D, NameInfo.getLoc());
2292
2294 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2295 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2297
2298 // C++ [except.spec]p17:
2299 // An exception-specification is considered to be needed when:
2300 // - in an expression, the function is the unique lookup result or
2301 // the selected member of a set of overloaded functions.
2302 //
2303 // We delay doing this until after we've built the function reference and
2304 // marked it as used so that:
2305 // a) if the function is defaulted, we get errors from defining it before /
2306 // instead of errors from computing its exception specification, and
2307 // b) if the function is a defaulted comparison, we can use the body we
2308 // build when defining it as input to the exception specification
2309 // computation rather than computing a new body.
2310 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2311 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2312 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2314 }
2315 }
2316
2317 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2319 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2321
2322 const auto *FD = dyn_cast<FieldDecl>(D);
2323 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2324 FD = IFD->getAnonField();
2325 if (FD) {
2326 UnusedPrivateFields.remove(FD);
2327 // Just in case we're building an illegal pointer-to-member.
2328 if (FD->isBitField())
2330 }
2331
2332 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2333 // designates a bit-field.
2334 if (const auto *BD = dyn_cast<BindingDecl>(D))
2335 if (const auto *BE = BD->getBinding())
2336 E->setObjectKind(BE->getObjectKind());
2337
2338 return E;
2339}
2340
2341/// Decomposes the given name into a DeclarationNameInfo, its location, and
2342/// possibly a list of template arguments.
2343///
2344/// If this produces template arguments, it is permitted to call
2345/// DecomposeTemplateName.
2346///
2347/// This actually loses a lot of source location information for
2348/// non-standard name kinds; we should consider preserving that in
2349/// some way.
2350void
2353 DeclarationNameInfo &NameInfo,
2354 const TemplateArgumentListInfo *&TemplateArgs) {
2355 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2356 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2357 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2358
2359 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2360 Id.TemplateId->NumArgs);
2361 translateTemplateArguments(TemplateArgsPtr, Buffer);
2362
2363 TemplateName TName = Id.TemplateId->Template.get();
2364 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2365 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2366 TemplateArgs = &Buffer;
2367 } else {
2368 NameInfo = GetNameFromUnqualifiedId(Id);
2369 TemplateArgs = nullptr;
2370 }
2371}
2372
2374 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2376 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2377 DeclContext *Ctx =
2378 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2379 if (!TC) {
2380 // Emit a special diagnostic for failed member lookups.
2381 // FIXME: computing the declaration context might fail here (?)
2382 if (Ctx)
2383 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2384 << SS.getRange();
2385 else
2386 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2387 return;
2388 }
2389
2390 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2391 bool DroppedSpecifier =
2392 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2393 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2394 ? diag::note_implicit_param_decl
2395 : diag::note_previous_decl;
2396 if (!Ctx)
2397 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2398 SemaRef.PDiag(NoteID));
2399 else
2400 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2401 << Typo << Ctx << DroppedSpecifier
2402 << SS.getRange(),
2403 SemaRef.PDiag(NoteID));
2404}
2405
2406/// Diagnose a lookup that found results in an enclosing class during error
2407/// recovery. This usually indicates that the results were found in a dependent
2408/// base class that could not be searched as part of a template definition.
2409/// Always issues a diagnostic (though this may be only a warning in MS
2410/// compatibility mode).
2411///
2412/// Return \c true if the error is unrecoverable, or \c false if the caller
2413/// should attempt to recover using these lookup results.
2415 // During a default argument instantiation the CurContext points
2416 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2417 // function parameter list, hence add an explicit check.
2418 bool isDefaultArgument =
2419 !CodeSynthesisContexts.empty() &&
2420 CodeSynthesisContexts.back().Kind ==
2422 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2423 bool isInstance = CurMethod && CurMethod->isInstance() &&
2424 R.getNamingClass() == CurMethod->getParent() &&
2425 !isDefaultArgument;
2426
2427 // There are two ways we can find a class-scope declaration during template
2428 // instantiation that we did not find in the template definition: if it is a
2429 // member of a dependent base class, or if it is declared after the point of
2430 // use in the same class. Distinguish these by comparing the class in which
2431 // the member was found to the naming class of the lookup.
2432 unsigned DiagID = diag::err_found_in_dependent_base;
2433 unsigned NoteID = diag::note_member_declared_at;
2435 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2436 : diag::err_found_later_in_class;
2437 } else if (getLangOpts().MSVCCompat) {
2438 DiagID = diag::ext_found_in_dependent_base;
2439 NoteID = diag::note_dependent_member_use;
2440 }
2441
2442 if (isInstance) {
2443 // Give a code modification hint to insert 'this->'.
2444 Diag(R.getNameLoc(), DiagID)
2445 << R.getLookupName()
2446 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2448 } else {
2449 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2450 // they're not shadowed).
2451 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2452 }
2453
2454 for (const NamedDecl *D : R)
2455 Diag(D->getLocation(), NoteID);
2456
2457 // Return true if we are inside a default argument instantiation
2458 // and the found name refers to an instance member function, otherwise
2459 // the caller will try to create an implicit member call and this is wrong
2460 // for default arguments.
2461 //
2462 // FIXME: Is this special case necessary? We could allow the caller to
2463 // diagnose this.
2464 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2465 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2466 return true;
2467 }
2468
2469 // Tell the callee to try to recover.
2470 return false;
2471}
2472
2473/// Diagnose an empty lookup.
2474///
2475/// \return false if new lookup candidates were found
2478 TemplateArgumentListInfo *ExplicitTemplateArgs,
2479 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2480 TypoExpr **Out) {
2481 DeclarationName Name = R.getLookupName();
2482
2483 unsigned diagnostic = diag::err_undeclared_var_use;
2484 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2485 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2486 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2487 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2488 diagnostic = diag::err_undeclared_use;
2489 diagnostic_suggest = diag::err_undeclared_use_suggest;
2490 }
2491
2492 // If the original lookup was an unqualified lookup, fake an
2493 // unqualified lookup. This is useful when (for example) the
2494 // original lookup would not have found something because it was a
2495 // dependent name.
2496 DeclContext *DC =
2497 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2498 while (DC) {
2499 if (isa<CXXRecordDecl>(DC)) {
2500 LookupQualifiedName(R, DC);
2501
2502 if (!R.empty()) {
2503 // Don't give errors about ambiguities in this lookup.
2505
2506 // If there's a best viable function among the results, only mention
2507 // that one in the notes.
2508 OverloadCandidateSet Candidates(R.getNameLoc(),
2510 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2512 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2513 OR_Success) {
2514 R.clear();
2515 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2516 R.resolveKind();
2517 }
2518
2520 }
2521
2522 R.clear();
2523 }
2524
2525 DC = DC->getLookupParent();
2526 }
2527
2528 // We didn't find anything, so try to correct for a typo.
2529 TypoCorrection Corrected;
2530 if (S && Out) {
2531 SourceLocation TypoLoc = R.getNameLoc();
2532 assert(!ExplicitTemplateArgs &&
2533 "Diagnosing an empty lookup with explicit template args!");
2534 *Out = CorrectTypoDelayed(
2535 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2536 [=](const TypoCorrection &TC) {
2537 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2538 diagnostic, diagnostic_suggest);
2539 },
2540 nullptr, CTK_ErrorRecovery, LookupCtx);
2541 if (*Out)
2542 return true;
2543 } else if (S && (Corrected =
2545 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2546 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2547 bool DroppedSpecifier =
2548 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2549 R.setLookupName(Corrected.getCorrection());
2550
2551 bool AcceptableWithRecovery = false;
2552 bool AcceptableWithoutRecovery = false;
2553 NamedDecl *ND = Corrected.getFoundDecl();
2554 if (ND) {
2555 if (Corrected.isOverloaded()) {
2559 for (NamedDecl *CD : Corrected) {
2560 if (FunctionTemplateDecl *FTD =
2561 dyn_cast<FunctionTemplateDecl>(CD))
2563 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2564 Args, OCS);
2565 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2566 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2568 Args, OCS);
2569 }
2570 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2571 case OR_Success:
2572 ND = Best->FoundDecl;
2573 Corrected.setCorrectionDecl(ND);
2574 break;
2575 default:
2576 // FIXME: Arbitrarily pick the first declaration for the note.
2577 Corrected.setCorrectionDecl(ND);
2578 break;
2579 }
2580 }
2581 R.addDecl(ND);
2582 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2583 CXXRecordDecl *Record = nullptr;
2584 if (Corrected.getCorrectionSpecifier()) {
2585 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2586 Record = Ty->getAsCXXRecordDecl();
2587 }
2588 if (!Record)
2589 Record = cast<CXXRecordDecl>(
2592 }
2593
2594 auto *UnderlyingND = ND->getUnderlyingDecl();
2595 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2596 isa<FunctionTemplateDecl>(UnderlyingND);
2597 // FIXME: If we ended up with a typo for a type name or
2598 // Objective-C class name, we're in trouble because the parser
2599 // is in the wrong place to recover. Suggest the typo
2600 // correction, but don't make it a fix-it since we're not going
2601 // to recover well anyway.
2602 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2603 getAsTypeTemplateDecl(UnderlyingND) ||
2604 isa<ObjCInterfaceDecl>(UnderlyingND);
2605 } else {
2606 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2607 // because we aren't able to recover.
2608 AcceptableWithoutRecovery = true;
2609 }
2610
2611 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2612 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2613 ? diag::note_implicit_param_decl
2614 : diag::note_previous_decl;
2615 if (SS.isEmpty())
2616 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2617 PDiag(NoteID), AcceptableWithRecovery);
2618 else
2619 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2620 << Name << computeDeclContext(SS, false)
2621 << DroppedSpecifier << SS.getRange(),
2622 PDiag(NoteID), AcceptableWithRecovery);
2623
2624 // Tell the callee whether to try to recover.
2625 return !AcceptableWithRecovery;
2626 }
2627 }
2628 R.clear();
2629
2630 // Emit a special diagnostic for failed member lookups.
2631 // FIXME: computing the declaration context might fail here (?)
2632 if (!SS.isEmpty()) {
2633 Diag(R.getNameLoc(), diag::err_no_member)
2634 << Name << computeDeclContext(SS, false)
2635 << SS.getRange();
2636 return true;
2637 }
2638
2639 // Give up, we can't recover.
2640 Diag(R.getNameLoc(), diagnostic) << Name;
2641 return true;
2642}
2643
2644/// In Microsoft mode, if we are inside a template class whose parent class has
2645/// dependent base classes, and we can't resolve an unqualified identifier, then
2646/// assume the identifier is a member of a dependent base class. We can only
2647/// recover successfully in static methods, instance methods, and other contexts
2648/// where 'this' is available. This doesn't precisely match MSVC's
2649/// instantiation model, but it's close enough.
2650static Expr *
2652 DeclarationNameInfo &NameInfo,
2653 SourceLocation TemplateKWLoc,
2654 const TemplateArgumentListInfo *TemplateArgs) {
2655 // Only try to recover from lookup into dependent bases in static methods or
2656 // contexts where 'this' is available.
2657 QualType ThisType = S.getCurrentThisType();
2658 const CXXRecordDecl *RD = nullptr;
2659 if (!ThisType.isNull())
2660 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2661 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2662 RD = MD->getParent();
2663 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2664 return nullptr;
2665
2666 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2667 // is available, suggest inserting 'this->' as a fixit.
2668 SourceLocation Loc = NameInfo.getLoc();
2669 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2670 DB << NameInfo.getName() << RD;
2671
2672 if (!ThisType.isNull()) {
2673 DB << FixItHint::CreateInsertion(Loc, "this->");
2675 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2676 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2677 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2678 }
2679
2680 // Synthesize a fake NNS that points to the derived class. This will
2681 // perform name lookup during template instantiation.
2682 CXXScopeSpec SS;
2683 auto *NNS =
2684 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2685 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2687 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2688 TemplateArgs);
2689}
2690
2693 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2694 bool HasTrailingLParen, bool IsAddressOfOperand,
2696 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2697 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2698 "cannot be direct & operand and have a trailing lparen");
2699 if (SS.isInvalid())
2700 return ExprError();
2701
2702 TemplateArgumentListInfo TemplateArgsBuffer;
2703
2704 // Decompose the UnqualifiedId into the following data.
2705 DeclarationNameInfo NameInfo;
2706 const TemplateArgumentListInfo *TemplateArgs;
2707 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2708
2709 DeclarationName Name = NameInfo.getName();
2710 IdentifierInfo *II = Name.getAsIdentifierInfo();
2711 SourceLocation NameLoc = NameInfo.getLoc();
2712
2713 if (II && II->isEditorPlaceholder()) {
2714 // FIXME: When typed placeholders are supported we can create a typed
2715 // placeholder expression node.
2716 return ExprError();
2717 }
2718
2719 // C++ [temp.dep.expr]p3:
2720 // An id-expression is type-dependent if it contains:
2721 // -- an identifier that was declared with a dependent type,
2722 // (note: handled after lookup)
2723 // -- a template-id that is dependent,
2724 // (note: handled in BuildTemplateIdExpr)
2725 // -- a conversion-function-id that specifies a dependent type,
2726 // -- a nested-name-specifier that contains a class-name that
2727 // names a dependent type.
2728 // Determine whether this is a member of an unknown specialization;
2729 // we need to handle these differently.
2730 bool DependentID = false;
2731 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2732 Name.getCXXNameType()->isDependentType()) {
2733 DependentID = true;
2734 } else if (SS.isSet()) {
2735 if (DeclContext *DC = computeDeclContext(SS, false)) {
2736 if (RequireCompleteDeclContext(SS, DC))
2737 return ExprError();
2738 } else {
2739 DependentID = true;
2740 }
2741 }
2742
2743 if (DependentID)
2744 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2745 IsAddressOfOperand, TemplateArgs);
2746
2747 // BoundsSafety: This specially handles arguments of bounds attributes
2748 // appertains to a type of C struct field such that the name lookup
2749 // within a struct finds the member name, which is not the case for other
2750 // contexts in C.
2751 if (isBoundsAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2752 // See if this is reference to a field of struct.
2753 LookupResult R(*this, NameInfo, LookupMemberName);
2754 // LookupParsedName handles a name lookup from within anonymous struct.
2755 if (LookupParsedName(R, S, &SS)) {
2756 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2757 QualType type = VD->getType().getNonReferenceType();
2758 // This will eventually be translated into MemberExpr upon
2759 // the use of instantiated struct fields.
2760 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2761 }
2762 }
2763 }
2764
2765 // Perform the required lookup.
2766 LookupResult R(*this, NameInfo,
2770 if (TemplateKWLoc.isValid() || TemplateArgs) {
2771 // Lookup the template name again to correctly establish the context in
2772 // which it was found. This is really unfortunate as we already did the
2773 // lookup to determine that it was a template name in the first place. If
2774 // this becomes a performance hit, we can work harder to preserve those
2775 // results until we get here but it's likely not worth it.
2776 bool MemberOfUnknownSpecialization;
2777 AssumedTemplateKind AssumedTemplate;
2778 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2779 MemberOfUnknownSpecialization, TemplateKWLoc,
2780 &AssumedTemplate))
2781 return ExprError();
2782
2783 if (MemberOfUnknownSpecialization ||
2785 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2786 IsAddressOfOperand, TemplateArgs);
2787 } else {
2788 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2789 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2790
2791 // If the result might be in a dependent base class, this is a dependent
2792 // id-expression.
2794 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2795 IsAddressOfOperand, TemplateArgs);
2796
2797 // If this reference is in an Objective-C method, then we need to do
2798 // some special Objective-C lookup, too.
2799 if (IvarLookupFollowUp) {
2800 ExprResult E(LookupInObjCMethod(R, S, II, true));
2801 if (E.isInvalid())
2802 return ExprError();
2803
2804 if (Expr *Ex = E.getAs<Expr>())
2805 return Ex;
2806 }
2807 }
2808
2809 if (R.isAmbiguous())
2810 return ExprError();
2811
2812 // This could be an implicitly declared function reference if the language
2813 // mode allows it as a feature.
2814 if (R.empty() && HasTrailingLParen && II &&
2815 getLangOpts().implicitFunctionsAllowed()) {
2816 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2817 if (D) R.addDecl(D);
2818 }
2819
2820 // Determine whether this name might be a candidate for
2821 // argument-dependent lookup.
2822 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2823
2824 if (R.empty() && !ADL) {
2825 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2826 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2827 TemplateKWLoc, TemplateArgs))
2828 return E;
2829 }
2830
2831 // Don't diagnose an empty lookup for inline assembly.
2832 if (IsInlineAsmIdentifier)
2833 return ExprError();
2834
2835 // If this name wasn't predeclared and if this is not a function
2836 // call, diagnose the problem.
2837 TypoExpr *TE = nullptr;
2838 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2839 : nullptr);
2840 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2841 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2842 "Typo correction callback misconfigured");
2843 if (CCC) {
2844 // Make sure the callback knows what the typo being diagnosed is.
2845 CCC->setTypoName(II);
2846 if (SS.isValid())
2847 CCC->setTypoNNS(SS.getScopeRep());
2848 }
2849 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2850 // a template name, but we happen to have always already looked up the name
2851 // before we get here if it must be a template name.
2852 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2853 std::nullopt, nullptr, &TE)) {
2854 if (TE && KeywordReplacement) {
2855 auto &State = getTypoExprState(TE);
2856 auto BestTC = State.Consumer->getNextCorrection();
2857 if (BestTC.isKeyword()) {
2858 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2859 if (State.DiagHandler)
2860 State.DiagHandler(BestTC);
2861 KeywordReplacement->startToken();
2862 KeywordReplacement->setKind(II->getTokenID());
2863 KeywordReplacement->setIdentifierInfo(II);
2864 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2865 // Clean up the state associated with the TypoExpr, since it has
2866 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2867 clearDelayedTypo(TE);
2868 // Signal that a correction to a keyword was performed by returning a
2869 // valid-but-null ExprResult.
2870 return (Expr*)nullptr;
2871 }
2872 State.Consumer->resetCorrectionStream();
2873 }
2874 return TE ? TE : ExprError();
2875 }
2876
2877 assert(!R.empty() &&
2878 "DiagnoseEmptyLookup returned false but added no results");
2879
2880 // If we found an Objective-C instance variable, let
2881 // LookupInObjCMethod build the appropriate expression to
2882 // reference the ivar.
2883 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2884 R.clear();
2885 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2886 // In a hopelessly buggy code, Objective-C instance variable
2887 // lookup fails and no expression will be built to reference it.
2888 if (!E.isInvalid() && !E.get())
2889 return ExprError();
2890 return E;
2891 }
2892 }
2893
2894 // This is guaranteed from this point on.
2895 assert(!R.empty() || ADL);
2896
2897 // Check whether this might be a C++ implicit instance member access.
2898 // C++ [class.mfct.non-static]p3:
2899 // When an id-expression that is not part of a class member access
2900 // syntax and not used to form a pointer to member is used in the
2901 // body of a non-static member function of class X, if name lookup
2902 // resolves the name in the id-expression to a non-static non-type
2903 // member of some class C, the id-expression is transformed into a
2904 // class member access expression using (*this) as the
2905 // postfix-expression to the left of the . operator.
2906 //
2907 // But we don't actually need to do this for '&' operands if R
2908 // resolved to a function or overloaded function set, because the
2909 // expression is ill-formed if it actually works out to be a
2910 // non-static member function:
2911 //
2912 // C++ [expr.ref]p4:
2913 // Otherwise, if E1.E2 refers to a non-static member function. . .
2914 // [t]he expression can be used only as the left-hand operand of a
2915 // member function call.
2916 //
2917 // There are other safeguards against such uses, but it's important
2918 // to get this right here so that we don't end up making a
2919 // spuriously dependent expression if we're inside a dependent
2920 // instance method.
2921 if (getLangOpts().CPlusPlus && !R.empty() &&
2922 (*R.begin())->isCXXClassMember()) {
2923 bool MightBeImplicitMember;
2924 if (!IsAddressOfOperand)
2925 MightBeImplicitMember = true;
2926 else if (!SS.isEmpty())
2927 MightBeImplicitMember = false;
2928 else if (R.isOverloadedResult())
2929 MightBeImplicitMember = false;
2930 else if (R.isUnresolvableResult())
2931 MightBeImplicitMember = true;
2932 else
2933 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2934 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2935 isa<MSPropertyDecl>(R.getFoundDecl());
2936
2937 if (MightBeImplicitMember)
2938 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2939 R, TemplateArgs, S);
2940 }
2941
2942 if (TemplateArgs || TemplateKWLoc.isValid()) {
2943
2944 // In C++1y, if this is a variable template id, then check it
2945 // in BuildTemplateIdExpr().
2946 // The single lookup result must be a variable template declaration.
2947 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2948 Id.TemplateId->Kind == TNK_Var_template) {
2949 assert(R.getAsSingle<VarTemplateDecl>() &&
2950 "There should only be one declaration found.");
2951 }
2952
2953 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2954 }
2955
2956 return BuildDeclarationNameExpr(SS, R, ADL);
2957}
2958
2959/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2960/// declaration name, generally during template instantiation.
2961/// There's a large number of things which don't need to be done along
2962/// this path.
2964 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2965 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2966 if (NameInfo.getName().isDependentName())
2967 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2968 NameInfo, /*TemplateArgs=*/nullptr);
2969
2970 DeclContext *DC = computeDeclContext(SS, false);
2971 if (!DC)
2972 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2973 NameInfo, /*TemplateArgs=*/nullptr);
2974
2975 if (RequireCompleteDeclContext(SS, DC))
2976 return ExprError();
2977
2978 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2979 LookupQualifiedName(R, DC);
2980
2981 if (R.isAmbiguous())
2982 return ExprError();
2983
2985 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2986 NameInfo, /*TemplateArgs=*/nullptr);
2987
2988 if (R.empty()) {
2989 // Don't diagnose problems with invalid record decl, the secondary no_member
2990 // diagnostic during template instantiation is likely bogus, e.g. if a class
2991 // is invalid because it's derived from an invalid base class, then missing
2992 // members were likely supposed to be inherited.
2993 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2994 if (CD->isInvalidDecl())
2995 return ExprError();
2996 Diag(NameInfo.getLoc(), diag::err_no_member)
2997 << NameInfo.getName() << DC << SS.getRange();
2998 return ExprError();
2999 }
3000
3001 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3002 // Diagnose a missing typename if this resolved unambiguously to a type in
3003 // a dependent context. If we can recover with a type, downgrade this to
3004 // a warning in Microsoft compatibility mode.
3005 unsigned DiagID = diag::err_typename_missing;
3006 if (RecoveryTSI && getLangOpts().MSVCCompat)
3007 DiagID = diag::ext_typename_missing;
3008 SourceLocation Loc = SS.getBeginLoc();
3009 auto D = Diag(Loc, DiagID);
3010 D << SS.getScopeRep() << NameInfo.getName().getAsString()
3011 << SourceRange(Loc, NameInfo.getEndLoc());
3012
3013 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3014 // context.
3015 if (!RecoveryTSI)
3016 return ExprError();
3017
3018 // Only issue the fixit if we're prepared to recover.
3019 D << FixItHint::CreateInsertion(Loc, "typename ");
3020
3021 // Recover by pretending this was an elaborated type.
3023 TypeLocBuilder TLB;
3024 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
3025
3030
3031 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3032
3033 return ExprEmpty();
3034 }
3035
3036 // Defend against this resolving to an implicit member access. We usually
3037 // won't get here if this might be a legitimate a class member (we end up in
3038 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3039 // a pointer-to-member or in an unevaluated context in C++11.
3040 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
3042 /*TemplateKWLoc=*/SourceLocation(),
3043 R, /*TemplateArgs=*/nullptr, S);
3044
3045 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
3046}
3047
3048/// The parser has read a name in, and Sema has detected that we're currently
3049/// inside an ObjC method. Perform some additional checks and determine if we
3050/// should form a reference to an ivar.
3051///
3052/// Ideally, most of this would be done by lookup, but there's
3053/// actually quite a lot of extra work involved.
3055 IdentifierInfo *II) {
3056 SourceLocation Loc = Lookup.getNameLoc();
3057 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3058
3059 // Check for error condition which is already reported.
3060 if (!CurMethod)
3061 return DeclResult(true);
3062
3063 // There are two cases to handle here. 1) scoped lookup could have failed,
3064 // in which case we should look for an ivar. 2) scoped lookup could have
3065 // found a decl, but that decl is outside the current instance method (i.e.
3066 // a global variable). In these two cases, we do a lookup for an ivar with
3067 // this name, if the lookup sucedes, we replace it our current decl.
3068
3069 // If we're in a class method, we don't normally want to look for
3070 // ivars. But if we don't find anything else, and there's an
3071 // ivar, that's an error.
3072 bool IsClassMethod = CurMethod->isClassMethod();
3073
3074 bool LookForIvars;
3075 if (Lookup.empty())
3076 LookForIvars = true;
3077 else if (IsClassMethod)
3078 LookForIvars = false;
3079 else
3080 LookForIvars = (Lookup.isSingleResult() &&
3082 ObjCInterfaceDecl *IFace = nullptr;
3083 if (LookForIvars) {
3084 IFace = CurMethod->getClassInterface();
3085 ObjCInterfaceDecl *ClassDeclared;
3086 ObjCIvarDecl *IV = nullptr;
3087 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
3088 // Diagnose using an ivar in a class method.
3089 if (IsClassMethod) {
3090 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3091 return DeclResult(true);
3092 }
3093
3094 // Diagnose the use of an ivar outside of the declaring class.
3096 !declaresSameEntity(ClassDeclared, IFace) &&
3097 !getLangOpts().DebuggerSupport)
3098 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
3099
3100 // Success.
3101 return IV;
3102 }
3103 } else if (CurMethod->isInstanceMethod()) {
3104 // We should warn if a local variable hides an ivar.
3105 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
3106 ObjCInterfaceDecl *ClassDeclared;
3107 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
3108 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
3109 declaresSameEntity(IFace, ClassDeclared))
3110 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
3111 }
3112 }
3113 } else if (Lookup.isSingleResult() &&
3115 // If accessing a stand-alone ivar in a class method, this is an error.
3116 if (const ObjCIvarDecl *IV =
3117 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
3118 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3119 return DeclResult(true);
3120 }
3121 }
3122
3123 // Didn't encounter an error, didn't find an ivar.
3124 return DeclResult(false);
3125}
3126
3128 ObjCIvarDecl *IV) {
3129 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3130 assert(CurMethod && CurMethod->isInstanceMethod() &&
3131 "should not reference ivar from this context");
3132
3133 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3134 assert(IFace && "should not reference ivar from this context");
3135
3136 // If we're referencing an invalid decl, just return this as a silent
3137 // error node. The error diagnostic was already emitted on the decl.
3138 if (IV->isInvalidDecl())
3139 return ExprError();
3140
3141 // Check if referencing a field with __attribute__((deprecated)).
3142 if (DiagnoseUseOfDecl(IV, Loc))
3143 return ExprError();
3144
3145 // FIXME: This should use a new expr for a direct reference, don't
3146 // turn this into Self->ivar, just return a BareIVarExpr or something.
3147 IdentifierInfo &II = Context.Idents.get("self");
3148 UnqualifiedId SelfName;
3149 SelfName.setImplicitSelfParam(&II);
3150 CXXScopeSpec SelfScopeSpec;
3151 SourceLocation TemplateKWLoc;
3152 ExprResult SelfExpr =
3153 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
3154 /*HasTrailingLParen=*/false,
3155 /*IsAddressOfOperand=*/false);
3156 if (SelfExpr.isInvalid())
3157 return ExprError();
3158
3159 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
3160 if (SelfExpr.isInvalid())
3161 return ExprError();
3162
3163 MarkAnyDeclReferenced(Loc, IV, true);
3164
3165 ObjCMethodFamily MF = CurMethod->getMethodFamily();
3166 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3167 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3168 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3169
3171 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
3172 IV->getLocation(), SelfExpr.get(), true, true);
3173
3175 if (!isUnevaluatedContext() &&
3176 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3178 }
3179 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3180 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3181 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
3182
3183 return Result;
3184}
3185
3186/// The parser has read a name in, and Sema has detected that we're currently
3187/// inside an ObjC method. Perform some additional checks and determine if we
3188/// should form a reference to an ivar. If so, build an expression referencing
3189/// that ivar.
3192 IdentifierInfo *II, bool AllowBuiltinCreation) {
3193 // FIXME: Integrate this lookup step into LookupParsedName.
3194 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3195 if (Ivar.isInvalid())
3196 return ExprError();
3197 if (Ivar.isUsable())
3198 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
3199 cast<ObjCIvarDecl>(Ivar.get()));
3200
3201 if (Lookup.empty() && II && AllowBuiltinCreation)
3202 LookupBuiltin(Lookup);
3203
3204 // Sentinel value saying that we didn't do anything special.
3205 return ExprResult(false);
3206}
3207
3208/// Cast a base object to a member's actual type.
3209///
3210/// There are two relevant checks:
3211///
3212/// C++ [class.access.base]p7:
3213///
3214/// If a class member access operator [...] is used to access a non-static
3215/// data member or non-static member function, the reference is ill-formed if
3216/// the left operand [...] cannot be implicitly converted to a pointer to the
3217/// naming class of the right operand.
3218///
3219/// C++ [expr.ref]p7:
3220///
3221/// If E2 is a non-static data member or a non-static member function, the
3222/// program is ill-formed if the class of which E2 is directly a member is an
3223/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3224///
3225/// Note that the latter check does not consider access; the access of the
3226/// "real" base class is checked as appropriate when checking the access of the
3227/// member name.
3230 NestedNameSpecifier *Qualifier,
3231 NamedDecl *FoundDecl,
3232 NamedDecl *Member) {
3233 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3234 if (!RD)
3235 return From;
3236
3237 QualType DestRecordType;
3238 QualType DestType;
3239 QualType FromRecordType;
3240 QualType FromType = From->getType();
3241 bool PointerConversions = false;
3242 if (isa<FieldDecl>(Member)) {
3243 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3244 auto FromPtrType = FromType->getAs<PointerType>();
3245 DestRecordType = Context.getAddrSpaceQualType(
3246 DestRecordType, FromPtrType
3247 ? FromType->getPointeeType().getAddressSpace()
3248 : FromType.getAddressSpace());
3249
3250 if (FromPtrType) {
3251 DestType = Context.getPointerType(DestRecordType);
3252 FromRecordType = FromPtrType->getPointeeType();
3253 PointerConversions = true;
3254 } else {
3255 DestType = DestRecordType;
3256 FromRecordType = FromType;
3257 }
3258 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3259 if (!Method->isImplicitObjectMemberFunction())
3260 return From;
3261
3262 DestType = Method->getThisType().getNonReferenceType();
3263 DestRecordType = Method->getFunctionObjectParameterType();
3264
3265 if (FromType->getAs<PointerType>()) {
3266 FromRecordType = FromType->getPointeeType();
3267 PointerConversions = true;
3268 } else {
3269 FromRecordType = FromType;
3270 DestType = DestRecordType;
3271 }
3272
3273 LangAS FromAS = FromRecordType.getAddressSpace();
3274 LangAS DestAS = DestRecordType.getAddressSpace();
3275 if (FromAS != DestAS) {
3276 QualType FromRecordTypeWithoutAS =
3277 Context.removeAddrSpaceQualType(FromRecordType);
3278 QualType FromTypeWithDestAS =
3279 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3280 if (PointerConversions)
3281 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3282 From = ImpCastExprToType(From, FromTypeWithDestAS,
3283 CK_AddressSpaceConversion, From->getValueKind())
3284 .get();
3285 }
3286 } else {
3287 // No conversion necessary.
3288 return From;
3289 }
3290
3291 if (DestType->isDependentType() || FromType->isDependentType())
3292 return From;
3293
3294 // If the unqualified types are the same, no conversion is necessary.
3295 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3296 return From;
3297
3298 SourceRange FromRange = From->getSourceRange();
3299 SourceLocation FromLoc = FromRange.getBegin();
3300
3301 ExprValueKind VK = From->getValueKind();
3302
3303 // C++ [class.member.lookup]p8:
3304 // [...] Ambiguities can often be resolved by qualifying a name with its
3305 // class name.
3306 //
3307 // If the member was a qualified name and the qualified referred to a
3308 // specific base subobject type, we'll cast to that intermediate type
3309 // first and then to the object in which the member is declared. That allows
3310 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3311 //
3312 // class Base { public: int x; };
3313 // class Derived1 : public Base { };
3314 // class Derived2 : public Base { };
3315 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3316 //
3317 // void VeryDerived::f() {
3318 // x = 17; // error: ambiguous base subobjects
3319 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3320 // }
3321 if (Qualifier && Qualifier->getAsType()) {
3322 QualType QType = QualType(Qualifier->getAsType(), 0);
3323 assert(QType->isRecordType() && "lookup done with non-record type");
3324
3325 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3326
3327 // In C++98, the qualifier type doesn't actually have to be a base
3328 // type of the object type, in which case we just ignore it.
3329 // Otherwise build the appropriate casts.
3330 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3331 CXXCastPath BasePath;
3332 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3333 FromLoc, FromRange, &BasePath))
3334 return ExprError();
3335
3336 if (PointerConversions)
3337 QType = Context.getPointerType(QType);
3338 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3339 VK, &BasePath).get();
3340
3341 FromType = QType;
3342 FromRecordType = QRecordType;
3343
3344 // If the qualifier type was the same as the destination type,
3345 // we're done.
3346 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3347 return From;
3348 }
3349 }
3350
3351 CXXCastPath BasePath;
3352 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3353 FromLoc, FromRange, &BasePath,
3354 /*IgnoreAccess=*/true))
3355 return ExprError();
3356
3357 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3358 VK, &BasePath);
3359}
3360
3362 const LookupResult &R,
3363 bool HasTrailingLParen) {
3364 // Only when used directly as the postfix-expression of a call.
3365 if (!HasTrailingLParen)
3366 return false;
3367
3368 // Never if a scope specifier was provided.
3369 if (SS.isSet())
3370 return false;
3371
3372 // Only in C++ or ObjC++.
3373 if (!getLangOpts().CPlusPlus)
3374 return false;
3375
3376 // Turn off ADL when we find certain kinds of declarations during
3377 // normal lookup:
3378 for (const NamedDecl *D : R) {
3379 // C++0x [basic.lookup.argdep]p3:
3380 // -- a declaration of a class member
3381 // Since using decls preserve this property, we check this on the
3382 // original decl.
3383 if (D->isCXXClassMember())
3384 return false;
3385
3386 // C++0x [basic.lookup.argdep]p3:
3387 // -- a block-scope function declaration that is not a
3388 // using-declaration
3389 // NOTE: we also trigger this for function templates (in fact, we
3390 // don't check the decl type at all, since all other decl types
3391 // turn off ADL anyway).
3392 if (isa<UsingShadowDecl>(D))
3393 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3394 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3395 return false;
3396
3397 // C++0x [basic.lookup.argdep]p3:
3398 // -- a declaration that is neither a function or a function
3399 // template
3400 // And also for builtin functions.
3401 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3402 // But also builtin functions.
3403 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3404 return false;
3405 } else if (!isa<FunctionTemplateDecl>(D))
3406 return false;
3407 }
3408
3409 return true;
3410}
3411
3412
3413/// Diagnoses obvious problems with the use of the given declaration
3414/// as an expression. This is only actually called for lookups that
3415/// were not overloaded, and it doesn't promise that the declaration
3416/// will in fact be used.
3418 bool AcceptInvalid) {
3419 if (D->isInvalidDecl() && !AcceptInvalid)
3420 return true;
3421
3422 if (isa<TypedefNameDecl>(D)) {
3423 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3424 return true;
3425 }
3426
3427 if (isa<ObjCInterfaceDecl>(D)) {
3428 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3429 return true;
3430 }
3431
3432 if (isa<NamespaceDecl>(D)) {
3433 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3434 return true;
3435 }
3436
3437 return false;
3438}
3439
3440// Certain multiversion types should be treated as overloaded even when there is
3441// only one result.
3443 assert(R.isSingleResult() && "Expected only a single result");
3444 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3445 return FD &&
3446 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3447}
3448
3450 LookupResult &R, bool NeedsADL,
3451 bool AcceptInvalidDecl) {
3452 // If this is a single, fully-resolved result and we don't need ADL,
3453 // just build an ordinary singleton decl ref.
3454 if (!NeedsADL && R.isSingleResult() &&
3458 R.getRepresentativeDecl(), nullptr,
3459 AcceptInvalidDecl);
3460
3461 // We only need to check the declaration if there's exactly one
3462 // result, because in the overloaded case the results can only be
3463 // functions and function templates.
3465 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3466 AcceptInvalidDecl))
3467 return ExprError();
3468
3469 // Otherwise, just build an unresolved lookup expression. Suppress
3470 // any lookup-related diagnostics; we'll hash these out later, when
3471 // we've picked a target.
3473
3478 NeedsADL, R.isOverloadedResult(),
3479 R.begin(), R.end());
3480
3481 return ULE;
3482}
3483
3485 SourceLocation loc,
3486 ValueDecl *var);
3487
3488/// Complete semantic analysis for a reference to the given declaration.
3490 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3491 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3492 bool AcceptInvalidDecl) {
3493 assert(D && "Cannot refer to a NULL declaration");
3494 assert(!isa<FunctionTemplateDecl>(D) &&
3495 "Cannot refer unambiguously to a function template");
3496
3497 SourceLocation Loc = NameInfo.getLoc();
3498 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3499 // Recovery from invalid cases (e.g. D is an invalid Decl).
3500 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3501 // diagnostics, as invalid decls use int as a fallback type.
3502 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3503 }
3504
3505 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3506 // Specifically diagnose references to class templates that are missing
3507 // a template argument list.
3509 return ExprError();
3510 }
3511
3512 // Make sure that we're referring to a value.
3513 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3514 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3515 Diag(D->getLocation(), diag::note_declared_at);
3516 return ExprError();
3517 }
3518
3519 // Check whether this declaration can be used. Note that we suppress
3520 // this check when we're going to perform argument-dependent lookup
3521 // on this function name, because this might not be the function
3522 // that overload resolution actually selects.
3523 if (DiagnoseUseOfDecl(D, Loc))
3524 return ExprError();
3525
3526 auto *VD = cast<ValueDecl>(D);
3527
3528 // Only create DeclRefExpr's for valid Decl's.
3529 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3530 return ExprError();
3531
3532 // Handle members of anonymous structs and unions. If we got here,
3533 // and the reference is to a class member indirect field, then this
3534 // must be the subject of a pointer-to-member expression.
3535 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3536 IndirectField && !IndirectField->isCXXClassMember())
3538 IndirectField);
3539
3540 QualType type = VD->getType();
3541 if (type.isNull())
3542 return ExprError();
3543 ExprValueKind valueKind = VK_PRValue;
3544
3545 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3546 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3547 // is expanded by some outer '...' in the context of the use.
3548 type = type.getNonPackExpansionType();
3549
3550 switch (D->getKind()) {
3551 // Ignore all the non-ValueDecl kinds.
3552#define ABSTRACT_DECL(kind)
3553#define VALUE(type, base)
3554#define DECL(type, base) case Decl::type:
3555#include "clang/AST/DeclNodes.inc"
3556 llvm_unreachable("invalid value decl kind");
3557
3558 // These shouldn't make it here.
3559 case Decl::ObjCAtDefsField:
3560 llvm_unreachable("forming non-member reference to ivar?");
3561
3562 // Enum constants are always r-values and never references.
3563 // Unresolved using declarations are dependent.
3564 case Decl::EnumConstant:
3565 case Decl::UnresolvedUsingValue:
3566 case Decl::OMPDeclareReduction:
3567 case Decl::OMPDeclareMapper:
3568 valueKind = VK_PRValue;
3569 break;
3570
3571 // Fields and indirect fields that got here must be for
3572 // pointer-to-member expressions; we just call them l-values for
3573 // internal consistency, because this subexpression doesn't really
3574 // exist in the high-level semantics.
3575 case Decl::Field:
3576 case Decl::IndirectField:
3577 case Decl::ObjCIvar:
3578 assert((getLangOpts().CPlusPlus || isBoundsAttrContext()) &&
3579 "building reference to field in C?");
3580
3581 // These can't have reference type in well-formed programs, but
3582 // for internal consistency we do this anyway.
3583 type = type.getNonReferenceType();
3584 valueKind = VK_LValue;
3585 break;
3586
3587 // Non-type template parameters are either l-values or r-values
3588 // depending on the type.
3589 case Decl::NonTypeTemplateParm: {
3590 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3591 type = reftype->getPointeeType();
3592 valueKind = VK_LValue; // even if the parameter is an r-value reference
3593 break;
3594 }
3595
3596 // [expr.prim.id.unqual]p2:
3597 // If the entity is a template parameter object for a template
3598 // parameter of type T, the type of the expression is const T.
3599 // [...] The expression is an lvalue if the entity is a [...] template
3600 // parameter object.
3601 if (type->isRecordType()) {
3602 type = type.getUnqualifiedType().withConst();
3603 valueKind = VK_LValue;
3604 break;
3605 }
3606
3607 // For non-references, we need to strip qualifiers just in case
3608 // the template parameter was declared as 'const int' or whatever.
3609 valueKind = VK_PRValue;
3610 type = type.getUnqualifiedType();
3611 break;
3612 }
3613
3614 case Decl::Var:
3615 case Decl::VarTemplateSpecialization:
3616 case Decl::VarTemplatePartialSpecialization:
3617 case Decl::Decomposition:
3618 case Decl::OMPCapturedExpr:
3619 // In C, "extern void blah;" is valid and is an r-value.
3620 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3621 type->isVoidType()) {
3622 valueKind = VK_PRValue;
3623 break;
3624 }
3625 [[fallthrough]];
3626
3627 case Decl::ImplicitParam:
3628 case Decl::ParmVar: {
3629 // These are always l-values.
3630 valueKind = VK_LValue;
3631 type = type.getNonReferenceType();
3632
3633 // FIXME: Does the addition of const really only apply in
3634 // potentially-evaluated contexts? Since the variable isn't actually
3635 // captured in an unevaluated context, it seems that the answer is no.
3636 if (!isUnevaluatedContext()) {
3637 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3638 if (!CapturedType.isNull())
3639 type = CapturedType;
3640 }
3641
3642 break;
3643 }
3644
3645 case Decl::Binding:
3646 // These are always lvalues.
3647 valueKind = VK_LValue;
3648 type = type.getNonReferenceType();
3649 break;
3650
3651 case Decl::Function: {
3652 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3655 valueKind = VK_PRValue;
3656 break;
3657 }
3658 }
3659
3660 const FunctionType *fty = type->castAs<FunctionType>();
3661
3662 // If we're referring to a function with an __unknown_anytype
3663 // result type, make the entire expression __unknown_anytype.
3664 if (fty->getReturnType() == Context.UnknownAnyTy) {
3666 valueKind = VK_PRValue;
3667 break;
3668 }
3669
3670 // Functions are l-values in C++.
3671 if (getLangOpts().CPlusPlus) {
3672 valueKind = VK_LValue;
3673 break;
3674 }
3675
3676 // C99 DR 316 says that, if a function type comes from a
3677 // function definition (without a prototype), that type is only
3678 // used for checking compatibility. Therefore, when referencing
3679 // the function, we pretend that we don't have the full function
3680 // type.
3681 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3683 fty->getExtInfo());
3684
3685 // Functions are r-values in C.
3686 valueKind = VK_PRValue;
3687 break;
3688 }
3689
3690 case Decl::CXXDeductionGuide:
3691 llvm_unreachable("building reference to deduction guide");
3692
3693 case Decl::MSProperty:
3694 case Decl::MSGuid:
3695 case Decl::TemplateParamObject:
3696 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3697 // capture in OpenMP, or duplicated between host and device?
3698 valueKind = VK_LValue;
3699 break;
3700
3701 case Decl::UnnamedGlobalConstant:
3702 valueKind = VK_LValue;
3703 break;
3704
3705 case Decl::CXXMethod:
3706 // If we're referring to a method with an __unknown_anytype
3707 // result type, make the entire expression __unknown_anytype.
3708 // This should only be possible with a type written directly.
3709 if (const FunctionProtoType *proto =
3710 dyn_cast<FunctionProtoType>(VD->getType()))
3711 if (proto->getReturnType() == Context.UnknownAnyTy) {
3713 valueKind = VK_PRValue;
3714 break;
3715 }
3716
3717 // C++ methods are l-values if static, r-values if non-static.
3718 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3719 valueKind = VK_LValue;
3720 break;
3721 }
3722 [[fallthrough]];
3723
3724 case Decl::CXXConversion:
3725 case Decl::CXXDestructor:
3726 case Decl::CXXConstructor:
3727 valueKind = VK_PRValue;
3728 break;
3729 }
3730
3731 auto *E =
3732 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3733 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3734 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3735 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3736 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3737 // diagnostics).
3738 if (VD->isInvalidDecl() && E)
3739 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3740 return E;
3741}
3742
3743static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3745 Target.resize(CharByteWidth * (Source.size() + 1));
3746 char *ResultPtr = &Target[0];
3747 const llvm::UTF8 *ErrorPtr;
3748 bool success =
3749 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3750 (void)success;
3751 assert(success);
3752 Target.resize(ResultPtr - &Target[0]);
3753}
3754
3757 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3758 if (!currentDecl) {
3759 Diag(Loc, diag::ext_predef_outside_function);
3760 currentDecl = Context.getTranslationUnitDecl();
3761 }
3762
3763 QualType ResTy;
3764 StringLiteral *SL = nullptr;
3765 if (cast<DeclContext>(currentDecl)->isDependentContext())
3766 ResTy = Context.DependentTy;
3767 else {
3768 // Pre-defined identifiers are of type char[x], where x is the length of
3769 // the string.
3770 bool ForceElaboratedPrinting =
3771 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3772 auto Str =
3773 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3774 unsigned Length = Str.length();
3775
3776 llvm::APInt LengthI(32, Length + 1);
3779 ResTy =
3781 SmallString<32> RawChars;
3783 Str, RawChars);
3784 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3786 /*IndexTypeQuals*/ 0);
3788 /*Pascal*/ false, ResTy, Loc);
3789 } else {
3791 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3793 /*IndexTypeQuals*/ 0);
3795 /*Pascal*/ false, ResTy, Loc);
3796 }
3797 }
3798
3799 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3800 SL);
3801}
3802
3804 return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3805}
3806
3808 SmallString<16> CharBuffer;
3809 bool Invalid = false;
3810 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3811 if (Invalid)
3812 return ExprError();
3813
3814 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3815 PP, Tok.getKind());
3816 if (Literal.hadError())
3817 return ExprError();
3818
3819 QualType Ty;
3820 if (Literal.isWide())
3821 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3822 else if (Literal.isUTF8() && getLangOpts().C23)
3823 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3824 else if (Literal.isUTF8() && getLangOpts().Char8)
3825 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3826 else if (Literal.isUTF16())
3827 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3828 else if (Literal.isUTF32())
3829 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3830 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3831 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3832 else
3833 Ty = Context.CharTy; // 'x' -> char in C++;
3834 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3835
3837 if (Literal.isWide())
3839 else if (Literal.isUTF16())
3841 else if (Literal.isUTF32())
3843 else if (Literal.isUTF8())
3845
3846 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3847 Tok.getLocation());
3848
3849 if (Literal.getUDSuffix().empty())
3850 return Lit;
3851
3852 // We're building a user-defined literal.
3853 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3854 SourceLocation UDSuffixLoc =
3855 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3856
3857 // Make sure we're allowed user-defined literals here.
3858 if (!UDLScope)
3859 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3860
3861 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3862 // operator "" X (ch)
3863 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3864 Lit, Tok.getLocation());
3865}
3866
3868 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3869 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3870 Context.IntTy, Loc);
3871}
3872
3874 QualType Ty, SourceLocation Loc) {
3875 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3876
3877 using llvm::APFloat;
3878 APFloat Val(Format);
3879
3880 APFloat::opStatus result = Literal.GetFloatValue(Val);
3881
3882 // Overflow is always an error, but underflow is only an error if
3883 // we underflowed to zero (APFloat reports denormals as underflow).
3884 if ((result & APFloat::opOverflow) ||
3885 ((result & APFloat::opUnderflow) && Val.isZero())) {
3886 unsigned diagnostic;
3887 SmallString<20> buffer;
3888 if (result & APFloat::opOverflow) {
3889 diagnostic = diag::warn_float_overflow;
3890 APFloat::getLargest(Format).toString(buffer);
3891 } else {
3892 diagnostic = diag::warn_float_underflow;
3893 APFloat::getSmallest(Format).toString(buffer);
3894 }
3895
3896 S.Diag(Loc, diagnostic)
3897 << Ty
3898 << StringRef(buffer.data(), buffer.size());
3899 }
3900
3901 bool isExact = (result == APFloat::opOK);
3902 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3903}
3904
3906 assert(E && "Invalid expression");
3907
3908 if (E->isValueDependent())
3909 return false;
3910
3911 QualType QT = E->getType();
3912 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3913 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3914 return true;
3915 }
3916
3917 llvm::APSInt ValueAPS;
3919
3920 if (R.isInvalid())
3921 return true;
3922
3923 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3924 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3925 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3926 << toString(ValueAPS, 10) << ValueIsPositive;
3927 return true;
3928 }
3929
3930 return false;
3931}
3932
3934 // Fast path for a single digit (which is quite common). A single digit
3935 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3936 if (Tok.getLength() == 1) {
3937 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3938 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3939 }
3940
3941 SmallString<128> SpellingBuffer;
3942 // NumericLiteralParser wants to overread by one character. Add padding to
3943 // the buffer in case the token is copied to the buffer. If getSpelling()
3944 // returns a StringRef to the memory buffer, it should have a null char at
3945 // the EOF, so it is also safe.
3946 SpellingBuffer.resize(Tok.getLength() + 1);
3947
3948 // Get the spelling of the token, which eliminates trigraphs, etc.
3949 bool Invalid = false;
3950 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3951 if (Invalid)
3952 return ExprError();
3953
3954 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3957 if (Literal.hadError)
3958 return ExprError();
3959
3960 if (Literal.hasUDSuffix()) {
3961 // We're building a user-defined literal.
3962 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3963 SourceLocation UDSuffixLoc =
3964 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3965
3966 // Make sure we're allowed user-defined literals here.
3967 if (!UDLScope)
3968 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3969
3970 QualType CookedTy;
3971 if (Literal.isFloatingLiteral()) {
3972 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3973 // long double, the literal is treated as a call of the form
3974 // operator "" X (f L)
3975 CookedTy = Context.LongDoubleTy;
3976 } else {
3977 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3978 // unsigned long long, the literal is treated as a call of the form
3979 // operator "" X (n ULL)
3980 CookedTy = Context.UnsignedLongLongTy;
3981 }
3982
3983 DeclarationName OpName =
3985 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3986 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3987
3988 SourceLocation TokLoc = Tok.getLocation();
3989
3990 // Perform literal operator lookup to determine if we're building a raw
3991 // literal or a cooked one.
3992 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3993 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3994 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3995 /*AllowStringTemplatePack*/ false,
3996 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3998 // Lookup failure for imaginary constants isn't fatal, there's still the
3999 // GNU extension producing _Complex types.
4000 break;
4001 case LOLR_Error:
4002 return ExprError();
4003 case LOLR_Cooked: {
4004 Expr *Lit;
4005 if (Literal.isFloatingLiteral()) {
4006 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
4007 } else {
4008 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
4009 if (Literal.GetIntegerValue(ResultVal))
4010 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4011 << /* Unsigned */ 1;
4012 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
4013 Tok.getLocation());
4014 }
4015 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4016 }
4017
4018 case LOLR_Raw: {
4019 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
4020 // literal is treated as a call of the form
4021 // operator "" X ("n")
4022 unsigned Length = Literal.getUDSuffixOffset();
4025 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
4026 Expr *Lit =
4027 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
4029 /*Pascal*/ false, StrTy, &TokLoc, 1);
4030 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4031 }
4032
4033 case LOLR_Template: {
4034 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4035 // template), L is treated as a call fo the form
4036 // operator "" X <'c1', 'c2', ... 'ck'>()
4037 // where n is the source character sequence c1 c2 ... ck.
4038 TemplateArgumentListInfo ExplicitArgs;
4039 unsigned CharBits = Context.getIntWidth(Context.CharTy);
4040 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4041 llvm::APSInt Value(CharBits, CharIsUnsigned);
4042 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4043 Value = TokSpelling[I];
4046 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4047 }
4048 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
4049 &ExplicitArgs);
4050 }
4052 llvm_unreachable("unexpected literal operator lookup result");
4053 }
4054 }
4055
4056 Expr *Res;
4057
4058 if (Literal.isFixedPointLiteral()) {
4059 QualType Ty;
4060
4061 if (Literal.isAccum) {
4062 if (Literal.isHalf) {
4063 Ty = Context.ShortAccumTy;
4064 } else if (Literal.isLong) {
4065 Ty = Context.LongAccumTy;
4066 } else {
4067 Ty = Context.AccumTy;
4068 }
4069 } else if (Literal.isFract) {
4070 if (Literal.isHalf) {
4071 Ty = Context.ShortFractTy;
4072 } else if (Literal.isLong) {
4073 Ty = Context.LongFractTy;
4074 } else {
4075 Ty = Context.FractTy;
4076 }
4077 }
4078
4079 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4080
4081 bool isSigned = !Literal.isUnsigned;
4082 unsigned scale = Context.getFixedPointScale(Ty);
4083 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4084
4085 llvm::APInt Val(bit_width, 0, isSigned);
4086 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4087 bool ValIsZero = Val.isZero() && !Overflowed;
4088
4089 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4090 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4091 // Clause 6.4.4 - The value of a constant shall be in the range of
4092 // representable values for its type, with exception for constants of a
4093 // fract type with a value of exactly 1; such a constant shall denote
4094 // the maximal value for the type.
4095 --Val;
4096 else if (Val.ugt(MaxVal) || Overflowed)
4097 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4098
4100 Tok.getLocation(), scale);
4101 } else if (Literal.isFloatingLiteral()) {
4102 QualType Ty;
4103 if (Literal.isHalf){
4104 if (getLangOpts().HLSL ||
4105 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4106 Ty = Context.HalfTy;
4107 else {
4108 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4109 return ExprError();
4110 }
4111 } else if (Literal.isFloat)
4112 Ty = Context.FloatTy;
4113 else if (Literal.isLong)
4115 else if (Literal.isFloat16)
4116 Ty = Context.Float16Ty;
4117 else if (Literal.isFloat128)
4118 Ty = Context.Float128Ty;
4119 else
4120 Ty = Context.DoubleTy;
4121
4122 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4123
4124 if (Ty == Context.DoubleTy) {
4125 if (getLangOpts().SinglePrecisionConstants) {
4126 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4127 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4128 }
4129 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4130 "cl_khr_fp64", getLangOpts())) {
4131 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4132 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4134 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4135 }
4136 }
4137 } else if (!Literal.isIntegerLiteral()) {
4138 return ExprError();
4139 } else {
4140 QualType Ty;
4141
4142 // 'z/uz' literals are a C++23 feature.
4143 if (Literal.isSizeT)
4146 ? diag::warn_cxx20_compat_size_t_suffix
4147 : diag::ext_cxx23_size_t_suffix
4148 : diag::err_cxx23_size_t_suffix);
4149
4150 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4151 // but we do not currently support the suffix in C++ mode because it's not
4152 // entirely clear whether WG21 will prefer this suffix to return a library
4153 // type such as std::bit_int instead of returning a _BitInt.
4154 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
4156 ? diag::warn_c23_compat_bitint_suffix
4157 : diag::ext_c23_bitint_suffix);
4158
4159 // Get the value in the widest-possible width. What is "widest" depends on
4160 // whether the literal is a bit-precise integer or not. For a bit-precise
4161 // integer type, try to scan the source to determine how many bits are
4162 // needed to represent the value. This may seem a bit expensive, but trying
4163 // to get the integer value from an overly-wide APInt is *extremely*
4164 // expensive, so the naive approach of assuming
4165 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4166 unsigned BitsNeeded =
4167 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4168 Literal.getLiteralDigits(), Literal.getRadix())
4170 llvm::APInt ResultVal(BitsNeeded, 0);
4171
4172 if (Literal.GetIntegerValue(ResultVal)) {
4173 // If this value didn't fit into uintmax_t, error and force to ull.
4174 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4175 << /* Unsigned */ 1;
4177 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4178 "long long is not intmax_t?");
4179 } else {
4180 // If this value fits into a ULL, try to figure out what else it fits into
4181 // according to the rules of C99 6.4.4.1p5.
4182
4183 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4184 // be an unsigned int.
4185 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4186
4187 // Check from smallest to largest, picking the smallest type we can.
4188 unsigned Width = 0;
4189
4190 // Microsoft specific integer suffixes are explicitly sized.
4191 if (Literal.MicrosoftInteger) {
4192 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4193 Width = 8;
4194 Ty = Context.CharTy;
4195 } else {
4196 Width = Literal.MicrosoftInteger;
4197 Ty = Context.getIntTypeForBitwidth(Width,
4198 /*Signed=*/!Literal.isUnsigned);
4199 }
4200 }
4201
4202 // Bit-precise integer literals are automagically-sized based on the
4203 // width required by the literal.
4204 if (Literal.isBitInt) {
4205 // The signed version has one more bit for the sign value. There are no
4206 // zero-width bit-precise integers, even if the literal value is 0.
4207 Width = std::max(ResultVal.getActiveBits(), 1u) +
4208 (Literal.isUnsigned ? 0u : 1u);
4209
4210 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4211 // and reset the type to the largest supported width.
4212 unsigned int MaxBitIntWidth =
4214 if (Width > MaxBitIntWidth) {
4215 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4216 << Literal.isUnsigned;
4217 Width = MaxBitIntWidth;
4218 }
4219
4220 // Reset the result value to the smaller APInt and select the correct
4221 // type to be used. Note, we zext even for signed values because the
4222 // literal itself is always an unsigned value (a preceeding - is a
4223 // unary operator, not part of the literal).
4224 ResultVal = ResultVal.zextOrTrunc(Width);
4225 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4226 }
4227
4228 // Check C++23 size_t literals.
4229 if (Literal.isSizeT) {
4230 assert(!Literal.MicrosoftInteger &&
4231 "size_t literals can't be Microsoft literals");
4232 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4234
4235 // Does it fit in size_t?
4236 if (ResultVal.isIntN(SizeTSize)) {
4237 // Does it fit in ssize_t?
4238 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4240 else if (AllowUnsigned)
4241 Ty = Context.getSizeType();
4242 Width = SizeTSize;
4243 }
4244 }
4245
4246 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4247 !Literal.isSizeT) {
4248 // Are int/unsigned possibilities?
4249 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4250
4251 // Does it fit in a unsigned int?
4252 if (ResultVal.isIntN(IntSize)) {
4253 // Does it fit in a signed int?
4254 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4255 Ty = Context.IntTy;
4256 else if (AllowUnsigned)
4258 Width = IntSize;
4259 }
4260 }
4261
4262 // Are long/unsigned long possibilities?
4263 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4264 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4265
4266 // Does it fit in a unsigned long?
4267 if (ResultVal.isIntN(LongSize)) {
4268 // Does it fit in a signed long?
4269 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4270 Ty = Context.LongTy;
4271 else if (AllowUnsigned)
4273 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4274 // is compatible.
4275 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4276 const unsigned LongLongSize =
4278 Diag(Tok.getLocation(),
4280 ? Literal.isLong
4281 ? diag::warn_old_implicitly_unsigned_long_cxx
4282 : /*C++98 UB*/ diag::
4283 ext_old_implicitly_unsigned_long_cxx
4284 : diag::warn_old_implicitly_unsigned_long)
4285 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4286 : /*will be ill-formed*/ 1);
4288 }
4289 Width = LongSize;
4290 }
4291 }
4292
4293 // Check long long if needed.
4294 if (Ty.isNull() && !Literal.isSizeT) {
4295 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4296
4297 // Does it fit in a unsigned long long?
4298 if (ResultVal.isIntN(LongLongSize)) {
4299 // Does it fit in a signed long long?
4300 // To be compatible with MSVC, hex integer literals ending with the
4301 // LL or i64 suffix are always signed in Microsoft mode.
4302 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4303 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4304 Ty = Context.LongLongTy;
4305 else if (AllowUnsigned)
4307 Width = LongLongSize;
4308
4309 // 'long long' is a C99 or C++11 feature, whether the literal
4310 // explicitly specified 'long long' or we needed the extra width.
4311 if (getLangOpts().CPlusPlus)
4312 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4313 ? diag::warn_cxx98_compat_longlong
4314 : diag::ext_cxx11_longlong);
4315 else if (!getLangOpts().C99)
4316 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4317 }
4318 }
4319
4320 // If we still couldn't decide a type, we either have 'size_t' literal
4321 // that is out of range, or a decimal literal that does not fit in a
4322 // signed long long and has no U suffix.
4323 if (Ty.isNull()) {
4324 if (Literal.isSizeT)
4325 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4326 << Literal.isUnsigned;
4327 else
4328 Diag(Tok.getLocation(),
4329 diag::ext_integer_literal_too_large_for_signed);
4332 }
4333
4334 if (ResultVal.getBitWidth() != Width)
4335 ResultVal = ResultVal.trunc(Width);
4336 }
4337 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4338 }
4339
4340 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4341 if (Literal.isImaginary) {
4342 Res = new (Context) ImaginaryLiteral(Res,
4344
4345 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4346 }
4347 return Res;
4348}
4349
4351 assert(E && "ActOnParenExpr() missing expr");
4352 QualType ExprTy = E->getType();
4353 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4354 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4355 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4356 return new (Context) ParenExpr(L, R, E);
4357}
4358
4360 SourceLocation Loc,
4361 SourceRange ArgRange) {
4362 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4363 // scalar or vector data type argument..."
4364 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4365 // type (C99 6.2.5p18) or void.
4366 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4367 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4368 << T << ArgRange;
4369 return true;
4370 }
4371
4372 assert((T->isVoidType() || !T->isIncompleteType()) &&
4373 "Scalar types should always be complete");
4374 return false;
4375}
4376
4378 SourceLocation Loc,
4379 SourceRange ArgRange) {
4380 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4381 if (!T->isVectorType() && !T->isSizelessVectorType())
4382 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4383 << ""
4384 << "__builtin_vectorelements" << T << ArgRange;
4385
4386 return false;
4387}
4388
4390 SourceLocation Loc,
4391 SourceRange ArgRange,
4392 UnaryExprOrTypeTrait TraitKind) {
4393 // Invalid types must be hard errors for SFINAE in C++.
4394 if (S.LangOpts.CPlusPlus)
4395 return true;
4396
4397 // C99 6.5.3.4p1:
4398 if (T->isFunctionType() &&
4399 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4400 TraitKind == UETT_PreferredAlignOf)) {
4401 // sizeof(function)/alignof(function) is allowed as an extension.
4402 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4403 << getTraitSpelling(TraitKind) << ArgRange;
4404 return false;
4405 }
4406
4407 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4408 // this is an error (OpenCL v1.1 s6.3.k)
4409 if (T->isVoidType()) {
4410 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4411 : diag::ext_sizeof_alignof_void_type;
4412 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4413 return false;
4414 }
4415
4416 return true;
4417}
4418
4420 SourceLocation Loc,
4421 SourceRange ArgRange,
4422 UnaryExprOrTypeTrait TraitKind) {
4423 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4424 // runtime doesn't allow it.
4426 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4427 << T << (TraitKind == UETT_SizeOf)
4428 << ArgRange;
4429 return true;
4430 }
4431
4432 return false;
4433}
4434
4435/// Check whether E is a pointer from a decayed array type (the decayed
4436/// pointer type is equal to T) and emit a warning if it is.
4438 const Expr *E) {
4439 // Don't warn if the operation changed the type.
4440 if (T != E->getType())
4441 return;
4442
4443 // Now look for array decays.
4444 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4445 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4446 return;
4447
4448 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4449 << ICE->getType()
4450 << ICE->getSubExpr()->getType();
4451}
4452
4453/// Check the constraints on expression operands to unary type expression
4454/// and type traits.
4455///
4456/// Completes any types necessary and validates the constraints on the operand
4457/// expression. The logic mostly mirrors the type-based overload, but may modify
4458/// the expression as it completes the type for that expression through template
4459/// instantiation, etc.
4461 UnaryExprOrTypeTrait ExprKind) {
4462 QualType ExprTy = E->getType();
4463 assert(!ExprTy->isReferenceType());
4464
4465 bool IsUnevaluatedOperand =
4466 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4467 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4468 ExprKind == UETT_VecStep);
4469 if (IsUnevaluatedOperand) {
4471 if (Result.isInvalid())
4472 return true;
4473 E = Result.get();
4474 }
4475
4476 // The operand for sizeof and alignof is in an unevaluated expression context,
4477 // so side effects could result in unintended consequences.
4478 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4479 // used to build SFINAE gadgets.
4480 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4481 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4483 !E->getType()->isVariableArrayType() &&
4484 E->HasSideEffects(Context, false))
4485 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4486
4487 if (ExprKind == UETT_VecStep)
4488 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4489 E->getSourceRange());
4490
4491 if (ExprKind == UETT_VectorElements)
4492 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4493 E->getSourceRange());
4494
4495 // Explicitly list some types as extensions.
4496 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4497 E->getSourceRange(), ExprKind))
4498 return false;
4499
4500 // WebAssembly tables are always illegal operands to unary expressions and
4501 // type traits.
4502 if (Context.getTargetInfo().getTriple().isWasm() &&
4504 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4505 << getTraitSpelling(ExprKind);
4506 return true;
4507 }
4508
4509 // 'alignof' applied to an expression only requires the base element type of
4510 // the expression to be complete. 'sizeof' requires the expression's type to
4511 // be complete (and will attempt to complete it if it's an array of unknown
4512 // bound).
4513 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4516 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4517 getTraitSpelling(ExprKind), E->getSourceRange()))
4518 return true;
4519 } else {
4521 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4522 getTraitSpelling(ExprKind), E->getSourceRange()))
4523 return true;
4524 }
4525
4526 // Completing the expression's type may have changed it.
4527 ExprTy = E->getType();
4528 assert(!ExprTy->isReferenceType());
4529
4530 if (ExprTy->isFunctionType()) {
4531 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4532 << getTraitSpelling(ExprKind) << E->getSourceRange();
4533 return true;
4534 }
4535
4536 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4537 E->getSourceRange(), ExprKind))
4538 return true;
4539
4540 if (ExprKind == UETT_SizeOf) {
4541 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4542 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4543 QualType OType = PVD->getOriginalType();
4544 QualType Type = PVD->getType();
4545 if (Type->isPointerType() && OType->isArrayType()) {
4546 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4547 << Type << OType;
4548 Diag(PVD->getLocation(), diag::note_declared_at);
4549 }
4550 }
4551 }
4552
4553 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4554 // decays into a pointer and returns an unintended result. This is most
4555 // likely a typo for "sizeof(array) op x".
4556 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4557 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4558 BO->getLHS());
4559 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4560 BO->getRHS());
4561 }
4562 }
4563
4564 return false;
4565}
4566
4567static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4568 // Cannot know anything else if the expression is dependent.
4569 if (E->isTypeDependent())
4570 return false;
4571
4572 if (E->getObjectKind() == OK_BitField) {
4573 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4574 << 1 << E->getSourceRange();
4575 return true;
4576 }
4577
4578 ValueDecl *D = nullptr;
4579 Expr *Inner = E->IgnoreParens();
4580 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4581 D = DRE->getDecl();
4582 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4583 D = ME->getMemberDecl();
4584 }
4585
4586 // If it's a field, require the containing struct to have a
4587 // complete definition so that we can compute the layout.
4588 //
4589 // This can happen in C++11 onwards, either by naming the member
4590 // in a way that is not transformed into a member access expression
4591 // (in an unevaluated operand, for instance), or by naming the member
4592 // in a trailing-return-type.
4593 //
4594 // For the record, since __alignof__ on expressions is a GCC
4595 // extension, GCC seems to permit this but always gives the
4596 // nonsensical answer 0.
4597 //
4598 // We don't really need the layout here --- we could instead just
4599 // directly check for all the appropriate alignment-lowing
4600 // attributes --- but that would require duplicating a lot of
4601 // logic that just isn't worth duplicating for such a marginal
4602 // use-case.
4603 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4604 // Fast path this check, since we at least know the record has a
4605 // definition if we can find a member of it.
4606 if (!FD->getParent()->isCompleteDefinition()) {
4607 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4608 << E->getSourceRange();
4609 return true;
4610 }
4611
4612 // Otherwise, if it's a field, and the field doesn't have
4613 // reference type, then it must have a complete type (or be a
4614 // flexible array member, which we explicitly want to
4615 // white-list anyway), which makes the following checks trivial.
4616 if (!FD->getType()->isReferenceType())
4617 return false;
4618 }
4619
4620 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4621}
4622
4624 E = E->IgnoreParens();
4625
4626 // Cannot know anything else if the expression is dependent.
4627 if (E->isTypeDependent())
4628 return false;
4629
4630 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4631}
4632
4634 CapturingScopeInfo *CSI) {
4635 assert(T->isVariablyModifiedType());
4636 assert(CSI != nullptr);
4637
4638 // We're going to walk down into the type and look for VLA expressions.
4639 do {
4640 const Type *Ty = T.getTypePtr();
4641 switch (Ty->getTypeClass()) {
4642#define TYPE(Class, Base)
4643#define ABSTRACT_TYPE(Class, Base)
4644#define NON_CANONICAL_TYPE(Class, Base)
4645#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4646#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4647#include "clang/AST/TypeNodes.inc"
4648 T = QualType();
4649 break;
4650 // These types are never variably-modified.
4651 case Type::Builtin:
4652 case Type::Complex:
4653 case Type::Vector:
4654 case Type::ExtVector:
4655 case Type::ConstantMatrix:
4656 case Type::Record:
4657 case Type::Enum:
4658 case Type::TemplateSpecialization:
4659 case Type::ObjCObject:
4660 case Type::ObjCInterface:
4661 case Type::ObjCObjectPointer:
4662 case Type::ObjCTypeParam:
4663 case Type::Pipe:
4664 case Type::BitInt:
4665 llvm_unreachable("type class is never variably-modified!");
4666 case Type::Elaborated:
4667 T = cast<ElaboratedType>(Ty)->getNamedType();
4668 break;
4669 case Type::Adjusted:
4670 T = cast<AdjustedType>(Ty)->getOriginalType();
4671 break;
4672 case Type::Decayed:
4673 T = cast<DecayedType>(Ty)->getPointeeType();
4674 break;
4675 case Type::ArrayParameter:
4676 T = cast<ArrayParameterType>(Ty)->getElementType();
4677 break;
4678 case Type::Pointer:
4679 T = cast<PointerType>(Ty)->getPointeeType();
4680 break;
4681 case Type::BlockPointer:
4682 T = cast<BlockPointerType>(Ty)->getPointeeType();
4683 break;
4684 case Type::LValueReference:
4685 case Type::RValueReference:
4686 T = cast<ReferenceType>(Ty)->getPointeeType();
4687 break;
4688 case Type::MemberPointer:
4689 T = cast<MemberPointerType>(Ty)->getPointeeType();
4690 break;
4691 case Type::ConstantArray:
4692 case Type::IncompleteArray:
4693 // Losing element qualification here is fine.
4694 T = cast<ArrayType>(Ty)->getElementType();
4695 break;
4696 case Type::VariableArray: {
4697 // Losing element qualification here is fine.
4698 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4699
4700 // Unknown size indication requires no size computation.
4701 // Otherwise, evaluate and record it.
4702 auto Size = VAT->getSizeExpr();
4703 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4704 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4705 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4706
4707 T = VAT->getElementType();
4708 break;
4709 }
4710 case Type::FunctionProto:
4711 case Type::FunctionNoProto:
4712 T = cast<FunctionType>(Ty)->getReturnType();
4713 break;
4714 case Type::Paren:
4715 case Type::TypeOf:
4716 case Type::UnaryTransform:
4717 case Type::Attributed:
4718 case Type::BTFTagAttributed:
4719 case Type::SubstTemplateTypeParm:
4720 case Type::MacroQualified:
4721 case Type::CountAttributed:
4722 // Keep walking after single level desugaring.
4723 T = T.getSingleStepDesugaredType(Context);
4724 break;
4725 case Type::Typedef:
4726 T = cast<TypedefType>(Ty)->desugar();
4727 break;
4728 case Type::Decltype:
4729 T = cast<DecltypeType>(Ty)->desugar();
4730 break;
4731 case Type::PackIndexing:
4732 T = cast<PackIndexingType>(Ty)->desugar();
4733 break;
4734 case Type::Using:
4735 T = cast<UsingType>(Ty)->desugar();
4736 break;
4737 case Type::Auto:
4738 case Type::DeducedTemplateSpecialization:
4739 T = cast<DeducedType>(Ty)->getDeducedType();
4740 break;
4741 case Type::TypeOfExpr:
4742 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4743 break;
4744 case Type::Atomic:
4745 T = cast<AtomicType>(Ty)->getValueType();
4746 break;
4747 }
4748 } while (!T.isNull() && T->isVariablyModifiedType());
4749}
4750
4751/// Check the constraints on operands to unary expression and type
4752/// traits.
4753///
4754/// This will complete any types necessary, and validate the various constraints
4755/// on those operands.
4756///
4757/// The UsualUnaryConversions() function is *not* called by this routine.
4758/// C99 6.3.2.1p[2-4] all state:
4759/// Except when it is the operand of the sizeof operator ...
4760///
4761/// C++ [expr.sizeof]p4
4762/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4763/// standard conversions are not applied to the operand of sizeof.
4764///
4765/// This policy is followed for all of the unary trait expressions.
4767 SourceLocation OpLoc,
4768 SourceRange ExprRange,
4769 UnaryExprOrTypeTrait ExprKind,
4770 StringRef KWName) {
4771 if (ExprType->isDependentType())
4772 return false;
4773
4774 // C++ [expr.sizeof]p2:
4775 // When applied to a reference or a reference type, the result
4776 // is the size of the referenced type.
4777 // C++11 [expr.alignof]p3:
4778 // When alignof is applied to a reference type, the result
4779 // shall be the alignment of the referenced type.
4780 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4781 ExprType = Ref->getPointeeType();
4782
4783 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4784 // When alignof or _Alignof is applied to an array type, the result
4785 // is the alignment of the element type.
4786 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4787 ExprKind == UETT_OpenMPRequiredSimdAlign)
4788 ExprType = Context.getBaseElementType(ExprType);
4789
4790 if (ExprKind == UETT_VecStep)
4791 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4792
4793 if (ExprKind == UETT_VectorElements)
4794 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4795 ExprRange);
4796
4797 // Explicitly list some types as extensions.
4798 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4799 ExprKind))
4800 return false;
4801
4803 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4804 KWName, ExprRange))
4805 return true;
4806
4807 if (ExprType->isFunctionType()) {
4808 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4809 return true;
4810 }
4811
4812 // WebAssembly tables are always illegal operands to unary expressions and
4813 // type traits.
4814 if (Context.getTargetInfo().getTriple().isWasm() &&
4815 ExprType->isWebAssemblyTableType()) {
4816 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4817 << getTraitSpelling(ExprKind);
4818 return true;
4819 }
4820
4821 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4822 ExprKind))
4823 return true;
4824
4825 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4826 if (auto *TT = ExprType->getAs<TypedefType>()) {
4827 for (auto I = FunctionScopes.rbegin(),
4828 E = std::prev(FunctionScopes.rend());
4829 I != E; ++I) {
4830 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4831 if (CSI == nullptr)
4832 break;
4833 DeclContext *DC = nullptr;
4834 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4835 DC = LSI->CallOperator;
4836 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4837 DC = CRSI->TheCapturedDecl;
4838 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4839 DC = BSI->TheDecl;
4840 if (DC) {
4841 if (DC->containsDecl(TT->getDecl()))
4842 break;
4843 captureVariablyModifiedType(Context, ExprType, CSI);
4844 }
4845 }
4846 }
4847 }
4848
4849 return false;
4850}
4851
4852/// Build a sizeof or alignof expression given a type operand.
4854 SourceLocation OpLoc,
4855 UnaryExprOrTypeTrait ExprKind,
4856 SourceRange R) {
4857 if (!TInfo)
4858 return ExprError();
4859
4860 QualType T = TInfo->getType();
4861
4862 if (!T->isDependentType() &&
4863 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4864 getTraitSpelling(ExprKind)))
4865 return ExprError();
4866
4867 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4868 // properly deal with VLAs in nested calls of sizeof and typeof.
4869 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4870 TInfo->getType()->isVariablyModifiedType())
4871 TInfo = TransformToPotentiallyEvaluated(TInfo);
4872
4873 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4874 return new (Context) UnaryExprOrTypeTraitExpr(
4875 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4876}
4877
4878/// Build a sizeof or alignof expression given an expression
4879/// operand.
4882 UnaryExprOrTypeTrait ExprKind) {
4884 if (PE.isInvalid())
4885 return ExprError();
4886
4887 E = PE.get();
4888
4889 // Verify that the operand is valid.
4890 bool isInvalid = false;
4891 if (E->isTypeDependent()) {
4892 // Delay type-checking for type-dependent expressions.
4893 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4894 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4895 } else if (ExprKind == UETT_VecStep) {
4897 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4898 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4899 isInvalid = true;
4900 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4901 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4902 isInvalid = true;
4903 } else if (ExprKind == UETT_VectorElements) {
4904 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4905 } else {
4907 }
4908
4909 if (isInvalid)